forked from saltcorn/copilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuilder-gen.js
More file actions
1711 lines (1576 loc) · 57.2 KB
/
Copy pathbuilder-gen.js
File metadata and controls
1711 lines (1576 loc) · 57.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { getState } = require("@saltcorn/data/db/state");
const Table = require("@saltcorn/data/models/table");
const Trigger = require("@saltcorn/data/models/trigger");
const View = require("@saltcorn/data/models/view");
const { edit_build_in_actions } = require("@saltcorn/data/viewable_fields");
const { buildBuilderSchema } = require("./builder-schema");
const { getLlmConfigurationSafe, canUseResponseFormat } = require("./common");
const { build_schema_data } = require("@saltcorn/data/plugin-helper");
const {
GET_RELATION_PATHS_FUNCTION,
getRelationPaths,
getRelationPathsForPairs,
pickBestRelation,
} = require("./relation-paths");
const ACTION_SIZES = ["btn-sm", "btn-lg"];
// ── Edit-mode guidance blocks ─────────────────────────────────────────────────
const EDIT_FIELD_INCLUSION = `\
Layout is a form for editing a single row. \
Include ALL non-primary-key, non-calculated fields from the table as inputs — \
not just fields mentioned in the task description. \
Never include calculated fields (aggregations, derived values) in an edit form — they are read-only. \
The only fields that may be omitted are FK fields to the users table that are explicitly \
designated as ownership fields (set automatically from the logged-in user). \
All other foreign key fields — including parent-context keys like trip_id — MUST appear as \
selector inputs; Saltcorn auto-fills them from the URL state when opened in context.`;
const {
fieldview_selection_rules: EDIT_FIELDVIEW_SELECTION,
} = require("./app-constructor/fixed-prompts");
const EDIT_LAYOUT_STRUCTURE = `\
Every field MUST be preceded by a label. \
Use a blank segment with the field's label text immediately above each field inside an above array, like: \
{"above": [{"type":"blank","contents":"Field Label","class":""}, {"type":"field","field_name":"...","fieldview":"edit"}]}. \
Alternatively wrap groups of fields in a card with a descriptive title.`;
const EDIT_ACTIONS = `\
Use edit fieldviews, group related inputs, and finish with a row of actions: \
a Save button (action_name "Save", style "btn btn-primary") and \
a Cancel button (action_name "GoBack", style "btn btn-outline-secondary"). \
To add a trigger button, add an extra action segment with action_name set to the trigger's name \
exactly as it appears in the available actions list (ctx.actions).`;
// ── Show-mode guidance blocks ─────────────────────────────────────────────────
const SHOW_PURPOSE = `\
Layout displays one record read-only. \
Use show fieldviews only (e.g. "show", "as_text", "showDay").`;
const SHOW_NO_EDIT_FIELDVIEWS = `\
A show layout is read-only and must never use edit fieldviews \
(textarea, edit, input, select) — those are for form inputs, not display.`;
const SHOW_LABELS = `\
Every field MUST be preceded by a label using a blank segment or \
grouped in a card with a descriptive title.`;
// ── List-columns guidance blocks ──────────────────────────────────────────────
const LISTCOLUMNS_STRUCTURE = `\
Layout defines list columns for a list view. \
Use a list_columns wrapper with besides entries containing list_column segments. \
Each list_column has a header_label for the column heading — \
do NOT add any blank or label segment inside a list_column. \
Typically each list_column contains a single field, action, or view_link.`;
const LISTCOLUMNS_FIELDVIEWS = `\
Include all meaningful fields as columns, including foreign key fields. \
For a foreign key field use fieldview "show" so the related record's label is displayed rather than a raw ID. \
For string/text fields use fieldview "as_text" or "show" by default; \
only use "show_with_html" when the task explicitly requires rendering HTML content.`;
const LISTCOLUMNS_VIEW_LINK = `\
A view_link that opens the detail of a row MUST point to a Show-type view (viewtemplate "Show"). \
Only include such a view_link if a Show view for this table is listed in the available views. \
Every view_link requires a "relation" string — you MUST call get_relation_paths before generating the layout \
whenever the layout will contain any view_link or embedded view segment.`;
// ── Composed MODE_GUIDANCE ────────────────────────────────────────────────────
const MODE_GUIDANCE = {
edit: [
EDIT_FIELD_INCLUSION,
EDIT_ACTIONS,
EDIT_FIELDVIEW_SELECTION,
EDIT_LAYOUT_STRUCTURE,
].join(" "),
show: [SHOW_PURPOSE, SHOW_NO_EDIT_FIELDVIEWS, SHOW_LABELS].join(" "),
list: "Layout represents a single row in a list. Highlight key fields, keep actions compact, and support filtering if requested.",
listcolumns: [
LISTCOLUMNS_STRUCTURE,
LISTCOLUMNS_FIELDVIEWS,
LISTCOLUMNS_VIEW_LINK,
].join(" "),
filter:
"Layout lets users define filters. Provide appropriate filter inputs plus an action to run or reset filters.",
page: "Layout builds a general app page. Combine hero text, cards, containers, and call-to-action buttons.",
default:
"Use Saltcorn layout primitives (above, besides, container, card, tabs, blank, field, action, view_link, view). Do not return HTML snippets.",
};
const stripCodeFences = (text) => text.replace(/```(?:json)?/gi, "").trim();
const stripHtmlTags = (text) =>
String(text || "")
.replace(/<script[\s\S]*?<\/script>/gi, " ")
.replace(/<style[\s\S]*?<\/style>/gi, " ")
.replace(/<[^>]+>/g, " ")
.replace(/\s+/g, " ")
.trim();
const attrValue = (node, key) => {
if (!node) return undefined;
if (Object.prototype.hasOwnProperty.call(node, key)) return node[key];
if (
node.attributes &&
Object.prototype.hasOwnProperty.call(node.attributes, key)
)
return node.attributes[key];
return undefined;
};
const pickAttrValue = (node, keys) => {
for (const key of keys) {
const val = attrValue(node, key);
if (val !== undefined) return val;
}
return undefined;
};
const firstItem = (value) => (Array.isArray(value) ? value[0] : value);
const findBalancedBlock = (text, openChar, closeChar) => {
const start = text.indexOf(openChar);
if (start === -1) return null;
let depth = 0;
let inString = false;
let escape = false;
for (let i = start; i < text.length; i++) {
const ch = text[i];
if (inString) {
if (escape) escape = false;
else if (ch === "\\") escape = true;
else if (ch === '"') inString = false;
continue;
}
if (ch === '"') {
inString = true;
continue;
}
if (ch === openChar) depth++;
else if (ch === closeChar) {
depth--;
if (depth === 0) return text.slice(start, i + 1);
}
}
return null;
};
const extractJsonStructure = (text) => {
if (!text) return null;
const cleaned = stripCodeFences(String(text));
const attempt = (candidate) => {
if (!candidate) return null;
try {
return JSON.parse(candidate);
} catch (err) {
return null;
}
};
const trimmed = cleaned.trim();
let parsed = attempt(trimmed);
if (parsed) return parsed;
const eqIdx = trimmed.indexOf("=");
if (eqIdx !== -1) {
parsed = attempt(trimmed.slice(eqIdx + 1).trim());
if (parsed) return parsed;
}
const arrayBlock = findBalancedBlock(trimmed, "[", "]");
if (arrayBlock) {
parsed = attempt(arrayBlock);
if (parsed) return parsed;
}
const objectBlock = findBalancedBlock(trimmed, "{", "}");
if (objectBlock) {
parsed = attempt(objectBlock);
if (parsed) return parsed;
}
return null;
};
const getSchemaByRef = (root, ref) => {
if (!ref || typeof ref !== "string" || !ref.startsWith("#/")) return null;
const parts = ref
.slice(2)
.split("/")
.map((part) => part.replace(/~1/g, "/").replace(/~0/g, "~"));
let current = root;
for (const part of parts) {
if (!current || typeof current !== "object") return null;
current = current[part];
}
return current || null;
};
const validateSchemaRefs = (schema) => {
const missing = [];
const walk = (node) => {
if (!node || typeof node !== "object") return;
if (Array.isArray(node)) {
node.forEach((item) => walk(item));
return;
}
if (typeof node.$ref === "string") {
const target = getSchemaByRef(schema, node.$ref);
if (!target) missing.push(node.$ref);
}
for (const key of Object.keys(node)) walk(node[key]);
};
walk(schema);
if (missing.length) {
throw new Error(`Schema $ref targets not found: ${missing.join(", ")}`);
}
};
const schemaHasRef = (schema) => {
let found = false;
const walk = (node) => {
if (found || !node || typeof node !== "object") return;
if (Array.isArray(node)) {
node.forEach((item) => walk(item));
return;
}
if (typeof node.$ref === "string") {
found = true;
return;
}
Object.keys(node).forEach((key) => walk(node[key]));
};
walk(schema);
return found;
};
const derefSchema = (schema, maxDepth = 3) => {
const root = JSON.parse(JSON.stringify(schema));
const expand = (node, stack) => {
if (!node || typeof node !== "object") return node;
if (Array.isArray(node)) return node.map((item) => expand(item, stack));
if (typeof node.$ref === "string") {
if (stack.length >= maxDepth) {
return { $ref: node.$ref };
}
if (stack.includes(node.$ref)) {
return { $ref: node.$ref };
}
const target = getSchemaByRef(root, node.$ref);
if (!target) throw new Error(`Schema $ref not found: ${node.$ref}`);
return expand({ ...target }, [...stack, node.$ref]);
}
const out = {};
for (const key of Object.keys(node)) {
if (key === "$ref") continue;
out[key] = expand(node[key], stack);
}
return out;
};
return expand(root, []);
};
const simplifySchemaForLlm = (schema) => {
const deref = derefSchema(schema, 2); // Reduced maxDepth
const scrub = (node, keyName, depth = 0) => {
if (!node || typeof node !== "object" || depth > 4) {
// Added depth limit
if (
keyName === "contents" ||
keyName === "besides" ||
keyName === "above"
)
return {
type: "string",
description: "Simplified content: a string or a basic segment.",
};
return node;
}
if (Array.isArray(node))
return node.map((item) => scrub(item, undefined, depth + 1));
if (keyName === "style") {
return {
type: "string",
description: "CSS style string (e.g. background-color: red;).",
};
}
if (typeof node.$ref === "string") {
return {
type: "object",
description: "Simplified recursive segment.",
additionalProperties: false,
};
}
const out = {};
for (const [key, val] of Object.entries(node)) {
if (key === "$defs" || key === "definitions") continue;
out[key] = scrub(val, key, depth + 1);
}
const nodeType = out.type;
const isObjectType =
nodeType === "object" ||
(Array.isArray(nodeType) && nodeType.includes("object")) ||
Object.prototype.hasOwnProperty.call(out, "properties");
const isArrayType =
nodeType === "array" ||
(Array.isArray(nodeType) && nodeType.includes("array")) ||
Object.prototype.hasOwnProperty.call(out, "items");
const isNumberType =
nodeType === "number" ||
nodeType === "integer" ||
(Array.isArray(nodeType) &&
(nodeType.includes("number") || nodeType.includes("integer")));
if (isObjectType) {
out.additionalProperties = false;
}
if (isArrayType && typeof out.minItems !== "undefined") {
const minItems = Number(out.minItems);
if (Number.isFinite(minItems) && minItems > 1) out.minItems = 1;
}
if (isNumberType) {
delete out.minimum;
delete out.maximum;
delete out.exclusiveMinimum;
delete out.exclusiveMaximum;
delete out.multipleOf;
}
return out;
};
return scrub(deref);
};
const countOptionalParams = (schema) => {
let count = 0;
const walk = (node) => {
if (!node || typeof node !== "object") return;
if (Array.isArray(node)) {
node.forEach(walk);
return;
}
const props = node.properties;
if (props && typeof props === "object") {
const required = Array.isArray(node.required) ? node.required : [];
const optional = Object.keys(props).filter(
(key) => !required.includes(key)
);
count += optional.length;
Object.values(props).forEach(walk);
}
if (node.items) walk(node.items);
if (node.anyOf) node.anyOf.forEach(walk);
if (node.oneOf) node.oneOf.forEach(walk);
if (node.allOf) node.allOf.forEach(walk);
};
walk(schema);
return count;
};
const trimOptionalProperties = (schema, maxOptional) => {
if (!schema || typeof schema !== "object") return schema;
const clonedSchema = JSON.parse(JSON.stringify(schema));
let optionalCount = countOptionalParams(clonedSchema);
if (optionalCount <= maxOptional) {
return clonedSchema;
}
const optionalPropsByNode = new Map();
const findOptional = (node, path = []) => {
if (!node || typeof node !== "object") return;
if (Array.isArray(node)) {
node.forEach((item, i) => findOptional(item, [...path, i]));
return;
}
const props = node.properties;
if (props && typeof props === "object") {
const required = new Set(node.required || []);
const optionalKeys = Object.keys(props).filter((k) => !required.has(k));
if (optionalKeys.length > 0) {
optionalPropsByNode.set(node, optionalKeys);
}
Object.values(props).forEach((propNode) => findOptional(propNode));
}
if (node.items) findOptional(node.items, [...path, "items"]);
if (node.anyOf)
node.anyOf.forEach((item, i) =>
findOptional(item, [...path, "anyOf", i])
);
if (node.oneOf)
node.oneOf.forEach((item, i) =>
findOptional(item, [...path, "oneOf", i])
);
if (node.allOf)
node.allOf.forEach((item, i) =>
findOptional(item, [...path, "allOf", i])
);
};
findOptional(clonedSchema);
const nodesWithOptionals = Array.from(optionalPropsByNode.keys());
let nodeIndex = 0;
while (optionalCount > maxOptional && nodeIndex < nodesWithOptionals.length) {
const node = nodesWithOptionals[nodeIndex];
const optionalKeys = optionalPropsByNode.get(node);
if (optionalKeys && optionalKeys.length > 0) {
const keyToRemove = optionalKeys.pop();
delete node.properties[keyToRemove];
optionalCount--;
} else {
nodeIndex++;
}
}
return clonedSchema;
};
const randomId = () =>
Math.floor(Math.random() * 0xffffff)
.toString(16)
.padStart(6, "0");
const toCamelCaseStyle = (key) =>
key.replace(/-([a-z])/g, (_m, chr) => chr.toUpperCase());
const parseStyleString = (styleStr) => {
if (typeof styleStr !== "string") return styleStr;
const trimmed = styleStr.trim();
if (!trimmed) return {};
if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
try {
const parsed = JSON.parse(trimmed);
return parsed && typeof parsed === "object" ? parsed : {};
} catch (err) {
// fall through to CSS parsing
}
}
const out = {};
trimmed.split(";").forEach((part) => {
const section = part.trim();
if (!section) return;
const idx = section.indexOf(":");
if (idx === -1) return;
const rawKey = section.slice(0, idx).trim();
const value = section.slice(idx + 1).trim();
if (!rawKey || !value) return;
if (rawKey.startsWith("--")) out[rawKey] = value;
else out[toCamelCaseStyle(rawKey)] = value;
});
return out;
};
const ensureArray = (value) =>
Array.isArray(value) ? value : value == null ? [] : [value];
const prettifyActionName = (name) =>
(name || "")
.replace(/_/g, " ")
.replace(/([a-z])([A-Z])/g, "$1 $2")
.replace(/\s+/g, " ")
.trim();
// Picks a valid fieldview from the field's available fieldviews only.
// Never returns a fieldview that doesn't exist in field.fieldviews
const pickFieldview = (field, mode, requestedFieldview = null) => {
const isEditMode = mode === "edit" || mode === "filter";
const availableViews = isEditMode
? field?.editFieldviews || field?.fieldviews || []
: field?.fieldviews || [];
// If no available fieldviews, return the first one or a safe default
if (!availableViews.length) {
// Return the first available or fall back based on mode
return mode === "edit" || mode === "filter" ? "edit" : "show";
}
// Helper to validate and return a fieldview only if it exists (exact match only)
const validateAndReturn = (candidate) => {
if (!candidate) return null;
const lower = String(candidate).toLowerCase();
return (
availableViews.find((fv) => String(fv).toLowerCase() === lower) || null
);
};
// Edit-only fieldviews must never be used in show/list modes
const EDIT_ONLY_FIELDVIEWS = new Set(["textarea", "edit", "input", "select"]);
const isShowMode =
mode === "show" || mode === "list" || mode === "listcolumns";
// For date fields in edit mode: flatpickr is always preferred (handles all date types).
// Only fall back to edit_day when day_only=true and flatpickr is not installed.
const fieldTypeLower = String(field?.type || "").toLowerCase();
const isDateField =
(mode === "edit" || mode === "filter") &&
(fieldTypeLower === "date" || fieldTypeLower.includes("date"));
if (isDateField) {
const flatpickrMatch = availableViews.find(
(fv) => String(fv).toLowerCase() === "flatpickr"
);
if (flatpickrMatch) return flatpickrMatch;
if (field?.attributes?.day_only) {
const dayMatch = availableViews.find(
(fv) => String(fv).toLowerCase() === "edit_day"
);
if (dayMatch) return dayMatch;
}
}
// Fields with fixed options (options attribute) always use plain select, never select_by_code
if ((mode === "edit" || mode === "filter") && field?.attributes?.options) {
const selectMatch = availableViews.find(
(fv) => String(fv).toLowerCase() === "select"
);
if (selectMatch) return selectMatch;
}
// If a specific fieldview was requested by the user, try to honor it
// but ONLY if it actually exists in available views and is appropriate for the mode
if (requestedFieldview) {
if (
isShowMode &&
EDIT_ONLY_FIELDVIEWS.has(String(requestedFieldview).toLowerCase())
) {
// Fall through to show-mode defaults — don't use edit fieldviews in show context
} else {
const validated = validateAndReturn(requestedFieldview);
if (validated) return validated;
// Requested fieldview not available for this field - fall through to defaults
}
}
// Get the field's configured default fieldview
const defaultFieldview =
field?.default_fieldview || field?.defaultFieldview || field?.fieldview;
if (defaultFieldview) {
const validated = validateAndReturn(defaultFieldview);
if (validated) return validated;
}
// Mode-based selection from available fieldviews
if (mode === "show" || mode === "list" || mode === "listcolumns") {
// For show mode, prefer simple text-based views, but only from available views
const showPreferences = ["as_text", "show", "as_string", "text", "showas"];
for (const pref of showPreferences) {
const match = availableViews.find(
(fv) => String(fv).toLowerCase() === pref
);
if (match) return match;
}
} else if (mode === "edit" || mode === "filter") {
// For edit mode, prefer edit-capable fieldviews from available views (exact match)
const editPreferences = ["edit", "input", "select", "textarea"];
for (const pref of editPreferences) {
const match = availableViews.find(
(fv) => String(fv).toLowerCase() === pref
);
if (match) return match;
}
}
// Fall back to first available fieldview - this is always valid
return availableViews[0];
};
const evenWidths = (count) => {
if (!count) return [];
const widths = Array(count).fill(Math.max(1, Math.floor(12 / count)));
let total = widths.reduce((sum, n) => sum + n, 0);
let idx = 0;
while (total < 12) {
widths[idx] += 1;
total += 1;
idx = (idx + 1) % count;
}
while (total > 12 && widths.some((w) => w > 1)) {
if (widths[idx] > 1) {
widths[idx] -= 1;
total -= 1;
}
idx = (idx + 1) % count;
}
return widths;
};
const normalizeWidths = (current, count) => {
if (!count) return [];
if (Array.isArray(current) && current.length === count) {
const sanitized = current.map((val) => {
const num = Number(val);
return Number.isFinite(num) && num > 0
? Math.min(12, Math.round(num))
: null;
});
if (sanitized.every((n) => n && n > 0)) {
const total = sanitized.reduce((sum, n) => sum + n, 0);
if (total === 12) return sanitized;
}
}
return evenWidths(count);
};
const parseJsonPayload = (raw) => {
if (raw == null) throw new Error("Empty response from LLM");
if (typeof raw === "object") return raw;
const cleaned = stripCodeFences(String(raw));
const extracted = extractJsonStructure(cleaned);
if (extracted) return extracted;
throw new Error("Could not parse JSON payload from LLM response");
};
const normalizeChild = (value, ctx) => {
if (value == null) return null;
if (typeof value === "string") return { type: "blank", contents: value };
return normalizeSegment(value, ctx);
};
const normalizeTabs = (tabs, ctx) =>
ensureArray(tabs)
.map((tab) => ({ ...tab, contents: normalizeChild(tab?.contents, ctx) }))
.filter((tab) => tab?.title && tab.contents)
.map((tab) => ({ ...tab, class: tab.class || "" }));
const normalizeSegment = (segment, ctx) => {
if (segment == null) return null;
if (typeof segment === "string") return { type: "blank", contents: segment };
if (Array.isArray(segment)) {
const arr = segment
.map((child) => normalizeSegment(child, ctx))
.filter(Boolean);
return arr.length ? arr : null;
}
if (typeof segment !== "object") return null;
const clone = { ...segment };
if (typeof clone.style === "string") {
clone.style = parseStyleString(clone.style);
}
if (clone.type === "prompt") return null;
if ((!clone.type || clone.type === "stack") && clone.above) {
const above = ensureArray(clone.above)
.map((child) => normalizeSegment(child, ctx))
.filter(Boolean);
return above.length ? { ...clone, above } : null;
}
if (!clone.type && clone.besides) {
const besides = ensureArray(clone.besides).map((child) =>
child == null ? null : normalizeSegment(child, ctx)
);
if (!besides.some((child) => child)) return null;
return {
...clone,
besides,
widths: normalizeWidths(clone.widths, besides.length),
};
}
// Handle {columns: {besides: [...], widths: [...]}} wrapper the LLM sometimes emits
if (!clone.type && clone.columns?.besides) {
const inner = clone.columns;
const besides = ensureArray(inner.besides).map((child) =>
child == null ? null : normalizeSegment(child, ctx)
);
if (!besides.some(Boolean)) return null;
return {
besides,
widths: normalizeWidths(inner.widths, besides.length),
};
}
switch (clone.type) {
case "columns":
case "row":
case "grid": {
// LLM uses these as a besides wrapper with widths
if (clone.besides) {
const besides = ensureArray(clone.besides).map((child) =>
child == null ? null : normalizeSegment(child, ctx)
);
if (!besides.some(Boolean)) return null;
return {
besides,
widths: normalizeWidths(clone.widths, besides.length),
};
}
// fall through to container-like handling if no besides
const contents = normalizeChild(clone.contents, ctx);
return contents ? { ...clone, contents } : null;
}
case "container": {
const contents = normalizeChild(clone.contents, ctx);
return contents
? {
...clone,
contents,
class: clone.class || "",
customClass: clone.customClass || "",
}
: null;
}
case "card": {
const contents = normalizeChild(clone.contents, ctx);
return contents
? {
...clone,
contents,
title: clone.title || "",
class: clone.class || "",
}
: null;
}
case "tabs": {
const tabs = normalizeTabs(clone.tabs, ctx);
if (!tabs.length) return null;
const titles = clone.titles ?? tabs.map((t) => t.title || "");
const contents = clone.contents ?? tabs.map((t) => t.contents);
return { ...clone, tabs, titles, contents, class: clone.class || "" };
}
case "blank":
return {
...clone,
contents: typeof clone.contents === "string" ? clone.contents : "",
class: clone.class || "",
};
case "line_break":
return { type: "line_break", class: clone.class || "" };
case "image":
return clone.url || clone.src
? {
...clone,
url: clone.url || clone.src || "",
alt: clone.alt || "",
class: clone.class || "",
}
: null;
case "link":
return clone.url
? {
...clone,
text: clone.text || clone.url,
link_style: clone.link_style || "",
class: clone.class || "",
}
: null;
case "search_bar":
return { ...clone, class: clone.class || "" };
case "view":
if (!ctx.viewNames.length) return null;
return {
...clone,
view: ctx.viewNames.includes(clone.view)
? clone.view
: ctx.viewNames[0],
state: clone.state || {},
class: clone.class || "",
};
case "view_link": {
if (!ctx.viewNames.length) return null;
const resolvedView = ctx.viewNames.includes(clone.view)
? clone.view
: ctx.viewNames[0];
let relation = clone.relation;
if (!relation && ctx.table && ctx.schemaData) {
try {
const relations = getRelationPaths(
ctx.table.name,
resolvedView,
ctx.schemaData
);
if (relations.length > 0) {
const picked = pickBestRelation(relations);
if (picked) relation = picked.relationString;
}
} catch (e) {
console.error("view_link relation lookup failed:", e.message);
}
}
// Convert {{ expr }} template syntax to isFormula.label: true with JS expression
let viewLabel = clone.view_label || clone.view;
let isFormula = clone.isFormula || {};
const tmplMatch =
typeof viewLabel === "string" &&
viewLabel.match(/^\{\{\s*(.+?)\s*\}\}$/);
if (tmplMatch) {
viewLabel = tmplMatch[1];
isFormula = { ...isFormula, label: true };
}
return {
...clone,
view: resolvedView,
view_label: viewLabel,
link_style: clone.link_style || "",
class: clone.class || "",
isFormula,
...(relation ? { relation } : {}),
};
}
case "field": {
if (!ctx.fields.length) return null;
const fieldMeta = ctx.fieldMap[clone.field_name] || ctx.fields[0];
// Use pickFieldview which validates that the fieldview exists in fieldMeta.fieldviews
// If clone.fieldview is invalid, pickFieldview will return a valid alternative
const validFieldview = pickFieldview(
fieldMeta,
ctx.mode,
clone.fieldview
);
return {
...clone,
field_name: fieldMeta.name,
fieldview: validFieldview,
configuration: clone.configuration || {},
class: clone.class || "",
};
}
case "list_columns": {
const besides = ensureArray(clone.besides).map((child) =>
child == null ? null : normalizeSegment(child, ctx)
);
if (!besides.some(Boolean)) return null;
// Drop 'type' — List viewtemplate expects { besides, list_columns: true } with no type field
const { type: _t, ...rest } = clone;
return { ...rest, besides, list_columns: true };
}
case "list_column": {
let raw = clone.contents;
// Saltcorn's list renderer handles `above` in a cell (wraps in Container)
// but silently drops a typeless `besides`. Convert it so both links render
// stacked in one column rather than disappearing.
if (raw && !raw.type && Array.isArray(raw.besides)) {
raw = { above: raw.besides };
}
const contents = normalizeChild(raw, ctx);
return contents
? { ...clone, contents, header_label: clone.header_label || "" }
: null;
}
case "action": {
if (!ctx.actions.length) return null;
const actionName = ctx.actions.includes(clone.action_name)
? clone.action_name
: ctx.actions[0];
return {
...clone,
action_name: actionName,
action_label: clone.action_label || prettifyActionName(actionName),
action_style: clone.action_style || "btn-primary",
action_size: ACTION_SIZES.includes(clone.action_size)
? clone.action_size
: undefined,
rndid: clone.rndid || randomId(),
minRole: clone.minRole || 100,
nsteps: clone.nsteps || 1,
isFormula: clone.isFormula || {},
configuration: clone.configuration || {},
class: clone.class || "",
};
}
default: {
if (clone.children) {
const childSegments = ensureArray(clone.children)
.map((child) => normalizeSegment(child, ctx))
.filter(Boolean);
if (childSegments.length === 1) return childSegments[0];
if (childSegments.length > 1) return { above: childSegments };
}
if (clone.contents) {
const contents = normalizeChild(clone.contents, ctx);
return contents ? { ...clone, contents } : null;
}
return null;
}
}
};
const collectSegments = (segment, out = []) => {
if (segment == null) return out;
if (Array.isArray(segment)) {
segment.forEach((s) => collectSegments(s, out));
return out;
}
if (typeof segment !== "object") return out;
out.push(segment);
if (segment.above) collectSegments(segment.above, out);
if (segment.besides) collectSegments(segment.besides, out);
if (segment.contents) collectSegments(segment.contents, out);
if (segment.tabs) {
ensureArray(segment.tabs).forEach((tab) =>
collectSegments(tab.contents, out)
);
}
return out;
};
// margin/padding must be [top, right, bottom, left] - saltcorn-markup's
// renderer calls .every()/.map() on them and crashes on a bare string/number.
const fixBoxModel = (value) => {
if (value == null) return undefined;
if (Array.isArray(value))
return value.length === 4
? value
: [0, 1, 2, 3].map((i) => value[i] ?? value[0] ?? 0);
if (typeof value === "string" || typeof value === "number")
return [value, value, value, value];
return undefined;
};
// Recursively fixes margin/padding shape, with no HTML stripping - used
// internally by sanitizeLayout below.
const fixLayoutBoxModel = (segment) => {
if (segment == null) return segment;
if (Array.isArray(segment)) return segment.map(fixLayoutBoxModel);
if (typeof segment !== "object") return segment;
const clone = { ...segment };
if (clone.margin !== undefined) {
const fixed = fixBoxModel(clone.margin);
if (fixed) clone.margin = fixed;
else delete clone.margin;
}
if (clone.padding !== undefined) {
const fixed = fixBoxModel(clone.padding);
if (fixed) clone.padding = fixed;
else delete clone.padding;
}
if (clone.contents !== undefined)
clone.contents = fixLayoutBoxModel(clone.contents);
if (clone.above !== undefined) clone.above = fixLayoutBoxModel(clone.above);
if (clone.besides !== undefined)
clone.besides = fixLayoutBoxModel(clone.besides);
if (clone.tabs !== undefined)
clone.tabs = ensureArray(clone.tabs).map((tab) => ({
...tab,
contents: fixLayoutBoxModel(tab?.contents),
}));
return clone;
};
// Pre-save fixes for callers that must not otherwise change the layout.
const sanitizeLayout = (layout) => fixLayoutBoxModel(layout);
const sanitizeNoHtmlSegments = (segment) => {
if (segment == null) return segment;
if (Array.isArray(segment))
return segment
.map((child) => sanitizeNoHtmlSegments(child))
.filter(Boolean);
if (typeof segment !== "object") return segment;
const clone = { ...segment };
if (clone.type === "blank") {
const usedHtml = !!clone.isHTML;
delete clone.isHTML;
delete clone.text_strings;
if (usedHtml && typeof clone.contents === "string") {
clone.contents = stripHtmlTags(clone.contents);
}
}
if (clone.margin !== undefined) {
const fixed = fixBoxModel(clone.margin);
if (fixed) clone.margin = fixed;
else delete clone.margin;
}
if (clone.padding !== undefined) {
const fixed = fixBoxModel(clone.padding);
if (fixed) clone.padding = fixed;
else delete clone.padding;
}
if (clone.contents !== undefined)
clone.contents = sanitizeNoHtmlSegments(clone.contents);
if (clone.above !== undefined)
clone.above = sanitizeNoHtmlSegments(clone.above);
if (clone.besides !== undefined)