@usethrottle/builder-schema 0.0.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -0
- package/dist/index.cjs +3530 -218
- package/dist/index.d.cts +494 -2
- package/dist/index.d.ts +494 -2
- package/dist/index.js +3528 -216
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -25,10 +25,37 @@ var ISSUE_CODES = [
|
|
|
25
25
|
"UNSUPPORTED_SCHEMA_VERSION",
|
|
26
26
|
"INVALID_WIDGET_TYPE",
|
|
27
27
|
"INVALID_COLUMN_WIDTHS",
|
|
28
|
-
"INNER_IN_INNER"
|
|
28
|
+
"INNER_IN_INNER",
|
|
29
29
|
// <task-8>
|
|
30
|
+
"SECTION_NOT_NESTABLE",
|
|
31
|
+
"INNER_NOT_TOP_LEVEL",
|
|
32
|
+
"COLUMN_LIMIT",
|
|
33
|
+
"NOT_ALLOWED_IN_PART",
|
|
34
|
+
"MOVE_INTO_SELF",
|
|
35
|
+
"COLUMN_REMOVE_NEEDS_SETCOLUMNS",
|
|
36
|
+
"COLUMN_NOT_EMPTY",
|
|
37
|
+
"UNKNOWN_PROP",
|
|
38
|
+
"SOURCE_NOT_ENABLED",
|
|
39
|
+
"RESULT_TYPE_MISMATCH",
|
|
40
|
+
"ID_NOT_FRESH",
|
|
41
|
+
"NODE_NOT_FOUND",
|
|
30
42
|
// </task-8>
|
|
31
43
|
// <task-9>
|
|
44
|
+
"TEMPLATE_SYNTAX",
|
|
45
|
+
"TEMPLATE_FORBIDDEN",
|
|
46
|
+
"ELEMENT_NOT_ALLOWED",
|
|
47
|
+
"ATTRIBUTE_NOT_ALLOWED",
|
|
48
|
+
"FIELD_NOT_ALLOWED",
|
|
49
|
+
"UNKNOWN_REFERENCE",
|
|
50
|
+
"CSS_SYNTAX",
|
|
51
|
+
"CSS_FORBIDDEN",
|
|
52
|
+
"CSS_PROPERTY_NOT_ALLOWED",
|
|
53
|
+
"NO_RECURSION",
|
|
54
|
+
"BINDING_TARGET_MISSING",
|
|
55
|
+
"BINDING_TYPE_MISMATCH",
|
|
56
|
+
"WIDGET_TOO_LARGE",
|
|
57
|
+
"DUPLICATE_KEY",
|
|
58
|
+
"VERSION_RULE"
|
|
32
59
|
// </task-9>
|
|
33
60
|
];
|
|
34
61
|
var MAX_ISSUES = 50;
|
|
@@ -51,43 +78,43 @@ function capIssues(issues) {
|
|
|
51
78
|
return issues.length > MAX_ISSUES ? issues.slice(0, MAX_ISSUES) : issues;
|
|
52
79
|
}
|
|
53
80
|
var KNOWN_CODES = new Set(ISSUE_CODES);
|
|
54
|
-
function codeFor(
|
|
55
|
-
if (
|
|
56
|
-
const params =
|
|
81
|
+
function codeFor(issue2) {
|
|
82
|
+
if (issue2.code === "custom") {
|
|
83
|
+
const params = issue2.params;
|
|
57
84
|
if (typeof params?.code === "string" && KNOWN_CODES.has(params.code)) {
|
|
58
85
|
return params.code;
|
|
59
86
|
}
|
|
60
87
|
return "INVALID_VALUE";
|
|
61
88
|
}
|
|
62
|
-
if (
|
|
63
|
-
if (
|
|
64
|
-
if (
|
|
65
|
-
return /received undefined/.test(
|
|
89
|
+
if (issue2.code === "unrecognized_keys") return "UNKNOWN_KEY";
|
|
90
|
+
if (issue2.code === "too_big") return "LIMIT_EXCEEDED";
|
|
91
|
+
if (issue2.code === "invalid_type") {
|
|
92
|
+
return /received undefined/.test(issue2.message) ? "REQUIRED" : "INVALID_SHAPE";
|
|
66
93
|
}
|
|
67
94
|
return "INVALID_VALUE";
|
|
68
95
|
}
|
|
69
|
-
function flatten(
|
|
70
|
-
if (
|
|
96
|
+
function flatten(issue2, out, prefix = []) {
|
|
97
|
+
if (issue2.code === "invalid_union") {
|
|
71
98
|
let best;
|
|
72
|
-
for (const branch of
|
|
99
|
+
for (const branch of issue2.errors) {
|
|
73
100
|
if (best === void 0 || branch.length < best.length) {
|
|
74
101
|
best = branch;
|
|
75
102
|
}
|
|
76
103
|
}
|
|
77
104
|
if (best !== void 0) {
|
|
78
|
-
for (const inner of best) flatten(inner, out, [...prefix, ...
|
|
105
|
+
for (const inner of best) flatten(inner, out, [...prefix, ...issue2.path]);
|
|
79
106
|
return;
|
|
80
107
|
}
|
|
81
108
|
}
|
|
82
|
-
const path = [...prefix, ...
|
|
109
|
+
const path = [...prefix, ...issue2.path].map(
|
|
83
110
|
(p) => typeof p === "symbol" ? String(p) : p
|
|
84
111
|
);
|
|
85
|
-
out.push(makeIssue(path, codeFor(
|
|
112
|
+
out.push(makeIssue(path, codeFor(issue2), issue2.message));
|
|
86
113
|
}
|
|
87
114
|
function zodIssues(error) {
|
|
88
115
|
const out = [];
|
|
89
|
-
for (const
|
|
90
|
-
flatten(
|
|
116
|
+
for (const issue2 of error.issues) {
|
|
117
|
+
flatten(issue2, out);
|
|
91
118
|
if (out.length >= MAX_ISSUES) break;
|
|
92
119
|
}
|
|
93
120
|
return capIssues(dropShadowed(out));
|
|
@@ -682,6 +709,7 @@ var spacingValueSchema = z3.union([
|
|
|
682
709
|
z3.enum(SPACING_TOKENS),
|
|
683
710
|
z3.number().min(0).max(400)
|
|
684
711
|
]);
|
|
712
|
+
var COMMON_SETTING_KEYS = ["hidden", "anchor", "spacingTop", "spacingBottom"];
|
|
685
713
|
var ANCHOR_RE = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
|
|
686
714
|
var anchorSchema = z3.string().regex(ANCHOR_RE);
|
|
687
715
|
var VERTICAL_ALIGN = ["top", "center", "bottom", "stretch"];
|
|
@@ -847,7 +875,7 @@ var customWidgetSnapshotSchema = z3.object({
|
|
|
847
875
|
description: z3.string().max(500),
|
|
848
876
|
icon: z3.string().max(40),
|
|
849
877
|
group: z3.literal("custom"),
|
|
850
|
-
settings: z3.array(z3.record(z3.string(), z3.unknown())).max(LIMITS.widgetSettings),
|
|
878
|
+
settings: z3.array(z3.record(z3.string(), z3.unknown())).max(LIMITS.widgetSettings + COMMON_SETTING_KEYS.length),
|
|
851
879
|
renamed: z3.record(z3.string(), z3.string()).optional(),
|
|
852
880
|
removed: z3.array(z3.string()).optional()
|
|
853
881
|
}).loose();
|
|
@@ -992,205 +1020,6 @@ function validateDocument(input) {
|
|
|
992
1020
|
|
|
993
1021
|
// src/widgets.ts
|
|
994
1022
|
import { z as z4 } from "zod";
|
|
995
|
-
var WIDGET_GROUPS = ["layout", "basic", "catalog", "commerce", "custom"];
|
|
996
|
-
var SETTING_TABS = ["content", "style", "advanced"];
|
|
997
|
-
var SETTING_CONTROLS = [
|
|
998
|
-
"text",
|
|
999
|
-
"richtext",
|
|
1000
|
-
"number",
|
|
1001
|
-
"select",
|
|
1002
|
-
"toggle",
|
|
1003
|
-
"color",
|
|
1004
|
-
"spacing",
|
|
1005
|
-
"image",
|
|
1006
|
-
"link",
|
|
1007
|
-
"icon",
|
|
1008
|
-
"alignment",
|
|
1009
|
-
"font-size"
|
|
1010
|
-
];
|
|
1011
|
-
var DATA_RESULT_TYPES = [
|
|
1012
|
-
"product[]",
|
|
1013
|
-
"product",
|
|
1014
|
-
"collection",
|
|
1015
|
-
"category[]",
|
|
1016
|
-
"review[]",
|
|
1017
|
-
"customer",
|
|
1018
|
-
"cart"
|
|
1019
|
-
];
|
|
1020
|
-
var settingValue = settingValueSchema;
|
|
1021
|
-
var settingFieldSchema = z4.object({
|
|
1022
|
-
key: z4.string().regex(/^[a-z][A-Za-z0-9]{0,39}$/),
|
|
1023
|
-
label: z4.string().min(1).max(100),
|
|
1024
|
-
tab: z4.enum(SETTING_TABS),
|
|
1025
|
-
output: z4.enum(["css", "markup"]),
|
|
1026
|
-
control: z4.enum(SETTING_CONTROLS),
|
|
1027
|
-
translatable: z4.boolean().optional(),
|
|
1028
|
-
default: settingValue,
|
|
1029
|
-
min: z4.number().optional(),
|
|
1030
|
-
max: z4.number().optional(),
|
|
1031
|
-
options: z4.array(z4.object({ value: z4.string().max(60), label: z4.string().max(100) }).strict()).max(50).optional(),
|
|
1032
|
-
maxLength: z4.number().int().min(1).max(2e4).optional()
|
|
1033
|
-
}).strict();
|
|
1034
|
-
var fieldSpecSchema = z4.object({
|
|
1035
|
-
/** A dotted path a template may read, such as `price.display`. */
|
|
1036
|
-
name: z4.string().regex(/^[a-z][A-Za-z0-9]*(?:\.[a-z][A-Za-z0-9]*)*$/),
|
|
1037
|
-
type: z4.enum(["string", "number", "boolean", "money", "image", "url", "date", "list"]),
|
|
1038
|
-
example: settingValue.optional()
|
|
1039
|
-
}).strict();
|
|
1040
|
-
var dataSourceDescriptorSchema = z4.object({
|
|
1041
|
-
id: z4.string().regex(/^[a-z][a-z0-9]*\.[a-z][a-z0-9-]*$/),
|
|
1042
|
-
provider: z4.enum(["catalog", "commerce"]),
|
|
1043
|
-
title: z4.string().min(1).max(100),
|
|
1044
|
-
description: z4.string().max(500),
|
|
1045
|
-
params: z4.array(settingFieldSchema).max(LIMITS.widgetSettings),
|
|
1046
|
-
result: z4.enum(DATA_RESULT_TYPES),
|
|
1047
|
-
fields: z4.array(fieldSpecSchema).max(200),
|
|
1048
|
-
perShopper: z4.boolean(),
|
|
1049
|
-
cacheKind: z4.enum(["listings", "product", "reviews", "none"])
|
|
1050
|
-
}).strict();
|
|
1051
|
-
var widgetDefinitionSchema = z4.object({
|
|
1052
|
-
type: z4.string().regex(WIDGET_TYPE_RE),
|
|
1053
|
-
v: z4.number().int().min(1).max(9999),
|
|
1054
|
-
title: z4.string().min(1).max(100),
|
|
1055
|
-
group: z4.enum(WIDGET_GROUPS),
|
|
1056
|
-
icon: z4.string().min(1).max(40),
|
|
1057
|
-
description: z4.string().min(1).max(500),
|
|
1058
|
-
settings: z4.array(settingFieldSchema).max(LIMITS.widgetSettings),
|
|
1059
|
-
data: z4.record(
|
|
1060
|
-
z4.string(),
|
|
1061
|
-
z4.object({
|
|
1062
|
-
accepts: z4.array(z4.enum(DATA_RESULT_TYPES)).min(1),
|
|
1063
|
-
required: z4.boolean(),
|
|
1064
|
-
default: dataBindingSchema.optional(),
|
|
1065
|
-
label: z4.string().min(1).max(100)
|
|
1066
|
-
}).strict()
|
|
1067
|
-
).optional(),
|
|
1068
|
-
placement: z4.object({
|
|
1069
|
-
slotsOnly: z4.boolean().optional(),
|
|
1070
|
-
notIn: z4.array(z4.enum(["header", "footer", "slot"])).optional()
|
|
1071
|
-
}).strict().optional()
|
|
1072
|
-
}).strict();
|
|
1073
|
-
var SIZE_TOKENS = ["xs", "s", "m", "l", "xl", "2xl", "3xl"];
|
|
1074
|
-
var ALIGNMENTS = ["left", "center", "right", "justify"];
|
|
1075
|
-
var LOCALE_KEY = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;
|
|
1076
|
-
function fitsText(value, field2) {
|
|
1077
|
-
const max = field2.maxLength ?? 2e3;
|
|
1078
|
-
if (field2.translatable === true) {
|
|
1079
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1080
|
-
return "Expected a map of locale to text";
|
|
1081
|
-
}
|
|
1082
|
-
for (const [locale, text] of Object.entries(value)) {
|
|
1083
|
-
if (!LOCALE_KEY.test(locale)) return `"${locale}" is not a locale tag`;
|
|
1084
|
-
if (typeof text !== "string") return `The text for "${locale}" must be a string`;
|
|
1085
|
-
if (text.length > max) return `The text for "${locale}" is over ${String(max)} characters`;
|
|
1086
|
-
}
|
|
1087
|
-
return null;
|
|
1088
|
-
}
|
|
1089
|
-
if (typeof value !== "string") return "Expected text";
|
|
1090
|
-
if (value.length > max) return `Text is over ${String(max)} characters`;
|
|
1091
|
-
return null;
|
|
1092
|
-
}
|
|
1093
|
-
function validateSettingValue(field2, value) {
|
|
1094
|
-
if (value === null) {
|
|
1095
|
-
return field2.default === null ? null : "This setting cannot be empty";
|
|
1096
|
-
}
|
|
1097
|
-
switch (field2.control) {
|
|
1098
|
-
case "text":
|
|
1099
|
-
case "richtext":
|
|
1100
|
-
if (field2.key === "anchor") {
|
|
1101
|
-
return typeof value === "string" && ANCHOR_RE.test(value) ? null : "An anchor starts with a letter and uses letters, digits, - and _ (64 at most)";
|
|
1102
|
-
}
|
|
1103
|
-
return fitsText(value, field2);
|
|
1104
|
-
case "icon":
|
|
1105
|
-
return typeof value === "string" && /^[a-z][a-z0-9-]{0,39}$/.test(value) ? null : "Expected an icon name";
|
|
1106
|
-
case "number": {
|
|
1107
|
-
if (typeof value !== "number" || !Number.isFinite(value)) return "Expected a number";
|
|
1108
|
-
if (field2.min !== void 0 && value < field2.min) return `Must be at least ${String(field2.min)}`;
|
|
1109
|
-
if (field2.max !== void 0 && value > field2.max) return `Must be at most ${String(field2.max)}`;
|
|
1110
|
-
return null;
|
|
1111
|
-
}
|
|
1112
|
-
case "select":
|
|
1113
|
-
return typeof value === "string" && (field2.options ?? []).some((o) => o.value === value) ? null : "Expected one of the listed options";
|
|
1114
|
-
case "toggle":
|
|
1115
|
-
return typeof value === "boolean" ? null : "Expected true or false";
|
|
1116
|
-
case "color":
|
|
1117
|
-
return typeof value === "string" && COLOR_VALUE_RE.test(value) ? null : "Expected token:name or #rrggbb[aa]";
|
|
1118
|
-
case "spacing":
|
|
1119
|
-
return typeof value === "string" && SPACING_TOKENS.includes(value) || typeof value === "number" && value >= 0 && value <= 400 ? null : "Expected a spacing token or 0 to 400 px";
|
|
1120
|
-
case "font-size":
|
|
1121
|
-
return typeof value === "string" && SIZE_TOKENS.includes(value) || typeof value === "number" && value >= 8 && value <= 200 ? null : "Expected a size token or 8 to 200 px";
|
|
1122
|
-
case "alignment":
|
|
1123
|
-
return typeof value === "string" && ALIGNMENTS.includes(value) ? null : "Expected an alignment";
|
|
1124
|
-
case "image":
|
|
1125
|
-
return typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value) ? null : "Expected a media asset id";
|
|
1126
|
-
case "link":
|
|
1127
|
-
return menuTargetSchema.safeParse(value).success ? null : "Expected a link target";
|
|
1128
|
-
default:
|
|
1129
|
-
return "Unknown control";
|
|
1130
|
-
}
|
|
1131
|
-
}
|
|
1132
|
-
function validateWidgetProps(def, props) {
|
|
1133
|
-
const byKey = new Map(def.settings.map((s) => [s.key, s]));
|
|
1134
|
-
const problems = [];
|
|
1135
|
-
for (const [key, value] of Object.entries(props)) {
|
|
1136
|
-
const field2 = byKey.get(key);
|
|
1137
|
-
if (field2 === void 0) {
|
|
1138
|
-
problems.push({ path: key, message: `Unknown setting "${key}"` });
|
|
1139
|
-
continue;
|
|
1140
|
-
}
|
|
1141
|
-
const message = validateSettingValue(field2, value);
|
|
1142
|
-
if (message !== null) problems.push({ path: key, message });
|
|
1143
|
-
}
|
|
1144
|
-
return problems;
|
|
1145
|
-
}
|
|
1146
|
-
function definitionOfSnapshot(snapshot) {
|
|
1147
|
-
const { type, v, title, description, icon, settings } = snapshot;
|
|
1148
|
-
const data = snapshot.data;
|
|
1149
|
-
return {
|
|
1150
|
-
type,
|
|
1151
|
-
v,
|
|
1152
|
-
title,
|
|
1153
|
-
group: "custom",
|
|
1154
|
-
icon,
|
|
1155
|
-
description,
|
|
1156
|
-
settings,
|
|
1157
|
-
...data === void 0 ? {} : { data }
|
|
1158
|
-
};
|
|
1159
|
-
}
|
|
1160
|
-
function createRegistry(defs, sources, custom = []) {
|
|
1161
|
-
const byType = /* @__PURE__ */ new Map();
|
|
1162
|
-
const add = (def) => {
|
|
1163
|
-
let versions = byType.get(def.type);
|
|
1164
|
-
if (versions === void 0) {
|
|
1165
|
-
versions = /* @__PURE__ */ new Map();
|
|
1166
|
-
byType.set(def.type, versions);
|
|
1167
|
-
}
|
|
1168
|
-
if (versions.has(def.v)) {
|
|
1169
|
-
throw new Error(`Duplicate widget definition ${def.type}@${String(def.v)}`);
|
|
1170
|
-
}
|
|
1171
|
-
versions.set(def.v, def);
|
|
1172
|
-
};
|
|
1173
|
-
for (const def of defs) add(def);
|
|
1174
|
-
for (const snapshot of custom) add(definitionOfSnapshot(snapshot));
|
|
1175
|
-
const sourcesById = /* @__PURE__ */ new Map();
|
|
1176
|
-
for (const source of sources) {
|
|
1177
|
-
if (sourcesById.has(source.id)) throw new Error(`Duplicate data source ${source.id}`);
|
|
1178
|
-
sourcesById.set(source.id, source);
|
|
1179
|
-
}
|
|
1180
|
-
const latest = (type) => {
|
|
1181
|
-
const versions = byType.get(type);
|
|
1182
|
-
if (versions === void 0) return void 0;
|
|
1183
|
-
let best;
|
|
1184
|
-
for (const def of versions.values()) if (best === void 0 || def.v > best.v) best = def;
|
|
1185
|
-
return best;
|
|
1186
|
-
};
|
|
1187
|
-
return {
|
|
1188
|
-
widget: (type, v) => byType.get(type)?.get(v),
|
|
1189
|
-
latest,
|
|
1190
|
-
source: (id) => sourcesById.get(id),
|
|
1191
|
-
all: () => [...byType.keys()].sort().map((type) => latest(type)).filter((def) => def !== void 0)
|
|
1192
|
-
};
|
|
1193
|
-
}
|
|
1194
1023
|
|
|
1195
1024
|
// src/basics.ts
|
|
1196
1025
|
var opts = (...values) => values.map((value) => ({ value, label: value.charAt(0).toUpperCase() + value.slice(1) }));
|
|
@@ -1527,21 +1356,3483 @@ var BASIC_WIDGET_DEFINITIONS = [
|
|
|
1527
1356
|
size("s")
|
|
1528
1357
|
])
|
|
1529
1358
|
];
|
|
1359
|
+
|
|
1360
|
+
// src/widgets.ts
|
|
1361
|
+
var WIDGET_GROUPS = ["layout", "basic", "catalog", "commerce", "custom"];
|
|
1362
|
+
var SETTING_TABS = ["content", "style", "advanced"];
|
|
1363
|
+
var SETTING_CONTROLS = [
|
|
1364
|
+
"text",
|
|
1365
|
+
"richtext",
|
|
1366
|
+
"number",
|
|
1367
|
+
"select",
|
|
1368
|
+
"toggle",
|
|
1369
|
+
"color",
|
|
1370
|
+
"spacing",
|
|
1371
|
+
"image",
|
|
1372
|
+
"link",
|
|
1373
|
+
"icon",
|
|
1374
|
+
"alignment",
|
|
1375
|
+
"font-size"
|
|
1376
|
+
];
|
|
1377
|
+
var DATA_RESULT_TYPES = [
|
|
1378
|
+
"product[]",
|
|
1379
|
+
"product",
|
|
1380
|
+
"collection",
|
|
1381
|
+
"category[]",
|
|
1382
|
+
"review[]",
|
|
1383
|
+
"customer",
|
|
1384
|
+
"cart"
|
|
1385
|
+
];
|
|
1386
|
+
var settingValue = settingValueSchema;
|
|
1387
|
+
var CSS_CONTROLS = ["color", "spacing", "font-size", "alignment", "number", "toggle", "select"];
|
|
1388
|
+
var CSS_OPTION_RE = /^[a-z0-9][a-z0-9:-]{0,39}$/;
|
|
1389
|
+
var settingFieldSchema = z4.object({
|
|
1390
|
+
key: z4.string().regex(/^[a-z][A-Za-z0-9]{0,39}$/),
|
|
1391
|
+
label: z4.string().min(1).max(100),
|
|
1392
|
+
tab: z4.enum(SETTING_TABS),
|
|
1393
|
+
output: z4.enum(["css", "markup"]),
|
|
1394
|
+
control: z4.enum(SETTING_CONTROLS),
|
|
1395
|
+
translatable: z4.boolean().optional(),
|
|
1396
|
+
default: settingValue,
|
|
1397
|
+
min: z4.number().optional(),
|
|
1398
|
+
max: z4.number().optional(),
|
|
1399
|
+
options: z4.array(z4.object({ value: z4.string().max(60), label: z4.string().max(100) }).strict()).max(50).optional(),
|
|
1400
|
+
maxLength: z4.number().int().min(1).max(2e4).optional()
|
|
1401
|
+
}).strict().superRefine((field2, ctx) => {
|
|
1402
|
+
if (field2.output !== "css") return;
|
|
1403
|
+
if (!CSS_CONTROLS.includes(field2.control) || field2.translatable === true) {
|
|
1404
|
+
customIssue(
|
|
1405
|
+
ctx,
|
|
1406
|
+
"INVALID_VALUE",
|
|
1407
|
+
`A css setting uses the ${CSS_CONTROLS.join(", ")} control, not ${field2.control}`,
|
|
1408
|
+
["control"]
|
|
1409
|
+
);
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1412
|
+
(field2.options ?? []).forEach((option, i) => {
|
|
1413
|
+
if (!CSS_OPTION_RE.test(option.value)) {
|
|
1414
|
+
customIssue(ctx, "INVALID_VALUE", "An option of a css setting is lower case letters, digits, - and :", ["options", i, "value"]);
|
|
1415
|
+
}
|
|
1416
|
+
});
|
|
1417
|
+
const problem = validateSettingValue(field2, field2.default);
|
|
1418
|
+
if (problem !== null) customIssue(ctx, "INVALID_VALUE", `The default is invalid: ${problem}`, ["default"]);
|
|
1419
|
+
});
|
|
1420
|
+
var fieldSpecSchema = z4.object({
|
|
1421
|
+
/** A dotted path a template may read, such as `price.display`. */
|
|
1422
|
+
name: z4.string().regex(/^[a-z][A-Za-z0-9]*(?:\.[a-z][A-Za-z0-9]*)*$/),
|
|
1423
|
+
type: z4.enum(["string", "number", "boolean", "money", "image", "url", "date", "list"]),
|
|
1424
|
+
example: settingValue.optional()
|
|
1425
|
+
}).strict();
|
|
1426
|
+
var dataSourceDescriptorSchema = z4.object({
|
|
1427
|
+
id: z4.string().regex(/^[a-z][a-z0-9]*\.[a-z][a-z0-9-]*$/),
|
|
1428
|
+
provider: z4.enum(["catalog", "commerce"]),
|
|
1429
|
+
title: z4.string().min(1).max(100),
|
|
1430
|
+
description: z4.string().max(500),
|
|
1431
|
+
params: z4.array(settingFieldSchema).max(LIMITS.widgetSettings),
|
|
1432
|
+
result: z4.enum(DATA_RESULT_TYPES),
|
|
1433
|
+
fields: z4.array(fieldSpecSchema).max(200),
|
|
1434
|
+
perShopper: z4.boolean(),
|
|
1435
|
+
cacheKind: z4.enum(["listings", "product", "reviews", "none"])
|
|
1436
|
+
}).strict();
|
|
1437
|
+
var widgetDefinitionSchema = z4.object({
|
|
1438
|
+
type: z4.string().regex(WIDGET_TYPE_RE),
|
|
1439
|
+
v: z4.number().int().min(1).max(9999),
|
|
1440
|
+
title: z4.string().min(1).max(100),
|
|
1441
|
+
group: z4.enum(WIDGET_GROUPS),
|
|
1442
|
+
icon: z4.string().min(1).max(40),
|
|
1443
|
+
description: z4.string().min(1).max(500),
|
|
1444
|
+
// The common props (hidden, anchor, spacing) do not count against the cap.
|
|
1445
|
+
settings: z4.array(settingFieldSchema).max(LIMITS.widgetSettings + COMMON_SETTING_KEYS.length),
|
|
1446
|
+
data: z4.record(
|
|
1447
|
+
z4.string(),
|
|
1448
|
+
z4.object({
|
|
1449
|
+
accepts: z4.array(z4.enum(DATA_RESULT_TYPES)).min(1),
|
|
1450
|
+
required: z4.boolean(),
|
|
1451
|
+
default: dataBindingSchema.optional(),
|
|
1452
|
+
label: z4.string().min(1).max(100)
|
|
1453
|
+
}).strict()
|
|
1454
|
+
).optional(),
|
|
1455
|
+
placement: z4.object({
|
|
1456
|
+
slotsOnly: z4.boolean().optional(),
|
|
1457
|
+
notIn: z4.array(z4.enum(["header", "footer", "slot"])).optional(),
|
|
1458
|
+
/** Not allowed inside an inner section. */
|
|
1459
|
+
topLevelOnly: z4.boolean().optional()
|
|
1460
|
+
}).strict().optional()
|
|
1461
|
+
}).strict().superRefine((def, ctx) => {
|
|
1462
|
+
const own = def.settings.filter(
|
|
1463
|
+
(f) => !COMMON_SETTING_KEYS.includes(f.key)
|
|
1464
|
+
).length;
|
|
1465
|
+
if (own > LIMITS.widgetSettings) {
|
|
1466
|
+
customIssue(ctx, "LIMIT_EXCEEDED", `A widget has at most ${String(LIMITS.widgetSettings)} settings`, ["settings"]);
|
|
1467
|
+
}
|
|
1468
|
+
});
|
|
1469
|
+
var SIZE_TOKENS = ["xs", "s", "m", "l", "xl", "2xl", "3xl"];
|
|
1470
|
+
var ALIGNMENTS = ["left", "center", "right", "justify"];
|
|
1471
|
+
var LOCALE_KEY = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;
|
|
1472
|
+
function fitsText(value, field2) {
|
|
1473
|
+
const max = field2.maxLength ?? 2e3;
|
|
1474
|
+
if (field2.translatable === true) {
|
|
1475
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1476
|
+
return "Expected a map of locale to text";
|
|
1477
|
+
}
|
|
1478
|
+
for (const [locale, text] of Object.entries(value)) {
|
|
1479
|
+
if (!LOCALE_KEY.test(locale)) return `"${locale}" is not a locale tag`;
|
|
1480
|
+
if (typeof text !== "string") return `The text for "${locale}" must be a string`;
|
|
1481
|
+
if (text.length > max) return `The text for "${locale}" is over ${String(max)} characters`;
|
|
1482
|
+
}
|
|
1483
|
+
return null;
|
|
1484
|
+
}
|
|
1485
|
+
if (typeof value !== "string") return "Expected text";
|
|
1486
|
+
if (value.length > max) return `Text is over ${String(max)} characters`;
|
|
1487
|
+
return null;
|
|
1488
|
+
}
|
|
1489
|
+
function validateSettingValue(field2, value) {
|
|
1490
|
+
if (value === null) {
|
|
1491
|
+
return field2.default === null ? null : "This setting cannot be empty";
|
|
1492
|
+
}
|
|
1493
|
+
switch (field2.control) {
|
|
1494
|
+
case "text":
|
|
1495
|
+
case "richtext":
|
|
1496
|
+
if (field2.key === "anchor") {
|
|
1497
|
+
return typeof value === "string" && ANCHOR_RE.test(value) ? null : "An anchor starts with a letter and uses letters, digits, - and _ (64 at most)";
|
|
1498
|
+
}
|
|
1499
|
+
return fitsText(value, field2);
|
|
1500
|
+
case "icon":
|
|
1501
|
+
return typeof value === "string" && /^[a-z][a-z0-9-]{0,39}$/.test(value) ? null : "Expected an icon name";
|
|
1502
|
+
case "number": {
|
|
1503
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return "Expected a number";
|
|
1504
|
+
if (field2.min !== void 0 && value < field2.min) return `Must be at least ${String(field2.min)}`;
|
|
1505
|
+
if (field2.max !== void 0 && value > field2.max) return `Must be at most ${String(field2.max)}`;
|
|
1506
|
+
return null;
|
|
1507
|
+
}
|
|
1508
|
+
case "select":
|
|
1509
|
+
return typeof value === "string" && (field2.options ?? []).some((o) => o.value === value) ? null : "Expected one of the listed options";
|
|
1510
|
+
case "toggle":
|
|
1511
|
+
return typeof value === "boolean" ? null : "Expected true or false";
|
|
1512
|
+
case "color":
|
|
1513
|
+
return typeof value === "string" && COLOR_VALUE_RE.test(value) ? null : "Expected token:name or #rrggbb[aa]";
|
|
1514
|
+
case "spacing":
|
|
1515
|
+
return typeof value === "string" && SPACING_TOKENS.includes(value) || typeof value === "number" && value >= 0 && value <= 400 ? null : "Expected a spacing token or 0 to 400 px";
|
|
1516
|
+
case "font-size":
|
|
1517
|
+
return typeof value === "string" && SIZE_TOKENS.includes(value) || typeof value === "number" && value >= 8 && value <= 200 ? null : "Expected a size token or 8 to 200 px";
|
|
1518
|
+
case "alignment":
|
|
1519
|
+
return typeof value === "string" && ALIGNMENTS.includes(value) ? null : "Expected an alignment";
|
|
1520
|
+
case "image":
|
|
1521
|
+
return typeof value === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(value) ? null : "Expected a media asset id";
|
|
1522
|
+
case "link":
|
|
1523
|
+
return menuTargetSchema.safeParse(value).success ? null : "Expected a link target";
|
|
1524
|
+
default:
|
|
1525
|
+
return "Unknown control";
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
function validateWidgetProps(def, props) {
|
|
1529
|
+
const byKey = new Map([...COMMON_WIDGET_SETTINGS, ...def.settings].map((s) => [s.key, s]));
|
|
1530
|
+
const problems = [];
|
|
1531
|
+
for (const [key, value] of Object.entries(props)) {
|
|
1532
|
+
const field2 = byKey.get(key);
|
|
1533
|
+
if (field2 === void 0) {
|
|
1534
|
+
problems.push({ path: key, message: `Unknown setting "${key}"` });
|
|
1535
|
+
continue;
|
|
1536
|
+
}
|
|
1537
|
+
const message = validateSettingValue(field2, value);
|
|
1538
|
+
if (message !== null) problems.push({ path: key, message });
|
|
1539
|
+
}
|
|
1540
|
+
return problems;
|
|
1541
|
+
}
|
|
1542
|
+
var snapshotPlacementSchema = z4.object({ topLevelOnly: z4.boolean().optional() }).strict();
|
|
1543
|
+
function snapshotPlacement(snapshot) {
|
|
1544
|
+
const raw2 = snapshot.placement;
|
|
1545
|
+
if (raw2 === void 0) return void 0;
|
|
1546
|
+
const parsed = snapshotPlacementSchema.safeParse(raw2);
|
|
1547
|
+
if (!parsed.success) throw new Error(`Invalid placement on ${snapshot.type}@${String(snapshot.v)}`);
|
|
1548
|
+
return parsed.data;
|
|
1549
|
+
}
|
|
1550
|
+
function definitionOfSnapshot(snapshot) {
|
|
1551
|
+
const { type, v, title, description, icon, settings, kind } = snapshot;
|
|
1552
|
+
const data = snapshot.data;
|
|
1553
|
+
const placement = snapshotPlacement(snapshot);
|
|
1554
|
+
return {
|
|
1555
|
+
type,
|
|
1556
|
+
kind,
|
|
1557
|
+
v,
|
|
1558
|
+
title,
|
|
1559
|
+
group: "custom",
|
|
1560
|
+
icon,
|
|
1561
|
+
description,
|
|
1562
|
+
settings,
|
|
1563
|
+
...placement === void 0 ? {} : { placement },
|
|
1564
|
+
...data === void 0 ? {} : { data },
|
|
1565
|
+
...snapshot.renamed === void 0 ? {} : { renamed: snapshot.renamed },
|
|
1566
|
+
...snapshot.removed === void 0 ? {} : { removed: snapshot.removed }
|
|
1567
|
+
};
|
|
1568
|
+
}
|
|
1569
|
+
function createRegistry(defs, sources, custom = []) {
|
|
1570
|
+
const byType = /* @__PURE__ */ new Map();
|
|
1571
|
+
const add = (def) => {
|
|
1572
|
+
let versions = byType.get(def.type);
|
|
1573
|
+
if (versions === void 0) {
|
|
1574
|
+
versions = /* @__PURE__ */ new Map();
|
|
1575
|
+
byType.set(def.type, versions);
|
|
1576
|
+
}
|
|
1577
|
+
if (versions.has(def.v)) {
|
|
1578
|
+
throw new Error(`Duplicate widget definition ${def.type}@${String(def.v)}`);
|
|
1579
|
+
}
|
|
1580
|
+
versions.set(def.v, def);
|
|
1581
|
+
};
|
|
1582
|
+
for (const def of defs) add(def);
|
|
1583
|
+
for (const snapshot of custom) add(definitionOfSnapshot(snapshot));
|
|
1584
|
+
const sourcesById = /* @__PURE__ */ new Map();
|
|
1585
|
+
for (const source of sources) {
|
|
1586
|
+
if (sourcesById.has(source.id)) throw new Error(`Duplicate data source ${source.id}`);
|
|
1587
|
+
sourcesById.set(source.id, source);
|
|
1588
|
+
}
|
|
1589
|
+
const latest = (type) => {
|
|
1590
|
+
const versions = byType.get(type);
|
|
1591
|
+
if (versions === void 0) return void 0;
|
|
1592
|
+
let best;
|
|
1593
|
+
for (const def of versions.values()) if (best === void 0 || def.v > best.v) best = def;
|
|
1594
|
+
return best;
|
|
1595
|
+
};
|
|
1596
|
+
return {
|
|
1597
|
+
widget: (type, v) => byType.get(type)?.get(v),
|
|
1598
|
+
latest,
|
|
1599
|
+
source: (id) => sourcesById.get(id),
|
|
1600
|
+
sources: () => [...sourcesById.values()],
|
|
1601
|
+
all: () => [...byType.keys()].sort().map((type) => latest(type)).filter((def) => def !== void 0)
|
|
1602
|
+
};
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
// src/tree.ts
|
|
1606
|
+
var isRec = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1607
|
+
var has = (rec, key) => Object.prototype.hasOwnProperty.call(rec, key);
|
|
1608
|
+
function findPath(doc, id) {
|
|
1609
|
+
let found;
|
|
1610
|
+
walkNodes(doc, (node, path) => {
|
|
1611
|
+
if (found === void 0 && node.id === id) found = path;
|
|
1612
|
+
});
|
|
1613
|
+
return found;
|
|
1614
|
+
}
|
|
1615
|
+
function getAt(root, path) {
|
|
1616
|
+
let current = root;
|
|
1617
|
+
for (const key of path) {
|
|
1618
|
+
if (typeof current !== "object" || current === null) return void 0;
|
|
1619
|
+
current = current[key];
|
|
1620
|
+
}
|
|
1621
|
+
return current;
|
|
1622
|
+
}
|
|
1623
|
+
function setAt(root, path, value) {
|
|
1624
|
+
const [key, ...rest] = path;
|
|
1625
|
+
if (key === void 0) return value;
|
|
1626
|
+
const child = root[key];
|
|
1627
|
+
const next = rest.length === 0 ? value : setAt(child, rest, value);
|
|
1628
|
+
if (Array.isArray(root)) {
|
|
1629
|
+
const copy = root.slice();
|
|
1630
|
+
copy[key] = next;
|
|
1631
|
+
return copy;
|
|
1632
|
+
}
|
|
1633
|
+
return { ...root, [key]: next };
|
|
1634
|
+
}
|
|
1635
|
+
function insertAtIndex(items, index, item) {
|
|
1636
|
+
return [...items.slice(0, index), item, ...items.slice(index)];
|
|
1637
|
+
}
|
|
1638
|
+
function parentOf(doc, path) {
|
|
1639
|
+
const arrayPath = path.slice(0, -1);
|
|
1640
|
+
const index = path[path.length - 1];
|
|
1641
|
+
if (path.length === 2) return { parentId: "root", arrayPath, index };
|
|
1642
|
+
const parent = getAt(doc, path.slice(0, -2));
|
|
1643
|
+
return { parentId: parent.id, arrayPath, index };
|
|
1644
|
+
}
|
|
1645
|
+
function widgetsIn(node, path = [], inner = false) {
|
|
1646
|
+
if (!isRec(node)) return [];
|
|
1647
|
+
if (node.type === "section" || node.type === "inner-section") {
|
|
1648
|
+
if (!Array.isArray(node.columns)) return [];
|
|
1649
|
+
const within = inner || node.type === "inner-section";
|
|
1650
|
+
return node.columns.flatMap((column, j) => widgetsIn(column, [...path, "columns", j], within));
|
|
1651
|
+
}
|
|
1652
|
+
if (node.type === "column") {
|
|
1653
|
+
if (!Array.isArray(node.children)) return [];
|
|
1654
|
+
return node.children.flatMap((child, k) => widgetsIn(child, [...path, "children", k], inner));
|
|
1655
|
+
}
|
|
1656
|
+
return [{ node, path, inner }];
|
|
1657
|
+
}
|
|
1658
|
+
function idsIn(node) {
|
|
1659
|
+
if (!isRec(node)) return [];
|
|
1660
|
+
const own = typeof node.id === "string" ? [node.id] : [];
|
|
1661
|
+
const nested = Array.isArray(node.columns) ? node.columns : Array.isArray(node.children) ? node.children : [];
|
|
1662
|
+
return [...own, ...nested.flatMap(idsIn)];
|
|
1663
|
+
}
|
|
1664
|
+
function collectIds(doc) {
|
|
1665
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1666
|
+
walkNodes(doc, (node) => ids.add(node.id));
|
|
1667
|
+
return ids;
|
|
1668
|
+
}
|
|
1669
|
+
function freshId(base, suffix, used) {
|
|
1670
|
+
const root = base.slice(0, 24 - suffix.length - 3);
|
|
1671
|
+
for (let n = 0; ; n += 1) {
|
|
1672
|
+
const candidate = `${root}${suffix}${n === 0 ? "" : String(n)}`;
|
|
1673
|
+
if (!used.has(candidate)) {
|
|
1674
|
+
used.add(candidate);
|
|
1675
|
+
return candidate;
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
function cloneJson(value) {
|
|
1680
|
+
if (Array.isArray(value)) return value.map(cloneJson);
|
|
1681
|
+
if (typeof value === "object" && value !== null) {
|
|
1682
|
+
const out = {};
|
|
1683
|
+
for (const [key, item] of Object.entries(value)) out[key] = cloneJson(item);
|
|
1684
|
+
return out;
|
|
1685
|
+
}
|
|
1686
|
+
return value;
|
|
1687
|
+
}
|
|
1688
|
+
function deepEqual(a, b) {
|
|
1689
|
+
if (a === b) return true;
|
|
1690
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
1691
|
+
return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((x, i) => deepEqual(x, b[i]));
|
|
1692
|
+
}
|
|
1693
|
+
if (isRec(a) && isRec(b)) {
|
|
1694
|
+
const keys = Object.keys(a);
|
|
1695
|
+
return keys.length === Object.keys(b).length && keys.every((k) => has(b, k) && deepEqual(a[k], b[k]));
|
|
1696
|
+
}
|
|
1697
|
+
return false;
|
|
1698
|
+
}
|
|
1699
|
+
|
|
1700
|
+
// src/placement.ts
|
|
1701
|
+
var refuse = (code, message) => ({ ok: false, code, message });
|
|
1702
|
+
var PART_OF_KIND = {
|
|
1703
|
+
"part:header": "header",
|
|
1704
|
+
"part:footer": "footer",
|
|
1705
|
+
slot: "slot"
|
|
1706
|
+
};
|
|
1707
|
+
function placementOf(type, ctx, v) {
|
|
1708
|
+
const def = (v === void 0 ? void 0 : ctx.registry.widget(type, v)) ?? ctx.registry.latest(type);
|
|
1709
|
+
return def === void 0 ? void 0 : { title: def.title, placement: def.placement };
|
|
1710
|
+
}
|
|
1711
|
+
function checkWidgetPart(type, ctx, v) {
|
|
1712
|
+
const found = placementOf(type, ctx, v);
|
|
1713
|
+
const placement = found?.placement;
|
|
1714
|
+
if (found === void 0 || placement === void 0) return { ok: true };
|
|
1715
|
+
if (placement.slotsOnly === true && ctx.documentKind !== "slot") {
|
|
1716
|
+
return refuse("NOT_ALLOWED_IN_PART", `${found.title} can only be used in a slot.`);
|
|
1717
|
+
}
|
|
1718
|
+
if (ctx.documentKind !== "page") {
|
|
1719
|
+
const part = PART_OF_KIND[ctx.documentKind];
|
|
1720
|
+
if (placement.notIn?.includes(part) === true) {
|
|
1721
|
+
return refuse(
|
|
1722
|
+
"NOT_ALLOWED_IN_PART",
|
|
1723
|
+
`${found.title} can't be used in the ${part === "slot" ? "slot" : `site ${part}`}.`
|
|
1724
|
+
);
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
return { ok: true };
|
|
1728
|
+
}
|
|
1729
|
+
function checkTopLevel(type, ctx, v) {
|
|
1730
|
+
const found = placementOf(type, ctx, v);
|
|
1731
|
+
if (found?.placement?.topLevelOnly === true) {
|
|
1732
|
+
return refuse(
|
|
1733
|
+
"INNER_NOT_TOP_LEVEL",
|
|
1734
|
+
`${found.title} can't go inside an inner section. Put it in a column of a section.`
|
|
1735
|
+
);
|
|
1736
|
+
}
|
|
1737
|
+
return { ok: true };
|
|
1738
|
+
}
|
|
1739
|
+
var startsWith = (path, prefix) => prefix.length <= path.length && prefix.every((key, i) => path[i] === key);
|
|
1740
|
+
function canPlace(doc, node, parentId, ctx) {
|
|
1741
|
+
const { type } = node;
|
|
1742
|
+
if (type === "column") {
|
|
1743
|
+
return refuse(
|
|
1744
|
+
"COLUMN_REMOVE_NEEDS_SETCOLUMNS",
|
|
1745
|
+
"Columns are added, removed and resized with the column controls."
|
|
1746
|
+
);
|
|
1747
|
+
}
|
|
1748
|
+
const own = node.id === void 0 ? void 0 : findPath(doc, node.id);
|
|
1749
|
+
const parentPath = parentId === "root" ? [] : findPath(doc, parentId);
|
|
1750
|
+
if (own !== void 0 && parentPath !== void 0 && (parentId === node.id || startsWith(parentPath, own))) {
|
|
1751
|
+
return refuse("MOVE_INTO_SELF", "A block can't be moved into itself.");
|
|
1752
|
+
}
|
|
1753
|
+
const isWidget = type !== "section" && type !== "inner-section";
|
|
1754
|
+
if (parentId === "root") {
|
|
1755
|
+
if (type === "inner-section") {
|
|
1756
|
+
return refuse(
|
|
1757
|
+
"INNER_NOT_TOP_LEVEL",
|
|
1758
|
+
"An inner section goes inside a column of a section, not on the page itself."
|
|
1759
|
+
);
|
|
1760
|
+
}
|
|
1761
|
+
return isWidget ? checkWidgetPart(type, ctx, node.v) : { ok: true };
|
|
1762
|
+
}
|
|
1763
|
+
const parent = parentPath === void 0 ? void 0 : getAt(doc, parentPath);
|
|
1764
|
+
if (!isRec(parent) || parent.type !== "column") {
|
|
1765
|
+
if (type === "inner-section") {
|
|
1766
|
+
return refuse(
|
|
1767
|
+
"INNER_NOT_TOP_LEVEL",
|
|
1768
|
+
"An inner section goes inside a column of a section."
|
|
1769
|
+
);
|
|
1770
|
+
}
|
|
1771
|
+
return refuse("SECTION_NOT_NESTABLE", "Blocks can only be placed inside a column.");
|
|
1772
|
+
}
|
|
1773
|
+
const inner = parentPath.length > 4;
|
|
1774
|
+
if (type === "section") {
|
|
1775
|
+
return refuse(
|
|
1776
|
+
"SECTION_NOT_NESTABLE",
|
|
1777
|
+
"A section can't go inside another section. Use an inner section."
|
|
1778
|
+
);
|
|
1779
|
+
}
|
|
1780
|
+
if (type === "inner-section" && inner) {
|
|
1781
|
+
return refuse("INNER_IN_INNER", "An inner section can't go inside another inner section.");
|
|
1782
|
+
}
|
|
1783
|
+
if (isWidget && inner) {
|
|
1784
|
+
const top = checkTopLevel(type, ctx, node.v);
|
|
1785
|
+
if (!top.ok) return top;
|
|
1786
|
+
}
|
|
1787
|
+
const children = parent.children;
|
|
1788
|
+
if (Array.isArray(children)) {
|
|
1789
|
+
const alreadyThere = own !== void 0 && children.some((child) => isRec(child) && child.id === node.id);
|
|
1790
|
+
const count = alreadyThere ? children.length - 1 : children.length;
|
|
1791
|
+
if (count >= LIMITS.childrenPerColumn) {
|
|
1792
|
+
return refuse("COLUMN_LIMIT", `This column is full (${String(LIMITS.childrenPerColumn)} blocks at most).`);
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
return isWidget ? checkWidgetPart(type, ctx, node.v) : { ok: true };
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
// src/ops.ts
|
|
1799
|
+
var at = (i, ...rest) => ["ops", i, ...rest];
|
|
1800
|
+
var fail = (path, code, message) => ({ issues: [makeIssue(path, code, message)] });
|
|
1801
|
+
var issue = (path, code, message) => makeIssue(path, code, message);
|
|
1802
|
+
var asNode = (value) => value;
|
|
1803
|
+
var DEVICES = ["tablet", "phone"];
|
|
1804
|
+
var SECTION_KEYS = new Set(Object.keys(sectionPropsSchema.shape));
|
|
1805
|
+
var COLUMN_KEYS = new Set(Object.keys(columnPropsSchema.shape));
|
|
1806
|
+
function propIssues(def, props, path, skipNull, common2 = false) {
|
|
1807
|
+
const fields = common2 ? [...def.settings, ...COMMON_WIDGET_SETTINGS] : def.settings;
|
|
1808
|
+
const byKey = new Map(fields.map((s) => [s.key, s]));
|
|
1809
|
+
const out = [];
|
|
1810
|
+
for (const [key, value] of Object.entries(props)) {
|
|
1811
|
+
if (FORBIDDEN_KEYS.has(key)) {
|
|
1812
|
+
out.push(issue([...path, key], "FORBIDDEN_KEY", `The key "${key}" is not allowed`));
|
|
1813
|
+
continue;
|
|
1814
|
+
}
|
|
1815
|
+
const field2 = byKey.get(key);
|
|
1816
|
+
if (field2 === void 0) {
|
|
1817
|
+
out.push(issue([...path, key], "UNKNOWN_PROP", `"${key}" is not a setting of ${def.title}`));
|
|
1818
|
+
continue;
|
|
1819
|
+
}
|
|
1820
|
+
if (value === null && skipNull) continue;
|
|
1821
|
+
if (!isSettingValue(value)) {
|
|
1822
|
+
out.push(issue([...path, key], "INVALID_VALUE", "Expected a JSON value"));
|
|
1823
|
+
continue;
|
|
1824
|
+
}
|
|
1825
|
+
const message = validateSettingValue(field2, value);
|
|
1826
|
+
if (message !== null) out.push(issue([...path, key], "INVALID_VALUE", message));
|
|
1827
|
+
}
|
|
1828
|
+
return out;
|
|
1829
|
+
}
|
|
1830
|
+
function bindingIssues(def, name, binding, ctx, path) {
|
|
1831
|
+
const input = def.data?.[name];
|
|
1832
|
+
if (input === void 0) {
|
|
1833
|
+
return [issue(path, "UNKNOWN_PROP", `${def.title} has no data input "${name}"`)];
|
|
1834
|
+
}
|
|
1835
|
+
if (!isRec(binding) || typeof binding.source !== "string") {
|
|
1836
|
+
return [issue(path, "INVALID_SHAPE", "A binding is { source, params }")];
|
|
1837
|
+
}
|
|
1838
|
+
const { source: id } = binding;
|
|
1839
|
+
if (id.startsWith("context.")) return [];
|
|
1840
|
+
const source = ctx.registry.source(id);
|
|
1841
|
+
if (source === void 0 || !ctx.enabledSources.has(id)) {
|
|
1842
|
+
return [issue([...path, "source"], "SOURCE_NOT_ENABLED", `The data source "${id}" is not enabled`)];
|
|
1843
|
+
}
|
|
1844
|
+
const out = [];
|
|
1845
|
+
if (isRec(binding.params)) {
|
|
1846
|
+
out.push(...propIssues({ settings: source.params, title: source.title }, binding.params, [...path, "params"], false));
|
|
1847
|
+
}
|
|
1848
|
+
if (!input.accepts.includes(source.result)) {
|
|
1849
|
+
out.push(
|
|
1850
|
+
issue(
|
|
1851
|
+
path,
|
|
1852
|
+
"RESULT_TYPE_MISMATCH",
|
|
1853
|
+
`${input.label} takes ${input.accepts.join(" or ")}, but ${source.title} gives ${source.result}`
|
|
1854
|
+
)
|
|
1855
|
+
);
|
|
1856
|
+
}
|
|
1857
|
+
return out;
|
|
1858
|
+
}
|
|
1859
|
+
function widgetIssues(widget, ctx, path, inner = false) {
|
|
1860
|
+
const { type, v } = widget;
|
|
1861
|
+
if (typeof type !== "string" || typeof v !== "number") {
|
|
1862
|
+
return [issue(path, "INVALID_SHAPE", "A widget has a type and a version")];
|
|
1863
|
+
}
|
|
1864
|
+
const def = ctx.registry.widget(type, v);
|
|
1865
|
+
if (def === void 0) {
|
|
1866
|
+
return [
|
|
1867
|
+
issue(path, "INVALID_WIDGET_TYPE", `The widget "${type}" version ${String(v)} is not available`)
|
|
1868
|
+
];
|
|
1869
|
+
}
|
|
1870
|
+
const out = [];
|
|
1871
|
+
const part = checkWidgetPart(type, ctx, v);
|
|
1872
|
+
if (!part.ok) out.push(issue(path, part.code, part.message));
|
|
1873
|
+
if (inner) {
|
|
1874
|
+
const top = checkTopLevel(type, ctx, v);
|
|
1875
|
+
if (!top.ok) out.push(issue(path, top.code, top.message));
|
|
1876
|
+
}
|
|
1877
|
+
if (isRec(widget.props)) out.push(...propIssues(def, widget.props, [...path, "props"], false, true));
|
|
1878
|
+
if (isRec(widget.responsive)) {
|
|
1879
|
+
for (const device of DEVICES) {
|
|
1880
|
+
const overrides = widget.responsive[device];
|
|
1881
|
+
if (isRec(overrides)) {
|
|
1882
|
+
out.push(...propIssues(def, overrides, [...path, "responsive", device], true, true));
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
}
|
|
1886
|
+
if (isRec(widget.data)) {
|
|
1887
|
+
for (const [name, binding] of Object.entries(widget.data)) {
|
|
1888
|
+
out.push(...bindingIssues(def, name, binding, ctx, [...path, "data", name]));
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
return out;
|
|
1892
|
+
}
|
|
1893
|
+
function patchProps(node, changes) {
|
|
1894
|
+
const props = { ...isRec(node.props) ? node.props : {} };
|
|
1895
|
+
for (const [key, value] of Object.entries(changes)) {
|
|
1896
|
+
if (value === null) delete props[key];
|
|
1897
|
+
else props[key] = value;
|
|
1898
|
+
}
|
|
1899
|
+
return { ...node, props };
|
|
1900
|
+
}
|
|
1901
|
+
function patchResponsive(node, device, changes) {
|
|
1902
|
+
const responsive = { ...isRec(node.responsive) ? node.responsive : {} };
|
|
1903
|
+
const overrides = { ...isRec(responsive[device]) ? responsive[device] : {} };
|
|
1904
|
+
for (const [key, value] of Object.entries(changes)) {
|
|
1905
|
+
if (value === null) delete overrides[key];
|
|
1906
|
+
else overrides[key] = value;
|
|
1907
|
+
}
|
|
1908
|
+
if (Object.keys(overrides).length === 0) delete responsive[device];
|
|
1909
|
+
else responsive[device] = overrides;
|
|
1910
|
+
const next = { ...node };
|
|
1911
|
+
if (Object.keys(responsive).length === 0) delete next.responsive;
|
|
1912
|
+
else next.responsive = responsive;
|
|
1913
|
+
return next;
|
|
1914
|
+
}
|
|
1915
|
+
var without = (rec, key) => {
|
|
1916
|
+
const copy = { ...rec };
|
|
1917
|
+
delete copy[key];
|
|
1918
|
+
return copy;
|
|
1919
|
+
};
|
|
1920
|
+
function target(doc, id, i, field2 = "id") {
|
|
1921
|
+
const path = typeof id === "string" ? findPath(doc, id) : void 0;
|
|
1922
|
+
if (path === void 0) {
|
|
1923
|
+
return fail(at(i, field2), "NODE_NOT_FOUND", `There is no node with id "${String(id)}"`);
|
|
1924
|
+
}
|
|
1925
|
+
return { path, node: asNode(getAt(doc, path)) };
|
|
1926
|
+
}
|
|
1927
|
+
var isFailure = (value) => "issues" in value;
|
|
1928
|
+
function definitionOf(node, registry, i, field2) {
|
|
1929
|
+
const def = typeof node.type === "string" && typeof node.v === "number" ? registry.widget(node.type, node.v) : void 0;
|
|
1930
|
+
return def ?? fail(at(i, field2), "INVALID_WIDGET_TYPE", "This widget's definition is not available");
|
|
1931
|
+
}
|
|
1932
|
+
function wrapperOf(widget, used) {
|
|
1933
|
+
const sectionId = freshId(widget.id, "s", used);
|
|
1934
|
+
const columnId = freshId(widget.id, "c", used);
|
|
1935
|
+
return {
|
|
1936
|
+
id: sectionId,
|
|
1937
|
+
type: "section",
|
|
1938
|
+
props: {},
|
|
1939
|
+
columns: [{ id: columnId, type: "column", props: { width: 100 }, children: [widget] }]
|
|
1940
|
+
};
|
|
1941
|
+
}
|
|
1942
|
+
function childArray(doc, parentId) {
|
|
1943
|
+
if (parentId === "root") return { arrayPath: ["sections"], length: doc.sections.length };
|
|
1944
|
+
const path = findPath(doc, parentId);
|
|
1945
|
+
const parent = path === void 0 ? void 0 : getAt(doc, path);
|
|
1946
|
+
if (!isRec(parent) || !Array.isArray(parent.children)) return void 0;
|
|
1947
|
+
return { arrayPath: [...path, "children"], length: parent.children.length };
|
|
1948
|
+
}
|
|
1949
|
+
function stepInsert(doc, op, ctx, i) {
|
|
1950
|
+
const node = op.node;
|
|
1951
|
+
if (!isRec(node) || typeof node.type !== "string" || typeof node.id !== "string") {
|
|
1952
|
+
return fail(at(i, "node"), "INVALID_SHAPE", "A node has an id and a type");
|
|
1953
|
+
}
|
|
1954
|
+
if (op.parentId !== "root" && findPath(doc, op.parentId) === void 0) {
|
|
1955
|
+
return fail(at(i, "parentId"), "NODE_NOT_FOUND", `There is no node with id "${String(op.parentId)}"`);
|
|
1956
|
+
}
|
|
1957
|
+
const placement = canPlace(doc, { type: node.type, v: node.v }, op.parentId, ctx);
|
|
1958
|
+
if (!placement.ok) return fail(at(i, "parentId"), placement.code, placement.message);
|
|
1959
|
+
const used = collectIds(doc);
|
|
1960
|
+
const issues = [];
|
|
1961
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1962
|
+
for (const id of idsIn(node)) {
|
|
1963
|
+
if (used.has(id) || seen.has(id)) {
|
|
1964
|
+
issues.push(issue(at(i, "node"), "ID_NOT_FRESH", `The id "${id}" is already used in this document`));
|
|
1965
|
+
}
|
|
1966
|
+
seen.add(id);
|
|
1967
|
+
}
|
|
1968
|
+
for (const w of widgetsIn(node)) {
|
|
1969
|
+
issues.push(...widgetIssues(w.node, ctx, at(i, "node", ...w.path), w.inner));
|
|
1970
|
+
}
|
|
1971
|
+
if (issues.length > 0) return { issues };
|
|
1972
|
+
const container = childArray(doc, op.parentId);
|
|
1973
|
+
if (container === void 0) {
|
|
1974
|
+
return fail(at(i, "parentId"), "SECTION_NOT_NESTABLE", "Blocks can only be placed inside a column.");
|
|
1975
|
+
}
|
|
1976
|
+
if (!Number.isInteger(op.index) || op.index < 0 || op.index > container.length) {
|
|
1977
|
+
return fail(at(i, "index"), "INVALID_VALUE", `index must be 0 to ${String(container.length)}`);
|
|
1978
|
+
}
|
|
1979
|
+
const wrap = op.parentId === "root" && node.type !== "section";
|
|
1980
|
+
const item = wrap ? wrapperOf(node, /* @__PURE__ */ new Set([...used, ...seen])) : node;
|
|
1981
|
+
const list = getAt(doc, container.arrayPath);
|
|
1982
|
+
return {
|
|
1983
|
+
doc: setAt(doc, container.arrayPath, insertAtIndex(list, op.index, item)),
|
|
1984
|
+
inverse: [{ op: "remove", id: item.id }]
|
|
1985
|
+
};
|
|
1986
|
+
}
|
|
1987
|
+
function stepRemove(doc, op, i) {
|
|
1988
|
+
const found = target(doc, op.id, i);
|
|
1989
|
+
if (isFailure(found)) return found;
|
|
1990
|
+
if (found.node.type === "column") {
|
|
1991
|
+
return fail(
|
|
1992
|
+
at(i, "id"),
|
|
1993
|
+
"COLUMN_REMOVE_NEEDS_SETCOLUMNS",
|
|
1994
|
+
"A column is removed with the column controls (setColumns)."
|
|
1995
|
+
);
|
|
1996
|
+
}
|
|
1997
|
+
const { parentId, arrayPath, index } = parentOf(doc, found.path);
|
|
1998
|
+
const list = getAt(doc, arrayPath);
|
|
1999
|
+
return {
|
|
2000
|
+
doc: setAt(doc, arrayPath, list.filter((_, k) => k !== index)),
|
|
2001
|
+
inverse: [{ op: "insert", parentId, index, node: found.node }]
|
|
2002
|
+
};
|
|
2003
|
+
}
|
|
2004
|
+
function stepMove(doc, op, ctx, i) {
|
|
2005
|
+
const found = target(doc, op.id, i);
|
|
2006
|
+
if (isFailure(found)) return found;
|
|
2007
|
+
const node = found.node;
|
|
2008
|
+
if (op.parentId !== "root" && findPath(doc, op.parentId) === void 0) {
|
|
2009
|
+
return fail(at(i, "parentId"), "NODE_NOT_FOUND", `There is no node with id "${String(op.parentId)}"`);
|
|
2010
|
+
}
|
|
2011
|
+
const placement = canPlace(doc, { type: node.type, id: op.id, v: node.v }, op.parentId, ctx);
|
|
2012
|
+
if (!placement.ok) return fail(at(i, "parentId"), placement.code, placement.message);
|
|
2013
|
+
const from = parentOf(doc, found.path);
|
|
2014
|
+
const removed = setAt(
|
|
2015
|
+
doc,
|
|
2016
|
+
from.arrayPath,
|
|
2017
|
+
getAt(doc, from.arrayPath).filter((_, k) => k !== from.index)
|
|
2018
|
+
);
|
|
2019
|
+
const container = childArray(removed, op.parentId);
|
|
2020
|
+
if (container === void 0) {
|
|
2021
|
+
return fail(at(i, "parentId"), "SECTION_NOT_NESTABLE", "Blocks can only be placed inside a column.");
|
|
2022
|
+
}
|
|
2023
|
+
if (!Number.isInteger(op.index) || op.index < 0 || op.index > container.length) {
|
|
2024
|
+
return fail(at(i, "index"), "INVALID_VALUE", `index must be 0 to ${String(container.length)}`);
|
|
2025
|
+
}
|
|
2026
|
+
const wrap = op.parentId === "root" && node.type !== "section";
|
|
2027
|
+
const item = wrap ? wrapperOf(node, collectIds(doc)) : node;
|
|
2028
|
+
const list = getAt(removed, container.arrayPath);
|
|
2029
|
+
const inverse = [{ op: "move", id: op.id, parentId: from.parentId, index: from.index }];
|
|
2030
|
+
if (wrap) inverse.push({ op: "remove", id: item.id });
|
|
2031
|
+
return { doc: setAt(removed, container.arrayPath, insertAtIndex(list, op.index, item)), inverse };
|
|
2032
|
+
}
|
|
2033
|
+
function allowedKeys(node, registry, i) {
|
|
2034
|
+
if (node.type === "section" || node.type === "inner-section") return { keys: SECTION_KEYS };
|
|
2035
|
+
if (node.type === "column") return { keys: COLUMN_KEYS };
|
|
2036
|
+
const def = definitionOf(node, registry, i, "id");
|
|
2037
|
+
if (isFailure(def)) return def;
|
|
2038
|
+
return {
|
|
2039
|
+
keys: new Set([...def.settings, ...COMMON_WIDGET_SETTINGS].map((s) => s.key)),
|
|
2040
|
+
def
|
|
2041
|
+
};
|
|
2042
|
+
}
|
|
2043
|
+
function stepProps(doc, op, ctx, i) {
|
|
2044
|
+
const found = target(doc, op.id, i);
|
|
2045
|
+
if (isFailure(found)) return found;
|
|
2046
|
+
if (!isRec(op.props)) return fail(at(i, "props"), "INVALID_SHAPE", "props is an object");
|
|
2047
|
+
if (op.op === "setResponsive" && !DEVICES.includes(op.device)) {
|
|
2048
|
+
return fail(at(i, "device"), "INVALID_VALUE", 'device is "tablet" or "phone"');
|
|
2049
|
+
}
|
|
2050
|
+
const allowed = allowedKeys(found.node, ctx.registry, i);
|
|
2051
|
+
if (isFailure(allowed)) return allowed;
|
|
2052
|
+
const issues = [];
|
|
2053
|
+
for (const key of Object.keys(op.props)) {
|
|
2054
|
+
if (FORBIDDEN_KEYS.has(key)) {
|
|
2055
|
+
issues.push(issue(at(i, "props", key), "FORBIDDEN_KEY", `The key "${key}" is not allowed`));
|
|
2056
|
+
} else if (!allowed.keys.has(key)) {
|
|
2057
|
+
issues.push(issue(at(i, "props", key), "UNKNOWN_PROP", `"${key}" is not a setting of this ${String(found.node.type)}`));
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
if (issues.length === 0 && allowed.def !== void 0) {
|
|
2061
|
+
issues.push(...propIssues(allowed.def, op.props, at(i, "props"), true, true));
|
|
2062
|
+
} else if (issues.length === 0) {
|
|
2063
|
+
for (const [key, value] of Object.entries(op.props)) {
|
|
2064
|
+
if (value !== null && !isSettingValue(value)) {
|
|
2065
|
+
issues.push(issue(at(i, "props", key), "INVALID_VALUE", "Expected a JSON value"));
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
if (issues.length > 0) return { issues };
|
|
2070
|
+
const keys = Object.keys(op.props);
|
|
2071
|
+
const previous = op.op === "setProps" ? found.node.props : isRec(found.node.responsive) && isRec(found.node.responsive[op.device]) ? found.node.responsive[op.device] : {};
|
|
2072
|
+
const restore = {};
|
|
2073
|
+
for (const key of keys) restore[key] = has(previous, key) ? previous[key] : null;
|
|
2074
|
+
const next = op.op === "setProps" ? patchProps(found.node, op.props) : patchResponsive(found.node, op.device, op.props);
|
|
2075
|
+
const inverse = op.op === "setProps" ? { op: "setProps", id: op.id, props: restore } : { op: "setResponsive", id: op.id, device: op.device, props: restore };
|
|
2076
|
+
return { doc: setAt(doc, found.path, next), inverse: [inverse] };
|
|
2077
|
+
}
|
|
2078
|
+
var widthOverride = (column, device) => {
|
|
2079
|
+
const overrides = isRec(column.responsive) ? column.responsive[device] : void 0;
|
|
2080
|
+
const width = isRec(overrides) ? overrides.width : void 0;
|
|
2081
|
+
return typeof width === "number" ? width : void 0;
|
|
2082
|
+
};
|
|
2083
|
+
var clearWidthOverrides = (column) => patchResponsive(patchResponsive(column, "tablet", { width: null }), "phone", { width: null });
|
|
2084
|
+
function restoreWidthOverrides(columns) {
|
|
2085
|
+
const ops = [];
|
|
2086
|
+
for (const device of ["tablet", "phone"]) {
|
|
2087
|
+
for (const column of columns) {
|
|
2088
|
+
const width = widthOverride(column, device);
|
|
2089
|
+
if (width !== void 0) {
|
|
2090
|
+
ops.push({ op: "setResponsive", id: column.id, device, props: { width } });
|
|
2091
|
+
}
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
return ops;
|
|
2095
|
+
}
|
|
2096
|
+
function restoreColumnLooks(column) {
|
|
2097
|
+
const ops = [];
|
|
2098
|
+
const id = column.id;
|
|
2099
|
+
const props = without(column.props, "width");
|
|
2100
|
+
if (Object.keys(props).length > 0) {
|
|
2101
|
+
ops.push({ op: "setProps", id, props });
|
|
2102
|
+
}
|
|
2103
|
+
for (const device of ["tablet", "phone"]) {
|
|
2104
|
+
const overrides = isRec(column.responsive) ? column.responsive[device] : void 0;
|
|
2105
|
+
const rest = isRec(overrides) ? without(overrides, "width") : {};
|
|
2106
|
+
if (Object.keys(rest).length > 0) {
|
|
2107
|
+
ops.push({ op: "setResponsive", id, device, props: rest });
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
return ops;
|
|
2111
|
+
}
|
|
2112
|
+
function stepSetColumns(doc, op, i) {
|
|
2113
|
+
const found = target(doc, op.sectionId, i, "sectionId");
|
|
2114
|
+
if (isFailure(found)) return found;
|
|
2115
|
+
const section = found.node;
|
|
2116
|
+
if (section.type !== "section" && section.type !== "inner-section") {
|
|
2117
|
+
return fail(at(i, "sectionId"), "INVALID_VALUE", "setColumns needs a section or an inner section");
|
|
2118
|
+
}
|
|
2119
|
+
const columns = section.columns;
|
|
2120
|
+
const widths = op.widths;
|
|
2121
|
+
if (!Array.isArray(widths) || widths.some((w) => typeof w !== "number" || !Number.isFinite(w))) {
|
|
2122
|
+
return fail(at(i, "widths"), "INVALID_SHAPE", "widths is a list of numbers");
|
|
2123
|
+
}
|
|
2124
|
+
if (widths.length < LIMITS.columnsMin || widths.length > LIMITS.columnsMax) {
|
|
2125
|
+
return fail(
|
|
2126
|
+
at(i, "widths"),
|
|
2127
|
+
"COLUMN_LIMIT",
|
|
2128
|
+
`A section has ${String(LIMITS.columnsMin)} to ${String(LIMITS.columnsMax)} columns`
|
|
2129
|
+
);
|
|
2130
|
+
}
|
|
2131
|
+
const nums = widths;
|
|
2132
|
+
if (op.device !== void 0) {
|
|
2133
|
+
if (!DEVICES.includes(op.device)) {
|
|
2134
|
+
return fail(at(i, "device"), "INVALID_VALUE", 'device is "tablet" or "phone"');
|
|
2135
|
+
}
|
|
2136
|
+
if (nums.length !== columns.length) {
|
|
2137
|
+
return fail(
|
|
2138
|
+
at(i, "widths"),
|
|
2139
|
+
"INVALID_COLUMN_WIDTHS",
|
|
2140
|
+
`A ${op.device} width override must set every column of the section (${String(columns.length)})`
|
|
2141
|
+
);
|
|
2142
|
+
}
|
|
2143
|
+
const next = columns.map(
|
|
2144
|
+
(column, j) => patchResponsive(column, op.device, { width: nums[j] })
|
|
2145
|
+
);
|
|
2146
|
+
return {
|
|
2147
|
+
doc: setAt(doc, [...found.path, "columns"], next),
|
|
2148
|
+
inverse: columns.map((column) => ({
|
|
2149
|
+
op: "setResponsive",
|
|
2150
|
+
id: column.id,
|
|
2151
|
+
device: op.device,
|
|
2152
|
+
props: { width: widthOverride(column, op.device) ?? null }
|
|
2153
|
+
}))
|
|
2154
|
+
};
|
|
2155
|
+
}
|
|
2156
|
+
if (op.moveChildrenTo !== void 0 && op.moveChildrenTo !== "previous") {
|
|
2157
|
+
return fail(at(i, "moveChildrenTo"), "INVALID_VALUE", 'moveChildrenTo is "previous"');
|
|
2158
|
+
}
|
|
2159
|
+
const before = columns.map((column) => column.props.width);
|
|
2160
|
+
const n = nums.length;
|
|
2161
|
+
const m = columns.length;
|
|
2162
|
+
if (n === m) {
|
|
2163
|
+
return {
|
|
2164
|
+
doc: setAt(
|
|
2165
|
+
doc,
|
|
2166
|
+
[...found.path, "columns"],
|
|
2167
|
+
columns.map((column, j) => patchProps(column, { width: nums[j] }))
|
|
2168
|
+
),
|
|
2169
|
+
inverse: [{ op: "setColumns", sectionId: op.sectionId, widths: before }]
|
|
2170
|
+
};
|
|
2171
|
+
}
|
|
2172
|
+
const kept = columns.slice(0, Math.min(n, m)).map(
|
|
2173
|
+
(column, j) => patchProps(clearWidthOverrides(column), { width: nums[j] })
|
|
2174
|
+
);
|
|
2175
|
+
if (n > m) {
|
|
2176
|
+
const used = collectIds(doc);
|
|
2177
|
+
const given = /* @__PURE__ */ new Set();
|
|
2178
|
+
const added = [];
|
|
2179
|
+
for (let j = m; j < n; j += 1) {
|
|
2180
|
+
const wanted = Array.isArray(op.newIds) ? op.newIds[j - m] : void 0;
|
|
2181
|
+
if (wanted !== void 0) {
|
|
2182
|
+
if (typeof wanted !== "string" || used.has(wanted) || given.has(wanted)) {
|
|
2183
|
+
return fail(at(i, "newIds"), "ID_NOT_FRESH", `The id "${String(wanted)}" is already used in this document`);
|
|
2184
|
+
}
|
|
2185
|
+
given.add(wanted);
|
|
2186
|
+
used.add(wanted);
|
|
2187
|
+
}
|
|
2188
|
+
const id = wanted ?? freshId(op.sectionId, "c", used);
|
|
2189
|
+
added.push({ id, type: "column", props: { width: nums[j] }, children: [] });
|
|
2190
|
+
}
|
|
2191
|
+
return {
|
|
2192
|
+
doc: setAt(doc, [...found.path, "columns"], [...kept, ...added]),
|
|
2193
|
+
inverse: [
|
|
2194
|
+
{ op: "setColumns", sectionId: op.sectionId, widths: before },
|
|
2195
|
+
...restoreWidthOverrides(columns)
|
|
2196
|
+
]
|
|
2197
|
+
};
|
|
2198
|
+
}
|
|
2199
|
+
const removed = columns.slice(n);
|
|
2200
|
+
const orphans = removed.flatMap((column) => column.children);
|
|
2201
|
+
if (orphans.length > 0 && op.moveChildrenTo !== "previous") {
|
|
2202
|
+
return fail(
|
|
2203
|
+
at(i, "moveChildrenTo"),
|
|
2204
|
+
"COLUMN_NOT_EMPTY",
|
|
2205
|
+
"A column that still has blocks can't be removed. Move its blocks to the previous column first."
|
|
2206
|
+
);
|
|
2207
|
+
}
|
|
2208
|
+
const survivor = kept[n - 1];
|
|
2209
|
+
kept[n - 1] = { ...survivor, children: [...survivor.children, ...orphans] };
|
|
2210
|
+
const inverse = [
|
|
2211
|
+
{ op: "setColumns", sectionId: op.sectionId, widths: before, newIds: removed.map((c) => c.id) },
|
|
2212
|
+
...removed.flatMap(restoreColumnLooks),
|
|
2213
|
+
...removed.flatMap(
|
|
2214
|
+
(column) => column.children.map(
|
|
2215
|
+
(child, k) => ({ op: "move", id: child.id, parentId: column.id, index: k })
|
|
2216
|
+
)
|
|
2217
|
+
),
|
|
2218
|
+
...restoreWidthOverrides(columns)
|
|
2219
|
+
];
|
|
2220
|
+
return { doc: setAt(doc, [...found.path, "columns"], kept), inverse };
|
|
2221
|
+
}
|
|
2222
|
+
function stepSetData(doc, op, ctx, i) {
|
|
2223
|
+
const found = target(doc, op.id, i);
|
|
2224
|
+
if (isFailure(found)) return found;
|
|
2225
|
+
const node = found.node;
|
|
2226
|
+
if (node.type === "section" || node.type === "inner-section" || node.type === "column") {
|
|
2227
|
+
return fail(at(i, "id"), "INVALID_VALUE", "Only a widget has data inputs");
|
|
2228
|
+
}
|
|
2229
|
+
if (typeof op.name !== "string" || FORBIDDEN_KEYS.has(op.name)) {
|
|
2230
|
+
return fail(at(i, "name"), "FORBIDDEN_KEY", `The key "${String(op.name)}" is not allowed`);
|
|
2231
|
+
}
|
|
2232
|
+
const def = definitionOf(node, ctx.registry, i, "id");
|
|
2233
|
+
if (isFailure(def)) return def;
|
|
2234
|
+
const data = isRec(node.data) ? node.data : {};
|
|
2235
|
+
const previous = has(data, op.name) ? data[op.name] : null;
|
|
2236
|
+
if (op.binding !== null) {
|
|
2237
|
+
const issues = bindingIssues(def, op.name, op.binding, ctx, at(i, "binding"));
|
|
2238
|
+
if (issues.length > 0) return { issues };
|
|
2239
|
+
} else if (def.data?.[op.name] === void 0) {
|
|
2240
|
+
return fail(at(i, "name"), "UNKNOWN_PROP", `${def.title} has no data input "${op.name}"`);
|
|
2241
|
+
}
|
|
2242
|
+
const nextData = { ...data };
|
|
2243
|
+
if (op.binding === null) delete nextData[op.name];
|
|
2244
|
+
else nextData[op.name] = op.binding;
|
|
2245
|
+
const next = { ...node, data: nextData };
|
|
2246
|
+
if (Object.keys(nextData).length === 0) delete next.data;
|
|
2247
|
+
return {
|
|
2248
|
+
doc: setAt(doc, found.path, next),
|
|
2249
|
+
inverse: [{ op: "setData", id: op.id, name: op.name, binding: previous }]
|
|
2250
|
+
};
|
|
2251
|
+
}
|
|
2252
|
+
var isCustom = (type) => typeof type === "string" && type.startsWith("custom.");
|
|
2253
|
+
function renameAndRemove(record, renamed, removed) {
|
|
2254
|
+
const out = { ...record };
|
|
2255
|
+
for (const [from, to] of Object.entries(renamed ?? {})) {
|
|
2256
|
+
if (has(out, from) && !FORBIDDEN_KEYS.has(to)) {
|
|
2257
|
+
out[to] = out[from];
|
|
2258
|
+
delete out[from];
|
|
2259
|
+
}
|
|
2260
|
+
}
|
|
2261
|
+
for (const key of removed ?? []) delete out[key];
|
|
2262
|
+
return out;
|
|
2263
|
+
}
|
|
2264
|
+
function liftWidget(widget, toV, registry) {
|
|
2265
|
+
const type = widget.type;
|
|
2266
|
+
let props = widget.props;
|
|
2267
|
+
let responsive = isRec(widget.responsive) ? widget.responsive : void 0;
|
|
2268
|
+
for (let from = widget.v; from < toV; from += 1) {
|
|
2269
|
+
const next = registry.widget(type, from + 1);
|
|
2270
|
+
if (isCustom(type)) {
|
|
2271
|
+
if (next === void 0) return { message: `${type} version ${String(from + 1)} is not available` };
|
|
2272
|
+
props = renameAndRemove(props, next.renamed, next.removed);
|
|
2273
|
+
if (responsive !== void 0) {
|
|
2274
|
+
const lifted = {};
|
|
2275
|
+
for (const device of DEVICES) {
|
|
2276
|
+
const overrides = responsive[device];
|
|
2277
|
+
if (isRec(overrides)) lifted[device] = renameAndRemove(overrides, next.renamed, next.removed);
|
|
2278
|
+
}
|
|
2279
|
+
responsive = lifted;
|
|
2280
|
+
}
|
|
2281
|
+
} else {
|
|
2282
|
+
const migrate = next?.migrations?.[from] ?? registry.widget(type, toV)?.migrations?.[from];
|
|
2283
|
+
if (migrate !== void 0) {
|
|
2284
|
+
const run = (record) => {
|
|
2285
|
+
try {
|
|
2286
|
+
const out = migrate(cloneJson(record));
|
|
2287
|
+
return isRec(out) ? out : void 0;
|
|
2288
|
+
} catch {
|
|
2289
|
+
return void 0;
|
|
2290
|
+
}
|
|
2291
|
+
};
|
|
2292
|
+
const failed = { message: `The migration of ${type} from version ${String(from)} failed` };
|
|
2293
|
+
const migrated = run(props);
|
|
2294
|
+
if (migrated === void 0) return failed;
|
|
2295
|
+
props = migrated;
|
|
2296
|
+
if (responsive !== void 0) {
|
|
2297
|
+
const probe = run({});
|
|
2298
|
+
if (probe === void 0 || Object.keys(probe).length > 0) {
|
|
2299
|
+
return {
|
|
2300
|
+
message: `The migration of ${type} from version ${String(from)} cannot be applied to responsive overrides`
|
|
2301
|
+
};
|
|
2302
|
+
}
|
|
2303
|
+
const lifted = {};
|
|
2304
|
+
for (const device of DEVICES) {
|
|
2305
|
+
const overrides = responsive[device];
|
|
2306
|
+
if (!isRec(overrides)) continue;
|
|
2307
|
+
const out = run(overrides);
|
|
2308
|
+
if (out === void 0) return failed;
|
|
2309
|
+
lifted[device] = out;
|
|
2310
|
+
}
|
|
2311
|
+
responsive = lifted;
|
|
2312
|
+
}
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
}
|
|
2316
|
+
const node = { ...widget, v: toV, props };
|
|
2317
|
+
if (responsive !== void 0) node.responsive = responsive;
|
|
2318
|
+
return { node };
|
|
2319
|
+
}
|
|
2320
|
+
function stepUpgradeNode(doc, op, ctx, i) {
|
|
2321
|
+
const found = target(doc, op.id, i);
|
|
2322
|
+
if (isFailure(found)) return found;
|
|
2323
|
+
const node = found.node;
|
|
2324
|
+
if (node.type === "section" || node.type === "inner-section" || node.type === "column") {
|
|
2325
|
+
return fail(at(i, "id"), "INVALID_VALUE", "Only a widget has a version");
|
|
2326
|
+
}
|
|
2327
|
+
if (typeof node.type !== "string" || typeof node.v !== "number") {
|
|
2328
|
+
return fail(at(i, "id"), "INVALID_SHAPE", "A widget has a type and a version");
|
|
2329
|
+
}
|
|
2330
|
+
const targetDef = ctx.registry.widget(node.type, op.toV);
|
|
2331
|
+
if (targetDef === void 0) {
|
|
2332
|
+
return fail(at(i, "toV"), "INVALID_WIDGET_TYPE", `${node.type} version ${String(op.toV)} is not available`);
|
|
2333
|
+
}
|
|
2334
|
+
let next;
|
|
2335
|
+
if (op.restore !== void 0) {
|
|
2336
|
+
const restore = op.restore;
|
|
2337
|
+
if (!isRec(restore) || !isRec(restore.props)) {
|
|
2338
|
+
return fail(at(i, "restore"), "INVALID_SHAPE", "restore is { props, responsive? }");
|
|
2339
|
+
}
|
|
2340
|
+
if (!Number.isInteger(op.toV) || op.toV >= node.v) {
|
|
2341
|
+
return fail(at(i, "toV"), "INVALID_VALUE", `A restore goes back to a version below the current one (${String(node.v)})`);
|
|
2342
|
+
}
|
|
2343
|
+
next = { ...node, v: op.toV, props: restore.props };
|
|
2344
|
+
delete next.responsive;
|
|
2345
|
+
if (restore.responsive !== void 0) {
|
|
2346
|
+
if (!isRec(restore.responsive)) {
|
|
2347
|
+
return fail(at(i, "restore", "responsive"), "INVALID_SHAPE", "responsive is { tablet?, phone? }");
|
|
2348
|
+
}
|
|
2349
|
+
for (const [device, overrides] of Object.entries(restore.responsive)) {
|
|
2350
|
+
if (!DEVICES.includes(device) || !isRec(overrides)) {
|
|
2351
|
+
return fail(at(i, "restore", "responsive", device), "INVALID_SHAPE", "responsive holds tablet and phone objects only");
|
|
2352
|
+
}
|
|
2353
|
+
}
|
|
2354
|
+
next.responsive = restore.responsive;
|
|
2355
|
+
}
|
|
2356
|
+
const invalid = widgetIssues(next, ctx, at(i), found.path.length > 6);
|
|
2357
|
+
if (invalid.length > 0) return { issues: invalid };
|
|
2358
|
+
const replay = liftWidget(next, node.v, ctx.registry);
|
|
2359
|
+
if ("message" in replay || !deepEqual(replay.node.props, node.props) || !deepEqual(replay.node.responsive ?? {}, node.responsive ?? {})) {
|
|
2360
|
+
return fail(
|
|
2361
|
+
at(i, "restore"),
|
|
2362
|
+
"INVALID_VALUE",
|
|
2363
|
+
"A restore must be the exact inverse of an upgrade: migrating it forward must give the current node"
|
|
2364
|
+
);
|
|
2365
|
+
}
|
|
2366
|
+
} else {
|
|
2367
|
+
if (!Number.isInteger(op.toV) || op.toV <= node.v) {
|
|
2368
|
+
return fail(at(i, "toV"), "INVALID_VALUE", `toV must be higher than the current version (${String(node.v)})`);
|
|
2369
|
+
}
|
|
2370
|
+
const lifted = liftWidget(node, op.toV, ctx.registry);
|
|
2371
|
+
if ("message" in lifted) return fail(at(i, "toV"), "INVALID_VALUE", lifted.message);
|
|
2372
|
+
next = lifted.node;
|
|
2373
|
+
const invalid = widgetIssues(next, ctx, at(i), found.path.length > 6);
|
|
2374
|
+
if (invalid.length > 0) return { issues: invalid };
|
|
2375
|
+
}
|
|
2376
|
+
return {
|
|
2377
|
+
doc: setAt(doc, found.path, next),
|
|
2378
|
+
inverse: [
|
|
2379
|
+
{
|
|
2380
|
+
op: "upgradeNode",
|
|
2381
|
+
id: op.id,
|
|
2382
|
+
toV: node.v,
|
|
2383
|
+
restore: {
|
|
2384
|
+
props: node.props,
|
|
2385
|
+
...isRec(node.responsive) ? { responsive: node.responsive } : {}
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
]
|
|
2389
|
+
};
|
|
2390
|
+
}
|
|
2391
|
+
function mapShared(items, f) {
|
|
2392
|
+
let changed = false;
|
|
2393
|
+
const out = items.map((item) => {
|
|
2394
|
+
const next = f(item);
|
|
2395
|
+
if (next !== item) changed = true;
|
|
2396
|
+
return next;
|
|
2397
|
+
});
|
|
2398
|
+
return changed ? out : items;
|
|
2399
|
+
}
|
|
2400
|
+
function upgradeNodes(doc, registry) {
|
|
2401
|
+
const upgraded = [];
|
|
2402
|
+
const lift = (widget) => {
|
|
2403
|
+
const type = widget.type;
|
|
2404
|
+
if (typeof type !== "string" || typeof widget.v !== "number" || isCustom(type)) return widget;
|
|
2405
|
+
const latest = registry.latest(type);
|
|
2406
|
+
if (latest === void 0 || latest.v <= widget.v) return widget;
|
|
2407
|
+
const result = liftWidget(widget, latest.v, registry);
|
|
2408
|
+
if ("message" in result) return widget;
|
|
2409
|
+
upgraded.push(widget.id);
|
|
2410
|
+
return result.node;
|
|
2411
|
+
};
|
|
2412
|
+
const section = (node) => {
|
|
2413
|
+
const columns = mapShared(node.columns, (column) => {
|
|
2414
|
+
const children = mapShared(
|
|
2415
|
+
column.children,
|
|
2416
|
+
(child) => child.type === "inner-section" ? section(child) : lift(child)
|
|
2417
|
+
);
|
|
2418
|
+
return children === column.children ? column : { ...column, children };
|
|
2419
|
+
});
|
|
2420
|
+
return columns === node.columns ? node : { ...node, columns };
|
|
2421
|
+
};
|
|
2422
|
+
const sections = mapShared(doc.sections, section);
|
|
2423
|
+
return {
|
|
2424
|
+
doc: sections === doc.sections ? doc : { ...doc, sections },
|
|
2425
|
+
upgraded
|
|
2426
|
+
};
|
|
2427
|
+
}
|
|
2428
|
+
function stepReplace(op, doc, ctx, i) {
|
|
2429
|
+
const result = validateDocument(op.document);
|
|
2430
|
+
if (!result.ok) {
|
|
2431
|
+
return {
|
|
2432
|
+
issues: result.issues.map((found) => ({
|
|
2433
|
+
...found,
|
|
2434
|
+
path: found.path === "" ? "ops[" + String(i) + "].document" : `ops[${String(i)}].document.${found.path}`
|
|
2435
|
+
}))
|
|
2436
|
+
};
|
|
2437
|
+
}
|
|
2438
|
+
const issues = [];
|
|
2439
|
+
walkNodes(result.doc, (node, path) => {
|
|
2440
|
+
if (node.type !== "section" && node.type !== "inner-section" && node.type !== "column") {
|
|
2441
|
+
issues.push(
|
|
2442
|
+
...widgetIssues(node, ctx, at(i, "document", ...path), path.length > 6)
|
|
2443
|
+
);
|
|
2444
|
+
}
|
|
2445
|
+
});
|
|
2446
|
+
if (issues.length > 0) return { issues };
|
|
2447
|
+
return { doc: result.doc, inverse: [{ op: "replaceDocument", document: doc }] };
|
|
2448
|
+
}
|
|
2449
|
+
function applyOne(doc, op, ctx, i) {
|
|
2450
|
+
if (!isRec(op)) return fail(at(i), "INVALID_SHAPE", "An op is an object");
|
|
2451
|
+
switch (op.op) {
|
|
2452
|
+
case "insert":
|
|
2453
|
+
return stepInsert(doc, op, ctx, i);
|
|
2454
|
+
case "remove":
|
|
2455
|
+
return stepRemove(doc, op, i);
|
|
2456
|
+
case "move":
|
|
2457
|
+
return stepMove(doc, op, ctx, i);
|
|
2458
|
+
case "setProps":
|
|
2459
|
+
case "setResponsive":
|
|
2460
|
+
return stepProps(doc, op, ctx, i);
|
|
2461
|
+
case "setColumns":
|
|
2462
|
+
return stepSetColumns(doc, op, i);
|
|
2463
|
+
case "setData":
|
|
2464
|
+
return stepSetData(doc, op, ctx, i);
|
|
2465
|
+
case "replaceDocument":
|
|
2466
|
+
return stepReplace(op, doc, ctx, i);
|
|
2467
|
+
case "upgradeNode":
|
|
2468
|
+
return stepUpgradeNode(doc, op, ctx, i);
|
|
2469
|
+
default:
|
|
2470
|
+
return fail(at(i, "op"), "INVALID_SHAPE", `Unknown op "${String(op.op)}"`);
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
function applyOps(doc, ops, ctx) {
|
|
2474
|
+
if (!Array.isArray(ops)) {
|
|
2475
|
+
return { ok: false, issues: [issue(["ops"], "INVALID_SHAPE", "ops is a list of operations")] };
|
|
2476
|
+
}
|
|
2477
|
+
let working = doc;
|
|
2478
|
+
for (const [i, op] of ops.entries()) {
|
|
2479
|
+
const step = applyOne(working, op, ctx, i);
|
|
2480
|
+
if (isFailure(step)) return { ok: false, issues: capIssues(step.issues) };
|
|
2481
|
+
working = step.doc;
|
|
2482
|
+
}
|
|
2483
|
+
if (working === doc) return { ok: true, doc };
|
|
2484
|
+
const checked = validateDocument(working);
|
|
2485
|
+
if (!checked.ok) return { ok: false, issues: checked.issues };
|
|
2486
|
+
return { ok: true, doc: working };
|
|
2487
|
+
}
|
|
2488
|
+
function invertOps(before, ops, ctx) {
|
|
2489
|
+
let doc = before;
|
|
2490
|
+
const inverse = [];
|
|
2491
|
+
for (const [i, op] of ops.entries()) {
|
|
2492
|
+
const step = applyOne(doc, op, ctx, i);
|
|
2493
|
+
if (isFailure(step)) {
|
|
2494
|
+
throw new Error(`Cannot invert: ${step.issues[0]?.message ?? "an op does not apply"}`);
|
|
2495
|
+
}
|
|
2496
|
+
doc = step.doc;
|
|
2497
|
+
inverse.unshift(...step.inverse);
|
|
2498
|
+
}
|
|
2499
|
+
return inverse;
|
|
2500
|
+
}
|
|
2501
|
+
|
|
2502
|
+
// src/op-schema.ts
|
|
2503
|
+
import { z as z5 } from "zod";
|
|
2504
|
+
var parentIdSchema = z5.union([z5.literal("root"), nodeIdSchema]);
|
|
2505
|
+
var deviceSchema = z5.enum(["tablet", "phone"]);
|
|
2506
|
+
var propsSchema = safeRecord(settingValueSchema);
|
|
2507
|
+
var dataNameSchema2 = z5.string().regex(/^[a-z][A-Za-z0-9_]{0,39}$/);
|
|
2508
|
+
var INDEX_MAX = 1e4;
|
|
2509
|
+
var overridesSchema = z5.object({ tablet: propsSchema.optional(), phone: propsSchema.optional() }).strict();
|
|
2510
|
+
var insertOp = z5.object({
|
|
2511
|
+
op: z5.literal("insert"),
|
|
2512
|
+
parentId: parentIdSchema,
|
|
2513
|
+
index: z5.number().int().min(0).max(INDEX_MAX),
|
|
2514
|
+
node: z5.union([sectionNodeSchema, innerSectionNodeSchema, widgetNodeSchema])
|
|
2515
|
+
}).strict();
|
|
2516
|
+
var removeOp = z5.object({ op: z5.literal("remove"), id: nodeIdSchema }).strict();
|
|
2517
|
+
var moveOp = z5.object({
|
|
2518
|
+
op: z5.literal("move"),
|
|
2519
|
+
id: nodeIdSchema,
|
|
2520
|
+
parentId: parentIdSchema,
|
|
2521
|
+
index: z5.number().int().min(0).max(INDEX_MAX)
|
|
2522
|
+
}).strict();
|
|
2523
|
+
var setPropsOp = z5.object({ op: z5.literal("setProps"), id: nodeIdSchema, props: propsSchema }).strict();
|
|
2524
|
+
var setResponsiveOp = z5.object({
|
|
2525
|
+
op: z5.literal("setResponsive"),
|
|
2526
|
+
id: nodeIdSchema,
|
|
2527
|
+
device: deviceSchema,
|
|
2528
|
+
props: propsSchema
|
|
2529
|
+
}).strict();
|
|
2530
|
+
var setColumnsOp = z5.object({
|
|
2531
|
+
op: z5.literal("setColumns"),
|
|
2532
|
+
sectionId: nodeIdSchema,
|
|
2533
|
+
widths: z5.array(z5.number().finite()).max(50),
|
|
2534
|
+
device: deviceSchema.optional(),
|
|
2535
|
+
moveChildrenTo: z5.literal("previous").optional(),
|
|
2536
|
+
newIds: z5.array(nodeIdSchema).max(50).optional()
|
|
2537
|
+
}).strict();
|
|
2538
|
+
var setDataOp = z5.object({
|
|
2539
|
+
op: z5.literal("setData"),
|
|
2540
|
+
id: nodeIdSchema,
|
|
2541
|
+
name: dataNameSchema2,
|
|
2542
|
+
binding: dataBindingSchema.nullable()
|
|
2543
|
+
}).strict();
|
|
2544
|
+
var replaceDocumentOp = z5.object({ op: z5.literal("replaceDocument"), document: pageDocumentSchema }).strict();
|
|
2545
|
+
var upgradeNodeShape = { op: z5.literal("upgradeNode"), id: nodeIdSchema, toV: z5.number().int().min(1).max(9999) };
|
|
2546
|
+
var upgradeNodeOp = z5.object({
|
|
2547
|
+
...upgradeNodeShape,
|
|
2548
|
+
restore: z5.object({ props: propsSchema, responsive: overridesSchema.optional() }).strict().optional()
|
|
2549
|
+
}).strict();
|
|
2550
|
+
var agentUpgradeNodeOp = z5.object(upgradeNodeShape).strict();
|
|
2551
|
+
var docOpSchema = z5.discriminatedUnion("op", [
|
|
2552
|
+
insertOp,
|
|
2553
|
+
removeOp,
|
|
2554
|
+
moveOp,
|
|
2555
|
+
setPropsOp,
|
|
2556
|
+
setResponsiveOp,
|
|
2557
|
+
setColumnsOp,
|
|
2558
|
+
setDataOp,
|
|
2559
|
+
replaceDocumentOp,
|
|
2560
|
+
upgradeNodeOp
|
|
2561
|
+
]);
|
|
2562
|
+
var AGENT_MAX_OPS = 500;
|
|
2563
|
+
var agentDocOpSchema = z5.discriminatedUnion("op", [
|
|
2564
|
+
insertOp,
|
|
2565
|
+
removeOp,
|
|
2566
|
+
moveOp,
|
|
2567
|
+
setPropsOp,
|
|
2568
|
+
setResponsiveOp,
|
|
2569
|
+
setColumnsOp,
|
|
2570
|
+
setDataOp,
|
|
2571
|
+
agentUpgradeNodeOp
|
|
2572
|
+
]);
|
|
2573
|
+
var agentDocOpsSchema = z5.array(agentDocOpSchema).min(1).max(AGENT_MAX_OPS);
|
|
2574
|
+
|
|
2575
|
+
// src/urls.ts
|
|
2576
|
+
var MAX_URL_LENGTH = 2e3;
|
|
2577
|
+
var NOT_PLAIN_ASCII = /[^\x21-\x7E]/;
|
|
2578
|
+
var MARKUP_OR_BACKSLASH = /[\\<>"'`]/;
|
|
2579
|
+
var CHARACTER_REFERENCE = /&#|&[a-z][a-z0-9]*;/i;
|
|
2580
|
+
var ABSOLUTE = /^(https):\/\/([^/?#]*)(.*)$/is;
|
|
2581
|
+
var AUTHORITY = /^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?(?::[0-9]{1,5})?$/;
|
|
2582
|
+
function plain(value) {
|
|
2583
|
+
return value.length > 0 && value.length <= MAX_URL_LENGTH && !NOT_PLAIN_ASCII.test(value) && !MARKUP_OR_BACKSLASH.test(value) && !CHARACTER_REFERENCE.test(value);
|
|
2584
|
+
}
|
|
2585
|
+
function originOf(value) {
|
|
2586
|
+
const match = ABSOLUTE.exec(value);
|
|
2587
|
+
if (match === null) return null;
|
|
2588
|
+
const [, scheme, authority] = match;
|
|
2589
|
+
if (authority === void 0 || !AUTHORITY.test(authority)) return null;
|
|
2590
|
+
return `${scheme.toLowerCase()}://${authority.toLowerCase()}`;
|
|
2591
|
+
}
|
|
2592
|
+
function safeUrl(value, kind, ctx) {
|
|
2593
|
+
if (typeof value !== "string" || !plain(value)) return null;
|
|
2594
|
+
if (kind === "href") {
|
|
2595
|
+
if (value.startsWith("/")) return value[1] === "/" ? null : value;
|
|
2596
|
+
return originOf(value) === null ? null : value;
|
|
2597
|
+
}
|
|
2598
|
+
const media = originOf(ctx.mediaOrigin.replace(/\/+$/, ""));
|
|
2599
|
+
return media !== null && originOf(value) === media ? value : null;
|
|
2600
|
+
}
|
|
2601
|
+
|
|
2602
|
+
// src/template/ast.ts
|
|
2603
|
+
var TEMPLATE_FILTERS = ["upper", "lower", "truncate", "default"];
|
|
2604
|
+
var ALLOWED_ELEMENTS = [
|
|
2605
|
+
"div",
|
|
2606
|
+
"span",
|
|
2607
|
+
"p",
|
|
2608
|
+
"h1",
|
|
2609
|
+
"h2",
|
|
2610
|
+
"h3",
|
|
2611
|
+
"h4",
|
|
2612
|
+
"h5",
|
|
2613
|
+
"h6",
|
|
2614
|
+
"a",
|
|
2615
|
+
"img",
|
|
2616
|
+
"ul",
|
|
2617
|
+
"ol",
|
|
2618
|
+
"li",
|
|
2619
|
+
"strong",
|
|
2620
|
+
"em",
|
|
2621
|
+
"small",
|
|
2622
|
+
"figure",
|
|
2623
|
+
"figcaption",
|
|
2624
|
+
"section",
|
|
2625
|
+
"article",
|
|
2626
|
+
"header",
|
|
2627
|
+
"footer",
|
|
2628
|
+
"br",
|
|
2629
|
+
"hr"
|
|
2630
|
+
];
|
|
2631
|
+
var VOID_ELEMENTS = ["img", "br", "hr"];
|
|
2632
|
+
var ALLOWED_ATTRS = {
|
|
2633
|
+
"*": ["class", "title", "aria-label", "aria-hidden", "role"],
|
|
2634
|
+
a: ["href"],
|
|
2635
|
+
img: ["src", "alt"]
|
|
2636
|
+
};
|
|
2637
|
+
var ALLOWED_ROLES = [
|
|
2638
|
+
"article",
|
|
2639
|
+
"banner",
|
|
2640
|
+
"complementary",
|
|
2641
|
+
"contentinfo",
|
|
2642
|
+
"figure",
|
|
2643
|
+
"group",
|
|
2644
|
+
"heading",
|
|
2645
|
+
"img",
|
|
2646
|
+
"list",
|
|
2647
|
+
"listitem",
|
|
2648
|
+
"none",
|
|
2649
|
+
"note",
|
|
2650
|
+
"presentation",
|
|
2651
|
+
"region",
|
|
2652
|
+
"separator"
|
|
2653
|
+
];
|
|
2654
|
+
var RESERVED_CLASS_PREFIXES = ["b-", "tb-", "tsf-", "throttle-"];
|
|
2655
|
+
var isReservedClass = (name) => RESERVED_CLASS_PREFIXES.some((prefix) => name.startsWith(prefix));
|
|
2656
|
+
var BIDI_CONTROL_RE = /[\u202A-\u202E\u2066-\u2069]/;
|
|
2657
|
+
var CLASS_TOKEN_RE = /^[a-z][a-z0-9-]{0,40}$/;
|
|
2658
|
+
var DATA_ATTR_RE = /^data-[a-z][a-z0-9-]{0,40}$/;
|
|
2659
|
+
var RESERVED_DATA_PREFIX = "data-b-";
|
|
2660
|
+
var MAX_TEMPLATE_WEIGHT = 2e4;
|
|
2661
|
+
var EACH_ITERATION_CAP = 100;
|
|
2662
|
+
function templateWeight(ast, multiplier = 1) {
|
|
2663
|
+
let total = 0;
|
|
2664
|
+
for (const node of ast) {
|
|
2665
|
+
total += multiplier;
|
|
2666
|
+
switch (node.type) {
|
|
2667
|
+
case "if":
|
|
2668
|
+
total += templateWeight(node.then, multiplier) + templateWeight(node.else, multiplier);
|
|
2669
|
+
break;
|
|
2670
|
+
case "unless":
|
|
2671
|
+
total += templateWeight(node.body, multiplier);
|
|
2672
|
+
break;
|
|
2673
|
+
case "each":
|
|
2674
|
+
total += templateWeight(node.body, multiplier * EACH_ITERATION_CAP);
|
|
2675
|
+
break;
|
|
2676
|
+
case "element":
|
|
2677
|
+
for (const attr of node.attrs) total += multiplier * attr.value.length;
|
|
2678
|
+
total += templateWeight(node.children, multiplier);
|
|
2679
|
+
break;
|
|
2680
|
+
default:
|
|
2681
|
+
break;
|
|
2682
|
+
}
|
|
2683
|
+
}
|
|
2684
|
+
return total;
|
|
2685
|
+
}
|
|
2686
|
+
|
|
2687
|
+
// src/template/lexer.ts
|
|
2688
|
+
var TemplateError = class extends Error {
|
|
2689
|
+
constructor(code, message, pos) {
|
|
2690
|
+
super(message);
|
|
2691
|
+
this.code = code;
|
|
2692
|
+
this.pos = pos;
|
|
2693
|
+
}
|
|
2694
|
+
};
|
|
2695
|
+
var isLetter = (c) => c !== void 0 && (c >= "a" && c <= "z" || c >= "A" && c <= "Z");
|
|
2696
|
+
var isDigit = (c) => c !== void 0 && c >= "0" && c <= "9";
|
|
2697
|
+
var isSpace = (c) => c === " " || c === " " || c === "\n" || c === "\r" || c === "\f";
|
|
2698
|
+
function readMustache(src, i) {
|
|
2699
|
+
if (src[i + 2] === "{") {
|
|
2700
|
+
throw new TemplateError(
|
|
2701
|
+
"TEMPLATE_FORBIDDEN",
|
|
2702
|
+
"Triple-stash {{{ }}} (raw output) is not allowed. Use {{ }}, which always escapes.",
|
|
2703
|
+
i
|
|
2704
|
+
);
|
|
2705
|
+
}
|
|
2706
|
+
const end = src.indexOf("}}", i + 2);
|
|
2707
|
+
if (end === -1) throw new TemplateError("TEMPLATE_SYNTAX", "This {{ is never closed with }}", i);
|
|
2708
|
+
const body = src.slice(i + 2, end);
|
|
2709
|
+
if (body.includes("{{")) {
|
|
2710
|
+
throw new TemplateError("TEMPLATE_SYNTAX", "A {{ }} tag cannot contain another {{", i);
|
|
2711
|
+
}
|
|
2712
|
+
return { body, next: end + 2 };
|
|
2713
|
+
}
|
|
2714
|
+
function readAttributeValue(src, start) {
|
|
2715
|
+
const quote = src[start];
|
|
2716
|
+
if (quote !== '"' && quote !== "'") {
|
|
2717
|
+
throw new TemplateError("TEMPLATE_SYNTAX", "Attribute values must be in quotes", start);
|
|
2718
|
+
}
|
|
2719
|
+
const parts = [];
|
|
2720
|
+
let text = "";
|
|
2721
|
+
let i = start + 1;
|
|
2722
|
+
while (i < src.length) {
|
|
2723
|
+
const c = src[i];
|
|
2724
|
+
if (c === quote) {
|
|
2725
|
+
if (text !== "") parts.push({ kind: "text", value: text });
|
|
2726
|
+
return { parts, next: i + 1 };
|
|
2727
|
+
}
|
|
2728
|
+
if (c === "{" && src[i + 1] === "{") {
|
|
2729
|
+
if (text !== "") parts.push({ kind: "text", value: text });
|
|
2730
|
+
text = "";
|
|
2731
|
+
const { body, next } = readMustache(src, i);
|
|
2732
|
+
parts.push({ kind: "mustache", body, pos: i });
|
|
2733
|
+
i = next;
|
|
2734
|
+
continue;
|
|
2735
|
+
}
|
|
2736
|
+
text += c;
|
|
2737
|
+
i += 1;
|
|
2738
|
+
}
|
|
2739
|
+
throw new TemplateError("TEMPLATE_SYNTAX", "This attribute value is never closed", start);
|
|
2740
|
+
}
|
|
2741
|
+
function readOpenTag(src, start) {
|
|
2742
|
+
let i = start + 1;
|
|
2743
|
+
let name = "";
|
|
2744
|
+
while (isLetter(src[i]) || isDigit(src[i]) || src[i] === "-") {
|
|
2745
|
+
name += src[i];
|
|
2746
|
+
i += 1;
|
|
2747
|
+
}
|
|
2748
|
+
const after = src[i];
|
|
2749
|
+
if (!isSpace(after) && after !== "/" && after !== ">") {
|
|
2750
|
+
throw new TemplateError("TEMPLATE_SYNTAX", `Unexpected character after <${name}`, i);
|
|
2751
|
+
}
|
|
2752
|
+
const attrs = [];
|
|
2753
|
+
for (; ; ) {
|
|
2754
|
+
while (isSpace(src[i])) i += 1;
|
|
2755
|
+
const c = src[i];
|
|
2756
|
+
if (c === void 0) throw new TemplateError("TEMPLATE_SYNTAX", `<${name}> is never closed`, start);
|
|
2757
|
+
if (c === ">") {
|
|
2758
|
+
return { token: { kind: "open", name, attrs, selfClosing: false, pos: start }, next: i + 1 };
|
|
2759
|
+
}
|
|
2760
|
+
if (c === "/") {
|
|
2761
|
+
if (src[i + 1] !== ">") throw new TemplateError("TEMPLATE_SYNTAX", "Unexpected /", i);
|
|
2762
|
+
return { token: { kind: "open", name, attrs, selfClosing: true, pos: start }, next: i + 2 };
|
|
2763
|
+
}
|
|
2764
|
+
if (!(isLetter(c) || c === "_" || c === ":")) {
|
|
2765
|
+
throw new TemplateError("TEMPLATE_SYNTAX", `Unexpected character "${c}" in <${name}>`, i);
|
|
2766
|
+
}
|
|
2767
|
+
const attrStart = i;
|
|
2768
|
+
let attrName = "";
|
|
2769
|
+
while (isLetter(src[i]) || isDigit(src[i]) || src[i] === "-" || src[i] === "_" || src[i] === ":" || src[i] === ".") {
|
|
2770
|
+
attrName += src[i];
|
|
2771
|
+
i += 1;
|
|
2772
|
+
}
|
|
2773
|
+
while (isSpace(src[i])) i += 1;
|
|
2774
|
+
if (src[i] !== "=") {
|
|
2775
|
+
attrs.push({ name: attrName, parts: null, pos: attrStart });
|
|
2776
|
+
continue;
|
|
2777
|
+
}
|
|
2778
|
+
i += 1;
|
|
2779
|
+
while (isSpace(src[i])) i += 1;
|
|
2780
|
+
const value = readAttributeValue(src, i);
|
|
2781
|
+
attrs.push({ name: attrName, parts: value.parts, pos: attrStart });
|
|
2782
|
+
i = value.next;
|
|
2783
|
+
}
|
|
2784
|
+
}
|
|
2785
|
+
function lex(src) {
|
|
2786
|
+
const tokens = [];
|
|
2787
|
+
let text = "";
|
|
2788
|
+
let textPos = 0;
|
|
2789
|
+
const flush = () => {
|
|
2790
|
+
if (text !== "") tokens.push({ kind: "text", value: text, pos: textPos });
|
|
2791
|
+
text = "";
|
|
2792
|
+
};
|
|
2793
|
+
let i = 0;
|
|
2794
|
+
while (i < src.length) {
|
|
2795
|
+
const c = src[i];
|
|
2796
|
+
if (c === "{" && src[i + 1] === "{") {
|
|
2797
|
+
flush();
|
|
2798
|
+
const { body, next } = readMustache(src, i);
|
|
2799
|
+
tokens.push({ kind: "mustache", body, pos: i });
|
|
2800
|
+
i = next;
|
|
2801
|
+
continue;
|
|
2802
|
+
}
|
|
2803
|
+
if (c === "<") {
|
|
2804
|
+
const n = src[i + 1];
|
|
2805
|
+
if (n === "!" || n === "?") {
|
|
2806
|
+
throw new TemplateError(
|
|
2807
|
+
"TEMPLATE_SYNTAX",
|
|
2808
|
+
"Comments, doctypes and processing instructions are not allowed",
|
|
2809
|
+
i
|
|
2810
|
+
);
|
|
2811
|
+
}
|
|
2812
|
+
if (n === "/") {
|
|
2813
|
+
flush();
|
|
2814
|
+
let j = i + 2;
|
|
2815
|
+
let name = "";
|
|
2816
|
+
while (isLetter(src[j]) || isDigit(src[j]) || src[j] === "-") {
|
|
2817
|
+
name += src[j];
|
|
2818
|
+
j += 1;
|
|
2819
|
+
}
|
|
2820
|
+
while (isSpace(src[j])) j += 1;
|
|
2821
|
+
if (name === "" || src[j] !== ">") {
|
|
2822
|
+
throw new TemplateError("TEMPLATE_SYNTAX", "Malformed closing tag", i);
|
|
2823
|
+
}
|
|
2824
|
+
tokens.push({ kind: "close", name, pos: i });
|
|
2825
|
+
i = j + 1;
|
|
2826
|
+
continue;
|
|
2827
|
+
}
|
|
2828
|
+
if (isLetter(n)) {
|
|
2829
|
+
flush();
|
|
2830
|
+
const { token, next } = readOpenTag(src, i);
|
|
2831
|
+
tokens.push(token);
|
|
2832
|
+
i = next;
|
|
2833
|
+
continue;
|
|
2834
|
+
}
|
|
2835
|
+
}
|
|
2836
|
+
if (text === "") textPos = i;
|
|
2837
|
+
text += c;
|
|
2838
|
+
i += 1;
|
|
2839
|
+
}
|
|
2840
|
+
flush();
|
|
2841
|
+
return tokens;
|
|
2842
|
+
}
|
|
2843
|
+
function lineCol(src, pos) {
|
|
2844
|
+
let line = 1;
|
|
2845
|
+
let col = 1;
|
|
2846
|
+
for (let i = 0; i < pos && i < src.length; i += 1) {
|
|
2847
|
+
if (src[i] === "\n") {
|
|
2848
|
+
line += 1;
|
|
2849
|
+
col = 1;
|
|
2850
|
+
} else col += 1;
|
|
2851
|
+
}
|
|
2852
|
+
return { line, col };
|
|
2853
|
+
}
|
|
2854
|
+
|
|
2855
|
+
// src/template/parse.ts
|
|
2856
|
+
var PATH_RE = /^[a-z][A-Za-z0-9]{0,39}(?:\.[a-z][A-Za-z0-9]{0,39}){0,5}$/;
|
|
2857
|
+
var VAR_RE = /^[a-z][A-Za-z0-9]{0,19}$/;
|
|
2858
|
+
var ROOTS = ["settings", "data", "locale"];
|
|
2859
|
+
var MAX_FILTERS = 4;
|
|
2860
|
+
var MAX_TRUNCATE = 500;
|
|
2861
|
+
var MAX_DEFAULT_TEXT = 200;
|
|
2862
|
+
var MAX_STATIC_ATTR = 300;
|
|
2863
|
+
var PROTO_NAMES = /* @__PURE__ */ new Set([
|
|
2864
|
+
...FORBIDDEN_KEYS,
|
|
2865
|
+
...Object.getOwnPropertyNames(Object.prototype)
|
|
2866
|
+
]);
|
|
2867
|
+
var ELEMENTS = new Set(ALLOWED_ELEMENTS);
|
|
2868
|
+
var VOIDS = new Set(VOID_ELEMENTS);
|
|
2869
|
+
var ROLES = new Set(ALLOWED_ROLES);
|
|
2870
|
+
var FILTERS = new Set(TEMPLATE_FILTERS);
|
|
2871
|
+
var HEADINGS = /* @__PURE__ */ new Set(["h1", "h2", "h3", "h4", "h5", "h6"]);
|
|
2872
|
+
var CLOSES_P = /* @__PURE__ */ new Set([
|
|
2873
|
+
"div",
|
|
2874
|
+
"p",
|
|
2875
|
+
"h1",
|
|
2876
|
+
"h2",
|
|
2877
|
+
"h3",
|
|
2878
|
+
"h4",
|
|
2879
|
+
"h5",
|
|
2880
|
+
"h6",
|
|
2881
|
+
"ul",
|
|
2882
|
+
"ol",
|
|
2883
|
+
"li",
|
|
2884
|
+
"figure",
|
|
2885
|
+
"section",
|
|
2886
|
+
"article",
|
|
2887
|
+
"header",
|
|
2888
|
+
"footer",
|
|
2889
|
+
"hr"
|
|
2890
|
+
]);
|
|
2891
|
+
var forbidden = (message, pos) => new TemplateError("TEMPLATE_FORBIDDEN", message, pos);
|
|
2892
|
+
var syntax = (message, pos) => new TemplateError("TEMPLATE_SYNTAX", message, pos);
|
|
2893
|
+
function parsePath(raw2, pos, scope) {
|
|
2894
|
+
const text = raw2.trim();
|
|
2895
|
+
if (text === "") throw syntax("Expected a path such as settings.title", pos);
|
|
2896
|
+
if (/\s/.test(text)) {
|
|
2897
|
+
throw forbidden(
|
|
2898
|
+
"Helpers, arguments and comparisons are not supported. A tag holds one path and optional filters.",
|
|
2899
|
+
pos
|
|
2900
|
+
);
|
|
2901
|
+
}
|
|
2902
|
+
if (!PATH_RE.test(text)) {
|
|
2903
|
+
throw forbidden(
|
|
2904
|
+
`"${text.slice(0, 40)}" is not a plain path. Lookups, parent paths, index access and expressions are not supported.`,
|
|
2905
|
+
pos
|
|
2906
|
+
);
|
|
2907
|
+
}
|
|
2908
|
+
const path = text.split(".");
|
|
2909
|
+
for (const segment of path) {
|
|
2910
|
+
if (PROTO_NAMES.has(segment)) throw forbidden(`"${segment}" is not allowed in a path`, pos);
|
|
2911
|
+
}
|
|
2912
|
+
const root = path[0];
|
|
2913
|
+
if (root === "settings") {
|
|
2914
|
+
if (path.length !== 2) throw syntax("A settings path is settings.<key>", pos);
|
|
2915
|
+
} else if (root === "locale") {
|
|
2916
|
+
if (path.length !== 1) throw syntax("locale has no fields", pos);
|
|
2917
|
+
} else if (root === "data") {
|
|
2918
|
+
if (path.length < 2) throw syntax("A data path is data.<input> or data.<input>.<field>", pos);
|
|
2919
|
+
} else if (!scope.includes(root)) {
|
|
2920
|
+
throw new TemplateError(
|
|
2921
|
+
"UNKNOWN_REFERENCE",
|
|
2922
|
+
`"${root}" is not settings, data, locale or a loop variable in scope`,
|
|
2923
|
+
pos
|
|
2924
|
+
);
|
|
2925
|
+
}
|
|
2926
|
+
return path;
|
|
2927
|
+
}
|
|
2928
|
+
function splitPipes(body) {
|
|
2929
|
+
const parts = [];
|
|
2930
|
+
let current = "";
|
|
2931
|
+
let quote = null;
|
|
2932
|
+
for (const c of body) {
|
|
2933
|
+
if (quote !== null) {
|
|
2934
|
+
if (c === quote) quote = null;
|
|
2935
|
+
current += c;
|
|
2936
|
+
} else if (c === '"' || c === "'") {
|
|
2937
|
+
quote = c;
|
|
2938
|
+
current += c;
|
|
2939
|
+
} else if (c === "|") {
|
|
2940
|
+
parts.push(current);
|
|
2941
|
+
current = "";
|
|
2942
|
+
} else current += c;
|
|
2943
|
+
}
|
|
2944
|
+
parts.push(current);
|
|
2945
|
+
return parts;
|
|
2946
|
+
}
|
|
2947
|
+
function parseFilter(raw2, pos) {
|
|
2948
|
+
const text = raw2.trim();
|
|
2949
|
+
const colon = text.indexOf(":");
|
|
2950
|
+
const name = (colon === -1 ? text : text.slice(0, colon)).trim();
|
|
2951
|
+
const arg = colon === -1 ? void 0 : text.slice(colon + 1).trim();
|
|
2952
|
+
if (name === "") throw syntax("Empty filter after |", pos);
|
|
2953
|
+
if (!FILTERS.has(name)) {
|
|
2954
|
+
throw forbidden(`The filter "${name.slice(0, 30)}" is not allowed. Use ${TEMPLATE_FILTERS.join(", ")}.`, pos);
|
|
2955
|
+
}
|
|
2956
|
+
if (name === "upper" || name === "lower") {
|
|
2957
|
+
if (arg !== void 0) throw syntax(`${name} takes no argument`, pos);
|
|
2958
|
+
return { name };
|
|
2959
|
+
}
|
|
2960
|
+
if (name === "truncate") {
|
|
2961
|
+
if (arg === void 0 || !/^[0-9]{1,4}$/.test(arg)) {
|
|
2962
|
+
throw syntax("truncate needs a number, such as truncate:40", pos);
|
|
2963
|
+
}
|
|
2964
|
+
const n = Number(arg);
|
|
2965
|
+
if (n < 1 || n > MAX_TRUNCATE) throw syntax(`truncate takes 1 to ${String(MAX_TRUNCATE)}`, pos);
|
|
2966
|
+
return { name: "truncate", n };
|
|
2967
|
+
}
|
|
2968
|
+
const quote = arg?.[0];
|
|
2969
|
+
if (arg === void 0 || quote !== '"' && quote !== "'" || arg.length < 2 || arg[arg.length - 1] !== quote) {
|
|
2970
|
+
throw syntax('default needs quoted text, such as default:"none"', pos);
|
|
2971
|
+
}
|
|
2972
|
+
const textValue = arg.slice(1, -1);
|
|
2973
|
+
if (/[\\\u0000-\u001F\u007F]/.test(textValue) || textValue.includes(quote)) {
|
|
2974
|
+
throw syntax("default text cannot contain a backslash, a control character or its own quote", pos);
|
|
2975
|
+
}
|
|
2976
|
+
if (textValue.length > MAX_DEFAULT_TEXT) {
|
|
2977
|
+
throw syntax(`default text is over ${String(MAX_DEFAULT_TEXT)} characters`, pos);
|
|
2978
|
+
}
|
|
2979
|
+
return { name: "default", text: textValue };
|
|
2980
|
+
}
|
|
2981
|
+
function parseOutput(body, pos, scope) {
|
|
2982
|
+
const segments = splitPipes(body);
|
|
2983
|
+
const path = parsePath(segments[0], pos, scope);
|
|
2984
|
+
const filters = segments.slice(1).map((s) => parseFilter(s, pos));
|
|
2985
|
+
if (filters.length > MAX_FILTERS) throw syntax(`At most ${String(MAX_FILTERS)} filters per output`, pos);
|
|
2986
|
+
return { type: "output", path, filters };
|
|
2987
|
+
}
|
|
2988
|
+
function classify(body, pos, scope) {
|
|
2989
|
+
const text = body.trim();
|
|
2990
|
+
if (text === "") throw syntax("Empty {{ }}", pos);
|
|
2991
|
+
const first = text[0];
|
|
2992
|
+
if (first === "#") {
|
|
2993
|
+
const words = text.slice(1).trim().split(/\s+/);
|
|
2994
|
+
const block = words[0];
|
|
2995
|
+
if (block === "if" || block === "unless") {
|
|
2996
|
+
if (words.length !== 2) {
|
|
2997
|
+
throw forbidden(`{{#${block}}} tests one path. Comparisons and expressions are not supported.`, pos);
|
|
2998
|
+
}
|
|
2999
|
+
return { kind: "open", block, path: parsePath(words[1], pos, scope) };
|
|
3000
|
+
}
|
|
3001
|
+
if (block === "each") {
|
|
3002
|
+
if (words.length !== 4 || words[2] !== "as") {
|
|
3003
|
+
throw syntax("Write {{#each path as item}}", pos);
|
|
3004
|
+
}
|
|
3005
|
+
const as = words[3];
|
|
3006
|
+
if (!VAR_RE.test(as) || ROOTS.includes(as) || PROTO_NAMES.has(as) || scope.includes(as)) {
|
|
3007
|
+
throw forbidden(`"${as.slice(0, 30)}" cannot be used as a loop variable name`, pos);
|
|
3008
|
+
}
|
|
3009
|
+
return { kind: "open", block: "each", path: parsePath(words[1], pos, scope), as };
|
|
3010
|
+
}
|
|
3011
|
+
throw forbidden(`{{#${String(block).slice(0, 30)}}} is not supported. Blocks are if, unless and each.`, pos);
|
|
3012
|
+
}
|
|
3013
|
+
if (first === "/") {
|
|
3014
|
+
return { kind: "close", block: text.slice(1).trim() };
|
|
3015
|
+
}
|
|
3016
|
+
if (text === "else") return { kind: "else" };
|
|
3017
|
+
if (!/^[a-z]/.test(first)) {
|
|
3018
|
+
throw forbidden(
|
|
3019
|
+
"Partials, comments, raw output and inverted sections are not supported",
|
|
3020
|
+
pos
|
|
3021
|
+
);
|
|
3022
|
+
}
|
|
3023
|
+
if (/^else\s/.test(text)) throw forbidden("{{else if}} is not supported", pos);
|
|
3024
|
+
return { kind: "output", node: parseOutput(text, pos, scope) };
|
|
3025
|
+
}
|
|
3026
|
+
function staticText(parts, name, pos) {
|
|
3027
|
+
let value = "";
|
|
3028
|
+
for (const part of parts) {
|
|
3029
|
+
if (part.kind === "mustache") {
|
|
3030
|
+
throw new TemplateError(
|
|
3031
|
+
"ATTRIBUTE_NOT_ALLOWED",
|
|
3032
|
+
`${name} must be static text, not a {{ }} value`,
|
|
3033
|
+
pos
|
|
3034
|
+
);
|
|
3035
|
+
}
|
|
3036
|
+
value += part.value;
|
|
3037
|
+
}
|
|
3038
|
+
return value;
|
|
3039
|
+
}
|
|
3040
|
+
function isBlockTag(body) {
|
|
3041
|
+
const t = body.trim();
|
|
3042
|
+
return t.startsWith("#") || t.startsWith("/") || t === "else" || /^else\s/.test(t);
|
|
3043
|
+
}
|
|
3044
|
+
function attrParts(parts, scope, count) {
|
|
3045
|
+
const out = [];
|
|
3046
|
+
for (const part of parts) {
|
|
3047
|
+
count();
|
|
3048
|
+
if (part.kind === "text") {
|
|
3049
|
+
out.push({ type: "text", value: part.value });
|
|
3050
|
+
continue;
|
|
3051
|
+
}
|
|
3052
|
+
if (isBlockTag(part.body)) {
|
|
3053
|
+
throw forbidden("Blocks are not allowed inside an attribute", part.pos);
|
|
3054
|
+
}
|
|
3055
|
+
out.push(classifyOutput(part.body, part.pos, scope));
|
|
3056
|
+
}
|
|
3057
|
+
return out;
|
|
3058
|
+
}
|
|
3059
|
+
function classifyOutput(body, pos, scope) {
|
|
3060
|
+
const tag = classify(body, pos, scope);
|
|
3061
|
+
if (tag.kind !== "output") throw forbidden("Blocks are not allowed inside an attribute", pos);
|
|
3062
|
+
return tag.node;
|
|
3063
|
+
}
|
|
3064
|
+
function buildAttrs(tag, raw2, scope, count) {
|
|
3065
|
+
const attrs = [];
|
|
3066
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3067
|
+
const bad = (message, pos) => new TemplateError("ATTRIBUTE_NOT_ALLOWED", message, pos);
|
|
3068
|
+
for (const attr of raw2) {
|
|
3069
|
+
const { name, pos } = attr;
|
|
3070
|
+
if (name !== name.toLowerCase()) throw bad(`Attribute "${name}" must be lower case`, pos);
|
|
3071
|
+
if (name.startsWith("on")) throw bad(`Event handler attribute "${name}" is not allowed`, pos);
|
|
3072
|
+
if (name === "style") throw bad("The style attribute is not allowed. Use the CSS block.", pos);
|
|
3073
|
+
if (name === "id") throw bad("The id attribute is not allowed", pos);
|
|
3074
|
+
const isData = name.startsWith("data-");
|
|
3075
|
+
const allowed = (ALLOWED_ATTRS["*"] ?? []).includes(name) || (ALLOWED_ATTRS[tag] ?? []).includes(name);
|
|
3076
|
+
if (isData) {
|
|
3077
|
+
if (!DATA_ATTR_RE.test(name) || name.startsWith(RESERVED_DATA_PREFIX)) {
|
|
3078
|
+
throw bad(`"${name}" is not an allowed data attribute (data-b- is reserved)`, pos);
|
|
3079
|
+
}
|
|
3080
|
+
} else if (!allowed) {
|
|
3081
|
+
throw bad(`<${tag}> cannot have the attribute "${name}"`, pos);
|
|
3082
|
+
}
|
|
3083
|
+
if (seen.has(name)) throw bad(`Duplicate attribute "${name}"`, pos);
|
|
3084
|
+
seen.add(name);
|
|
3085
|
+
if (attr.parts === null) throw bad(`Attribute "${name}" needs a value`, pos);
|
|
3086
|
+
const parts = attr.parts;
|
|
3087
|
+
if (isData || name === "class" || name === "aria-hidden" || name === "role") {
|
|
3088
|
+
const value = staticText(parts, name, pos);
|
|
3089
|
+
count();
|
|
3090
|
+
if (/[\u0000-\u001F\u007F]/.test(value) || value.length > MAX_STATIC_ATTR) {
|
|
3091
|
+
throw bad(`"${name}" has a control character or is too long`, pos);
|
|
3092
|
+
}
|
|
3093
|
+
if (name === "class") {
|
|
3094
|
+
const tokens = value.split(/\s+/).filter((t) => t !== "");
|
|
3095
|
+
if (tokens.length === 0 || tokens.length > 10 || !tokens.every((t) => CLASS_TOKEN_RE.test(t))) {
|
|
3096
|
+
throw bad("class takes 1 to 10 tokens of lower case letters, digits and -, starting with a letter", pos);
|
|
3097
|
+
}
|
|
3098
|
+
const reserved = tokens.find(isReservedClass);
|
|
3099
|
+
if (reserved !== void 0) {
|
|
3100
|
+
throw bad(`The class "${reserved}" starts with a prefix reserved for the platform (b-, tb-, tsf-, throttle-)`, pos);
|
|
3101
|
+
}
|
|
3102
|
+
attrs.push({ name, value: [{ type: "text", value: tokens.join(" ") }] });
|
|
3103
|
+
continue;
|
|
3104
|
+
}
|
|
3105
|
+
if (name === "aria-hidden" && value !== "true" && value !== "false") {
|
|
3106
|
+
throw bad('aria-hidden is "true" or "false"', pos);
|
|
3107
|
+
}
|
|
3108
|
+
if (name === "role" && !ROLES.has(value)) {
|
|
3109
|
+
throw bad(`role "${value.slice(0, 30)}" is not allowed`, pos);
|
|
3110
|
+
}
|
|
3111
|
+
attrs.push({ name, value: [{ type: "text", value }] });
|
|
3112
|
+
continue;
|
|
3113
|
+
}
|
|
3114
|
+
if (name === "href" || name === "src") {
|
|
3115
|
+
if (parts.length === 1 && parts[0]?.kind === "mustache") {
|
|
3116
|
+
const out = attrParts(parts, scope, count)[0];
|
|
3117
|
+
if (out.type === "output" && out.filters.length > 0) {
|
|
3118
|
+
throw bad(`${name} takes a value as it is, with no filters`, pos);
|
|
3119
|
+
}
|
|
3120
|
+
attrs.push({ name, value: [out] });
|
|
3121
|
+
continue;
|
|
3122
|
+
}
|
|
3123
|
+
if (name === "src") {
|
|
3124
|
+
throw bad("src must be one {{ }} value: an image setting or an image field", pos);
|
|
3125
|
+
}
|
|
3126
|
+
const value = staticText(parts, name, pos);
|
|
3127
|
+
count();
|
|
3128
|
+
if (safeUrl(value, "href", { mediaOrigin: "" }) === null) {
|
|
3129
|
+
throw bad("A fixed href must be an https:// URL or a path starting with /", pos);
|
|
3130
|
+
}
|
|
3131
|
+
attrs.push({ name, value: [{ type: "text", value }] });
|
|
3132
|
+
continue;
|
|
3133
|
+
}
|
|
3134
|
+
const built = attrParts(parts, scope, count);
|
|
3135
|
+
const staticLength = built.reduce((n, p) => n + (p.type === "text" ? p.value.length : 0), 0);
|
|
3136
|
+
if (staticLength > MAX_STATIC_ATTR) throw bad(`"${name}" is too long`, pos);
|
|
3137
|
+
attrs.push({ name, value: built });
|
|
3138
|
+
}
|
|
3139
|
+
return attrs;
|
|
3140
|
+
}
|
|
3141
|
+
var Parser = class {
|
|
3142
|
+
constructor(tokens) {
|
|
3143
|
+
this.tokens = tokens;
|
|
3144
|
+
this.index = 0;
|
|
3145
|
+
this.nodes = 0;
|
|
3146
|
+
this.depth = 0;
|
|
3147
|
+
this.count = () => {
|
|
3148
|
+
this.nodes += 1;
|
|
3149
|
+
if (this.nodes > LIMITS.templateAstNodes) {
|
|
3150
|
+
throw new TemplateError(
|
|
3151
|
+
"LIMIT_EXCEEDED",
|
|
3152
|
+
`A template has at most ${String(LIMITS.templateAstNodes)} nodes`,
|
|
3153
|
+
this.tokens[this.index - 1]?.pos ?? 0
|
|
3154
|
+
);
|
|
3155
|
+
}
|
|
3156
|
+
};
|
|
3157
|
+
}
|
|
3158
|
+
enter(pos) {
|
|
3159
|
+
this.depth += 1;
|
|
3160
|
+
if (this.depth > LIMITS.templateAstDepth) {
|
|
3161
|
+
throw new TemplateError(
|
|
3162
|
+
"LIMIT_EXCEEDED",
|
|
3163
|
+
`A template nests at most ${String(LIMITS.templateAstDepth)} levels deep`,
|
|
3164
|
+
pos
|
|
3165
|
+
);
|
|
3166
|
+
}
|
|
3167
|
+
}
|
|
3168
|
+
parseAll() {
|
|
3169
|
+
const { nodes, end } = this.parseNodes("root", [], 0, []);
|
|
3170
|
+
if (end !== null) throw this.unexpected(end);
|
|
3171
|
+
return nodes;
|
|
3172
|
+
}
|
|
3173
|
+
unexpected(token) {
|
|
3174
|
+
if (token.kind === "close") {
|
|
3175
|
+
return syntax(`Unexpected </${token.name}>`, token.pos);
|
|
3176
|
+
}
|
|
3177
|
+
if (token.kind === "mustache") {
|
|
3178
|
+
return syntax(`Unexpected {{${token.body.trim()}}}`, token.pos);
|
|
3179
|
+
}
|
|
3180
|
+
return syntax("Unexpected token", token.pos);
|
|
3181
|
+
}
|
|
3182
|
+
/**
|
|
3183
|
+
* Reads nodes until the frame's terminator. The terminator (a closing tag,
|
|
3184
|
+
* `{{else}}` or `{{/x}}`) is consumed and returned for the caller to check.
|
|
3185
|
+
*/
|
|
3186
|
+
parseNodes(frame, scope, eachDepth, ancestors) {
|
|
3187
|
+
const nodes = [];
|
|
3188
|
+
while (this.index < this.tokens.length) {
|
|
3189
|
+
const token = this.tokens[this.index];
|
|
3190
|
+
this.index += 1;
|
|
3191
|
+
if (token.kind === "text") {
|
|
3192
|
+
this.count();
|
|
3193
|
+
nodes.push({ type: "text", value: token.value });
|
|
3194
|
+
continue;
|
|
3195
|
+
}
|
|
3196
|
+
if (token.kind === "close") {
|
|
3197
|
+
return { nodes, end: token };
|
|
3198
|
+
}
|
|
3199
|
+
if (token.kind === "open") {
|
|
3200
|
+
nodes.push(this.parseElement(token, scope, eachDepth, ancestors));
|
|
3201
|
+
continue;
|
|
3202
|
+
}
|
|
3203
|
+
const tag = classify(token.body, token.pos, scope);
|
|
3204
|
+
if (tag.kind === "output") {
|
|
3205
|
+
this.count();
|
|
3206
|
+
nodes.push(tag.node);
|
|
3207
|
+
} else if (tag.kind === "else" || tag.kind === "close") {
|
|
3208
|
+
return { nodes, end: token };
|
|
3209
|
+
} else {
|
|
3210
|
+
nodes.push(this.parseBlock(tag, token.pos, scope, eachDepth, ancestors));
|
|
3211
|
+
}
|
|
3212
|
+
}
|
|
3213
|
+
if (frame !== "root") {
|
|
3214
|
+
const last = this.tokens[this.tokens.length - 1];
|
|
3215
|
+
throw syntax("A tag or block is never closed", last?.pos ?? 0);
|
|
3216
|
+
}
|
|
3217
|
+
return { nodes, end: null };
|
|
3218
|
+
}
|
|
3219
|
+
expectClose(end, block, pos) {
|
|
3220
|
+
if (end === null || end.kind !== "mustache" || end.body.trim() !== `/${block}`) {
|
|
3221
|
+
throw syntax(`{{#${block}}} needs a matching {{/${block}}}`, end?.pos ?? pos);
|
|
3222
|
+
}
|
|
3223
|
+
}
|
|
3224
|
+
parseBlock(tag, pos, scope, eachDepth, ancestors) {
|
|
3225
|
+
this.count();
|
|
3226
|
+
this.enter(pos);
|
|
3227
|
+
let node;
|
|
3228
|
+
if (tag.block === "each") {
|
|
3229
|
+
if (eachDepth >= LIMITS.eachDepth) {
|
|
3230
|
+
throw new TemplateError(
|
|
3231
|
+
"LIMIT_EXCEEDED",
|
|
3232
|
+
`{{#each}} can be nested ${String(LIMITS.eachDepth)} levels deep at most`,
|
|
3233
|
+
pos
|
|
3234
|
+
);
|
|
3235
|
+
}
|
|
3236
|
+
const { nodes, end } = this.parseNodes("block", [...scope, tag.as], eachDepth + 1, ancestors);
|
|
3237
|
+
this.expectClose(end, "each", pos);
|
|
3238
|
+
node = { type: "each", path: tag.path, as: tag.as, body: nodes };
|
|
3239
|
+
} else if (tag.block === "unless") {
|
|
3240
|
+
const { nodes, end } = this.parseNodes("block", scope, eachDepth, ancestors);
|
|
3241
|
+
this.expectClose(end, "unless", pos);
|
|
3242
|
+
node = { type: "unless", path: tag.path, body: nodes };
|
|
3243
|
+
} else {
|
|
3244
|
+
const first = this.parseNodes("block", scope, eachDepth, ancestors);
|
|
3245
|
+
let otherwise = [];
|
|
3246
|
+
let end = first.end;
|
|
3247
|
+
if (end?.kind === "mustache" && end.body.trim() === "else") {
|
|
3248
|
+
const second = this.parseNodes("block", scope, eachDepth, ancestors);
|
|
3249
|
+
otherwise = second.nodes;
|
|
3250
|
+
end = second.end;
|
|
3251
|
+
}
|
|
3252
|
+
this.expectClose(end, "if", pos);
|
|
3253
|
+
node = { type: "if", path: tag.path, then: first.nodes, else: otherwise };
|
|
3254
|
+
}
|
|
3255
|
+
this.depth -= 1;
|
|
3256
|
+
return node;
|
|
3257
|
+
}
|
|
3258
|
+
parseElement(token, scope, eachDepth, ancestors) {
|
|
3259
|
+
const { name, pos } = token;
|
|
3260
|
+
if (!ELEMENTS.has(name)) {
|
|
3261
|
+
throw new TemplateError(
|
|
3262
|
+
"ELEMENT_NOT_ALLOWED",
|
|
3263
|
+
`<${name.slice(0, 30)}> is not an allowed element (lower case ${ALLOWED_ELEMENTS.join(" ")})`,
|
|
3264
|
+
pos
|
|
3265
|
+
);
|
|
3266
|
+
}
|
|
3267
|
+
if (name === "a" && ancestors.includes("a")) {
|
|
3268
|
+
throw new TemplateError("ELEMENT_NOT_ALLOWED", "A link cannot contain another link", pos);
|
|
3269
|
+
}
|
|
3270
|
+
if (CLOSES_P.has(name) && ancestors.includes("p")) {
|
|
3271
|
+
throw new TemplateError("ELEMENT_NOT_ALLOWED", `<${name}> cannot go inside <p>`, pos);
|
|
3272
|
+
}
|
|
3273
|
+
if (HEADINGS.has(name) && ancestors.some((a) => HEADINGS.has(a))) {
|
|
3274
|
+
throw new TemplateError("ELEMENT_NOT_ALLOWED", `<${name}> cannot go inside a heading`, pos);
|
|
3275
|
+
}
|
|
3276
|
+
if (name === "li") {
|
|
3277
|
+
const lastLi = ancestors.lastIndexOf("li");
|
|
3278
|
+
if (lastLi > Math.max(ancestors.lastIndexOf("ul"), ancestors.lastIndexOf("ol"))) {
|
|
3279
|
+
throw new TemplateError("ELEMENT_NOT_ALLOWED", "<li> cannot go directly inside another <li>", pos);
|
|
3280
|
+
}
|
|
3281
|
+
}
|
|
3282
|
+
this.count();
|
|
3283
|
+
this.enter(pos);
|
|
3284
|
+
const attrs = buildAttrs(name, token.attrs, scope, this.count);
|
|
3285
|
+
const element = { type: "element", tag: name, attrs, children: [] };
|
|
3286
|
+
if (!VOIDS.has(name) && !token.selfClosing) {
|
|
3287
|
+
const { nodes, end } = this.parseNodes("element", scope, eachDepth, [...ancestors, name]);
|
|
3288
|
+
if (end === null || end.kind !== "close" || end.name !== name) {
|
|
3289
|
+
throw syntax(`<${name}> needs a matching </${name}>`, end?.pos ?? pos);
|
|
3290
|
+
}
|
|
3291
|
+
element.children = nodes;
|
|
3292
|
+
}
|
|
3293
|
+
this.depth -= 1;
|
|
3294
|
+
return element;
|
|
3295
|
+
}
|
|
3296
|
+
};
|
|
3297
|
+
function parseTemplate(src) {
|
|
3298
|
+
if (typeof src !== "string") {
|
|
3299
|
+
return { ok: false, issues: [makeIssue("template", "INVALID_SHAPE", "The template must be text")] };
|
|
3300
|
+
}
|
|
3301
|
+
const bytes = utf8Length(src);
|
|
3302
|
+
if (bytes > LIMITS.templateSourceBytes) {
|
|
3303
|
+
return {
|
|
3304
|
+
ok: false,
|
|
3305
|
+
issues: [
|
|
3306
|
+
makeIssue(
|
|
3307
|
+
"template",
|
|
3308
|
+
"LIMIT_EXCEEDED",
|
|
3309
|
+
`Template source is ${String(bytes)} bytes, over the limit of ${String(LIMITS.templateSourceBytes)}`
|
|
3310
|
+
)
|
|
3311
|
+
]
|
|
3312
|
+
};
|
|
3313
|
+
}
|
|
3314
|
+
try {
|
|
3315
|
+
if (/[\u0000-\u0008\u000B\u000E-\u001F\u007F]/.test(src)) {
|
|
3316
|
+
throw syntax("The template contains a control character", 0);
|
|
3317
|
+
}
|
|
3318
|
+
if (BIDI_CONTROL_RE.test(src)) {
|
|
3319
|
+
throw syntax("The template contains a bidirectional override character", src.search(BIDI_CONTROL_RE));
|
|
3320
|
+
}
|
|
3321
|
+
const ast = new Parser(lex(src)).parseAll();
|
|
3322
|
+
const weight = templateWeight(ast);
|
|
3323
|
+
if (weight > MAX_TEMPLATE_WEIGHT) {
|
|
3324
|
+
return {
|
|
3325
|
+
ok: false,
|
|
3326
|
+
issues: [
|
|
3327
|
+
makeIssue(
|
|
3328
|
+
"template",
|
|
3329
|
+
"LIMIT_EXCEEDED",
|
|
3330
|
+
`A template can render at most ${String(MAX_TEMPLATE_WEIGHT)} nodes (each node counts 100 times per enclosing {{#each}}); this one can render ${String(weight)}`
|
|
3331
|
+
)
|
|
3332
|
+
]
|
|
3333
|
+
};
|
|
3334
|
+
}
|
|
3335
|
+
return { ok: true, ast };
|
|
3336
|
+
} catch (error) {
|
|
3337
|
+
if (error instanceof TemplateError) {
|
|
3338
|
+
const { line, col } = lineCol(src, error.pos);
|
|
3339
|
+
return {
|
|
3340
|
+
ok: false,
|
|
3341
|
+
issues: [makeIssue(`template:${String(line)}:${String(col)}`, error.code, error.message)]
|
|
3342
|
+
};
|
|
3343
|
+
}
|
|
3344
|
+
throw error;
|
|
3345
|
+
}
|
|
3346
|
+
}
|
|
3347
|
+
|
|
3348
|
+
// src/template/validate.ts
|
|
3349
|
+
var MONEY_PARTS = ["display", "currency"];
|
|
3350
|
+
function inputInfo(accepts, sources) {
|
|
3351
|
+
const fields = /* @__PURE__ */ new Map();
|
|
3352
|
+
for (const source of sources) {
|
|
3353
|
+
if (!accepts.includes(source.result)) continue;
|
|
3354
|
+
for (const spec of source.fields) if (!fields.has(spec.name)) fields.set(spec.name, spec);
|
|
3355
|
+
}
|
|
3356
|
+
return { listLike: accepts.some((a) => a.endsWith("[]")), fields };
|
|
3357
|
+
}
|
|
3358
|
+
var hasChildren = (fields, name) => {
|
|
3359
|
+
const prefix = `${name}.`;
|
|
3360
|
+
for (const key of fields.keys()) if (key.startsWith(prefix)) return true;
|
|
3361
|
+
return false;
|
|
3362
|
+
};
|
|
3363
|
+
function lookup(input, info, binding, rest) {
|
|
3364
|
+
const base = binding === null || binding.prefix === "" ? [] : binding.prefix.split(".");
|
|
3365
|
+
const full = [...base, ...rest];
|
|
3366
|
+
const shown = `${binding === null ? `data.${input}` : input}${rest.length > 0 ? `.${rest.join(".")}` : ""}`;
|
|
3367
|
+
if (rest.length === 0) {
|
|
3368
|
+
if (binding !== null) return binding.scalar ? { kind: "value", type: "string" } : { kind: "record" };
|
|
3369
|
+
return info.listLike ? { kind: "list", binding: { input, prefix: "", scalar: false } } : { kind: "record" };
|
|
3370
|
+
}
|
|
3371
|
+
const name = full.join(".");
|
|
3372
|
+
const leaf = full[full.length - 1];
|
|
3373
|
+
const parent = full.slice(0, -1).join(".");
|
|
3374
|
+
const parentSpec = parent === "" ? void 0 : info.fields.get(parent);
|
|
3375
|
+
if (leaf === "amount" && parent !== "" && (parentSpec?.type === "money" || info.fields.has(`${parent}.display`))) {
|
|
3376
|
+
return {
|
|
3377
|
+
kind: "error",
|
|
3378
|
+
code: "FIELD_NOT_ALLOWED",
|
|
3379
|
+
message: `"${shown}" is a money amount. Templates print money only as ${parent}.display or ${parent}.currency, never as a number.`
|
|
3380
|
+
};
|
|
3381
|
+
}
|
|
3382
|
+
const spec = info.fields.get(name);
|
|
3383
|
+
if (spec !== void 0) {
|
|
3384
|
+
if (spec.type === "list") {
|
|
3385
|
+
return {
|
|
3386
|
+
kind: "list",
|
|
3387
|
+
binding: { input, prefix: name, scalar: !hasChildren(info.fields, name) }
|
|
3388
|
+
};
|
|
3389
|
+
}
|
|
3390
|
+
if (spec.type === "money") {
|
|
3391
|
+
return MONEY_PARTS.includes(leaf) ? { kind: "value", type: "string" } : { kind: "record" };
|
|
3392
|
+
}
|
|
3393
|
+
return { kind: "value", type: spec.type };
|
|
3394
|
+
}
|
|
3395
|
+
if (parentSpec?.type === "money" && MONEY_PARTS.includes(leaf)) {
|
|
3396
|
+
return { kind: "value", type: "string" };
|
|
3397
|
+
}
|
|
3398
|
+
if (hasChildren(info.fields, name)) return { kind: "record" };
|
|
3399
|
+
return {
|
|
3400
|
+
kind: "error",
|
|
3401
|
+
code: "FIELD_NOT_ALLOWED",
|
|
3402
|
+
message: `"${shown}" is not a field of the data sources this input accepts`
|
|
3403
|
+
};
|
|
3404
|
+
}
|
|
3405
|
+
var Checker = class {
|
|
3406
|
+
constructor(ctx) {
|
|
3407
|
+
this.issues = [];
|
|
3408
|
+
this.settings = /* @__PURE__ */ new Map();
|
|
3409
|
+
this.inputs = /* @__PURE__ */ new Map();
|
|
3410
|
+
for (const field2 of ctx.settings) this.settings.set(field2.key, field2);
|
|
3411
|
+
for (const [name, input] of Object.entries(ctx.data)) {
|
|
3412
|
+
this.inputs.set(name, inputInfo(input.accepts, ctx.sources));
|
|
3413
|
+
}
|
|
3414
|
+
}
|
|
3415
|
+
fail(code, message) {
|
|
3416
|
+
this.issues.push(makeIssue("template", code, message));
|
|
3417
|
+
}
|
|
3418
|
+
resolve(path, scope) {
|
|
3419
|
+
const [root, ...rest] = path;
|
|
3420
|
+
const shown = path.join(".");
|
|
3421
|
+
if (root === "locale") return { kind: "locale" };
|
|
3422
|
+
if (root === "settings") {
|
|
3423
|
+
const field2 = this.settings.get(rest[0]);
|
|
3424
|
+
if (field2 === void 0) {
|
|
3425
|
+
return {
|
|
3426
|
+
kind: "error",
|
|
3427
|
+
code: "UNKNOWN_REFERENCE",
|
|
3428
|
+
message: `"${shown}" is not a setting of this widget`
|
|
3429
|
+
};
|
|
3430
|
+
}
|
|
3431
|
+
if (field2.output !== "markup") {
|
|
3432
|
+
return {
|
|
3433
|
+
kind: "error",
|
|
3434
|
+
code: "FIELD_NOT_ALLOWED",
|
|
3435
|
+
message: `"${shown}" is a css setting. It reaches the CSS as var(--w-${field2.key}), not the template.`
|
|
3436
|
+
};
|
|
3437
|
+
}
|
|
3438
|
+
return { kind: "setting", field: field2 };
|
|
3439
|
+
}
|
|
3440
|
+
if (root === "data") {
|
|
3441
|
+
const name = rest[0];
|
|
3442
|
+
const info2 = this.inputs.get(name);
|
|
3443
|
+
if (info2 === void 0) {
|
|
3444
|
+
return {
|
|
3445
|
+
kind: "error",
|
|
3446
|
+
code: "UNKNOWN_REFERENCE",
|
|
3447
|
+
message: `"data.${name}" is not a data input of this widget`
|
|
3448
|
+
};
|
|
3449
|
+
}
|
|
3450
|
+
return lookup(name, info2, null, rest.slice(1));
|
|
3451
|
+
}
|
|
3452
|
+
const binding = scope.get(root);
|
|
3453
|
+
const info = binding === void 0 ? void 0 : this.inputs.get(binding.input);
|
|
3454
|
+
if (binding === void 0 || info === void 0) {
|
|
3455
|
+
return { kind: "error", code: "UNKNOWN_REFERENCE", message: `"${root}" is not in scope` };
|
|
3456
|
+
}
|
|
3457
|
+
return lookup(binding.input, info, binding, rest);
|
|
3458
|
+
}
|
|
3459
|
+
/** Returns the resolved path after checking it is usable at `position`. */
|
|
3460
|
+
use(path, position, scope) {
|
|
3461
|
+
const resolved = this.resolve(path, scope);
|
|
3462
|
+
const shown = path.join(".");
|
|
3463
|
+
const bad = (message) => this.fail("FIELD_NOT_ALLOWED", message);
|
|
3464
|
+
if (resolved.kind === "error") {
|
|
3465
|
+
this.fail(resolved.code, resolved.message);
|
|
3466
|
+
return resolved;
|
|
3467
|
+
}
|
|
3468
|
+
if (position === "test") return resolved;
|
|
3469
|
+
if (position === "href") {
|
|
3470
|
+
const ok = resolved.kind === "setting" && resolved.field.control === "link" || resolved.kind === "value" && resolved.type === "url";
|
|
3471
|
+
if (!ok) bad(`href takes a link setting or a url field, not "${shown}"`);
|
|
3472
|
+
} else if (position === "src") {
|
|
3473
|
+
const ok = resolved.kind === "setting" && resolved.field.control === "image" || resolved.kind === "value" && resolved.type === "image";
|
|
3474
|
+
if (!ok) bad(`src takes an image setting or an image field, not "${shown}"`);
|
|
3475
|
+
} else if (resolved.kind === "list" || resolved.kind === "record") {
|
|
3476
|
+
bad(`"${shown}" is not a single value. Print one of its fields, or loop over it with {{#each}}.`);
|
|
3477
|
+
} else if (resolved.kind === "setting" && (resolved.field.control === "link" || resolved.field.control === "image")) {
|
|
3478
|
+
bad(`"${shown}" is a ${resolved.field.control} setting. Use it as ${resolved.field.control === "link" ? "href" : "src"}.`);
|
|
3479
|
+
}
|
|
3480
|
+
return resolved;
|
|
3481
|
+
}
|
|
3482
|
+
walk(nodes, scope, depth) {
|
|
3483
|
+
if (depth > LIMITS.templateAstDepth) {
|
|
3484
|
+
this.fail("LIMIT_EXCEEDED", `A template nests at most ${String(LIMITS.templateAstDepth)} levels deep`);
|
|
3485
|
+
return;
|
|
3486
|
+
}
|
|
3487
|
+
for (const node of nodes) {
|
|
3488
|
+
switch (node.type) {
|
|
3489
|
+
case "text":
|
|
3490
|
+
break;
|
|
3491
|
+
case "output":
|
|
3492
|
+
this.use(node.path, "text", scope);
|
|
3493
|
+
break;
|
|
3494
|
+
case "if":
|
|
3495
|
+
this.use(node.path, "test", scope);
|
|
3496
|
+
this.walk(node.then, scope, depth + 1);
|
|
3497
|
+
this.walk(node.else, scope, depth + 1);
|
|
3498
|
+
break;
|
|
3499
|
+
case "unless":
|
|
3500
|
+
this.use(node.path, "test", scope);
|
|
3501
|
+
this.walk(node.body, scope, depth + 1);
|
|
3502
|
+
break;
|
|
3503
|
+
case "each": {
|
|
3504
|
+
const resolved = this.use(node.path, "test", scope);
|
|
3505
|
+
const inner = new Map(scope);
|
|
3506
|
+
if (resolved.kind === "list") inner.set(node.as, resolved.binding);
|
|
3507
|
+
else if (resolved.kind !== "error") {
|
|
3508
|
+
this.fail("FIELD_NOT_ALLOWED", `"${node.path.join(".")}" is not a list, so {{#each}} cannot loop over it`);
|
|
3509
|
+
}
|
|
3510
|
+
this.walk(node.body, inner, depth + 1);
|
|
3511
|
+
break;
|
|
3512
|
+
}
|
|
3513
|
+
case "element":
|
|
3514
|
+
for (const attr of node.attrs) {
|
|
3515
|
+
const position = attr.name === "href" ? "href" : attr.name === "src" ? "src" : "text";
|
|
3516
|
+
for (const part of attr.value) {
|
|
3517
|
+
if (part.type === "output") this.use(part.path, position, scope);
|
|
3518
|
+
}
|
|
3519
|
+
}
|
|
3520
|
+
this.walk(node.children, scope, depth + 1);
|
|
3521
|
+
break;
|
|
3522
|
+
}
|
|
3523
|
+
}
|
|
3524
|
+
}
|
|
3525
|
+
};
|
|
3526
|
+
function validateTemplate(ast, ctx) {
|
|
3527
|
+
const checker = new Checker(ctx);
|
|
3528
|
+
checker.walk(ast, /* @__PURE__ */ new Map(), 1);
|
|
3529
|
+
return capIssues(checker.issues);
|
|
3530
|
+
}
|
|
3531
|
+
|
|
3532
|
+
// src/css/sanitize.ts
|
|
3533
|
+
var MAX_NESTING = 12;
|
|
3534
|
+
var MAX_STRING = 200;
|
|
3535
|
+
var MAX_SELECTORS = 20;
|
|
3536
|
+
var MAX_COMPOUNDS = 8;
|
|
3537
|
+
var MAX_PSEUDOS = 4;
|
|
3538
|
+
var CLASS_RE = /^[a-z][a-z0-9-]{0,40}$/;
|
|
3539
|
+
var VAR_NAME_RE = /^--w-[a-z][A-Za-z0-9]{0,39}$/;
|
|
3540
|
+
var WIDGET_TYPE = /^custom\.[a-z][a-z0-9-]{0,63}$/;
|
|
3541
|
+
var CssError = class extends Error {
|
|
3542
|
+
constructor(code, message, pos) {
|
|
3543
|
+
super(message);
|
|
3544
|
+
this.code = code;
|
|
3545
|
+
this.pos = pos;
|
|
3546
|
+
}
|
|
3547
|
+
};
|
|
3548
|
+
var forbidden2 = (message, pos) => new CssError("CSS_FORBIDDEN", message, pos);
|
|
3549
|
+
var syntax2 = (message, pos) => new CssError("CSS_SYNTAX", message, pos);
|
|
3550
|
+
var sides = (base, extra = []) => [
|
|
3551
|
+
base,
|
|
3552
|
+
...["top", "right", "bottom", "left"].map((s) => `${base}-${s}`),
|
|
3553
|
+
...extra
|
|
3554
|
+
];
|
|
3555
|
+
var PROPERTIES = /* @__PURE__ */ new Set([
|
|
3556
|
+
// box model
|
|
3557
|
+
"display",
|
|
3558
|
+
"box-sizing",
|
|
3559
|
+
"width",
|
|
3560
|
+
"min-width",
|
|
3561
|
+
"max-width",
|
|
3562
|
+
"height",
|
|
3563
|
+
"min-height",
|
|
3564
|
+
"max-height",
|
|
3565
|
+
"aspect-ratio",
|
|
3566
|
+
"overflow",
|
|
3567
|
+
"overflow-x",
|
|
3568
|
+
"overflow-y",
|
|
3569
|
+
"object-fit",
|
|
3570
|
+
"object-position",
|
|
3571
|
+
"float",
|
|
3572
|
+
"clear",
|
|
3573
|
+
"vertical-align",
|
|
3574
|
+
"visibility",
|
|
3575
|
+
...sides("margin"),
|
|
3576
|
+
...sides("padding"),
|
|
3577
|
+
// flex and grid
|
|
3578
|
+
"flex",
|
|
3579
|
+
"flex-direction",
|
|
3580
|
+
"flex-wrap",
|
|
3581
|
+
"flex-flow",
|
|
3582
|
+
"flex-grow",
|
|
3583
|
+
"flex-shrink",
|
|
3584
|
+
"flex-basis",
|
|
3585
|
+
"order",
|
|
3586
|
+
"gap",
|
|
3587
|
+
"row-gap",
|
|
3588
|
+
"column-gap",
|
|
3589
|
+
"justify-content",
|
|
3590
|
+
"justify-items",
|
|
3591
|
+
"justify-self",
|
|
3592
|
+
"align-items",
|
|
3593
|
+
"align-content",
|
|
3594
|
+
"align-self",
|
|
3595
|
+
"place-items",
|
|
3596
|
+
"place-content",
|
|
3597
|
+
"place-self",
|
|
3598
|
+
"grid-template",
|
|
3599
|
+
"grid-template-columns",
|
|
3600
|
+
"grid-template-rows",
|
|
3601
|
+
"grid-template-areas",
|
|
3602
|
+
"grid-auto-columns",
|
|
3603
|
+
"grid-auto-rows",
|
|
3604
|
+
"grid-auto-flow",
|
|
3605
|
+
"grid-column",
|
|
3606
|
+
"grid-row",
|
|
3607
|
+
"grid-area",
|
|
3608
|
+
"grid-column-start",
|
|
3609
|
+
"grid-column-end",
|
|
3610
|
+
"grid-row-start",
|
|
3611
|
+
"grid-row-end",
|
|
3612
|
+
// typography
|
|
3613
|
+
"font-family",
|
|
3614
|
+
"font-size",
|
|
3615
|
+
"font-weight",
|
|
3616
|
+
"font-style",
|
|
3617
|
+
"line-height",
|
|
3618
|
+
"letter-spacing",
|
|
3619
|
+
"word-spacing",
|
|
3620
|
+
"text-align",
|
|
3621
|
+
"text-decoration",
|
|
3622
|
+
"text-decoration-line",
|
|
3623
|
+
"text-decoration-color",
|
|
3624
|
+
"text-decoration-style",
|
|
3625
|
+
"text-decoration-thickness",
|
|
3626
|
+
"text-transform",
|
|
3627
|
+
"text-overflow",
|
|
3628
|
+
"text-indent",
|
|
3629
|
+
"white-space",
|
|
3630
|
+
"word-break",
|
|
3631
|
+
"overflow-wrap",
|
|
3632
|
+
"list-style",
|
|
3633
|
+
"list-style-type",
|
|
3634
|
+
"list-style-position",
|
|
3635
|
+
// colour
|
|
3636
|
+
"color",
|
|
3637
|
+
"opacity",
|
|
3638
|
+
"background",
|
|
3639
|
+
"background-color",
|
|
3640
|
+
"background-image",
|
|
3641
|
+
"background-position",
|
|
3642
|
+
"background-size",
|
|
3643
|
+
"background-repeat",
|
|
3644
|
+
// border, radius, shadow
|
|
3645
|
+
"border",
|
|
3646
|
+
"border-width",
|
|
3647
|
+
"border-style",
|
|
3648
|
+
"border-color",
|
|
3649
|
+
"border-collapse",
|
|
3650
|
+
"border-spacing",
|
|
3651
|
+
...sides("border"),
|
|
3652
|
+
...["top", "right", "bottom", "left"].flatMap((s) => [
|
|
3653
|
+
`border-${s}-width`,
|
|
3654
|
+
`border-${s}-style`,
|
|
3655
|
+
`border-${s}-color`
|
|
3656
|
+
]),
|
|
3657
|
+
"border-radius",
|
|
3658
|
+
"border-top-left-radius",
|
|
3659
|
+
"border-top-right-radius",
|
|
3660
|
+
"border-bottom-left-radius",
|
|
3661
|
+
"border-bottom-right-radius",
|
|
3662
|
+
"outline",
|
|
3663
|
+
"outline-width",
|
|
3664
|
+
"outline-style",
|
|
3665
|
+
"outline-color",
|
|
3666
|
+
"outline-offset",
|
|
3667
|
+
"box-shadow",
|
|
3668
|
+
"text-shadow",
|
|
3669
|
+
// transform and transition
|
|
3670
|
+
"transform",
|
|
3671
|
+
"transform-origin",
|
|
3672
|
+
"translate",
|
|
3673
|
+
"rotate",
|
|
3674
|
+
"scale",
|
|
3675
|
+
"transition",
|
|
3676
|
+
"transition-property",
|
|
3677
|
+
"transition-duration",
|
|
3678
|
+
"transition-timing-function",
|
|
3679
|
+
"transition-delay"
|
|
3680
|
+
]);
|
|
3681
|
+
var STRING_PROPERTIES = /* @__PURE__ */ new Set([
|
|
3682
|
+
"font-family",
|
|
3683
|
+
"grid-template",
|
|
3684
|
+
"grid-template-areas"
|
|
3685
|
+
]);
|
|
3686
|
+
var FUNCTIONS = /* @__PURE__ */ new Set([
|
|
3687
|
+
"calc",
|
|
3688
|
+
"min",
|
|
3689
|
+
"max",
|
|
3690
|
+
"clamp",
|
|
3691
|
+
"var",
|
|
3692
|
+
"rgb",
|
|
3693
|
+
"rgba",
|
|
3694
|
+
"hsl",
|
|
3695
|
+
"hsla",
|
|
3696
|
+
"linear-gradient",
|
|
3697
|
+
"radial-gradient",
|
|
3698
|
+
"conic-gradient",
|
|
3699
|
+
"repeating-linear-gradient",
|
|
3700
|
+
"repeating-radial-gradient",
|
|
3701
|
+
"translate",
|
|
3702
|
+
"translatex",
|
|
3703
|
+
"translatey",
|
|
3704
|
+
"translate3d",
|
|
3705
|
+
"rotate",
|
|
3706
|
+
"rotatex",
|
|
3707
|
+
"rotatey",
|
|
3708
|
+
"rotatez",
|
|
3709
|
+
"scale",
|
|
3710
|
+
"scalex",
|
|
3711
|
+
"scaley",
|
|
3712
|
+
"skew",
|
|
3713
|
+
"skewx",
|
|
3714
|
+
"skewy",
|
|
3715
|
+
"cubic-bezier",
|
|
3716
|
+
"steps",
|
|
3717
|
+
"minmax",
|
|
3718
|
+
"repeat",
|
|
3719
|
+
"fit-content"
|
|
3720
|
+
]);
|
|
3721
|
+
var LOADING_FUNCTIONS = /* @__PURE__ */ new Set([
|
|
3722
|
+
"url",
|
|
3723
|
+
"src",
|
|
3724
|
+
"image",
|
|
3725
|
+
"image-set",
|
|
3726
|
+
"-webkit-image-set",
|
|
3727
|
+
"cross-fade",
|
|
3728
|
+
"element",
|
|
3729
|
+
"paint",
|
|
3730
|
+
"expression",
|
|
3731
|
+
"attr",
|
|
3732
|
+
"env"
|
|
3733
|
+
]);
|
|
3734
|
+
var FORBIDDEN_IDENTS = /* @__PURE__ */ new Set([
|
|
3735
|
+
"url",
|
|
3736
|
+
"expression",
|
|
3737
|
+
"image-set",
|
|
3738
|
+
"javascript",
|
|
3739
|
+
"vbscript",
|
|
3740
|
+
"behavior",
|
|
3741
|
+
"binding"
|
|
3742
|
+
]);
|
|
3743
|
+
var UNITS = /* @__PURE__ */ new Set([
|
|
3744
|
+
"px",
|
|
3745
|
+
"em",
|
|
3746
|
+
"rem",
|
|
3747
|
+
"vh",
|
|
3748
|
+
"vw",
|
|
3749
|
+
"vmin",
|
|
3750
|
+
"vmax",
|
|
3751
|
+
"svh",
|
|
3752
|
+
"lvh",
|
|
3753
|
+
"dvh",
|
|
3754
|
+
"ch",
|
|
3755
|
+
"ex",
|
|
3756
|
+
"fr",
|
|
3757
|
+
"deg",
|
|
3758
|
+
"rad",
|
|
3759
|
+
"turn",
|
|
3760
|
+
"s",
|
|
3761
|
+
"ms"
|
|
3762
|
+
]);
|
|
3763
|
+
var PSEUDO_CLASSES = /* @__PURE__ */ new Set([
|
|
3764
|
+
"hover",
|
|
3765
|
+
"focus",
|
|
3766
|
+
"focus-visible",
|
|
3767
|
+
"focus-within",
|
|
3768
|
+
"active",
|
|
3769
|
+
"first-child",
|
|
3770
|
+
"last-child",
|
|
3771
|
+
"only-child",
|
|
3772
|
+
"first-of-type",
|
|
3773
|
+
"last-of-type",
|
|
3774
|
+
"empty"
|
|
3775
|
+
]);
|
|
3776
|
+
var NTH_FUNCTIONS = /* @__PURE__ */ new Set([
|
|
3777
|
+
"nth-child",
|
|
3778
|
+
"nth-last-child",
|
|
3779
|
+
"nth-of-type",
|
|
3780
|
+
"nth-last-of-type"
|
|
3781
|
+
]);
|
|
3782
|
+
var ELEMENTS2 = new Set(ALLOWED_ELEMENTS);
|
|
3783
|
+
var MIN_WIDTHS = [768, 1025];
|
|
3784
|
+
var MAX_WIDTHS = [767, 1024];
|
|
3785
|
+
var isAlpha = (c) => c !== void 0 && (c >= "a" && c <= "z" || c >= "A" && c <= "Z");
|
|
3786
|
+
var isDigit2 = (c) => c !== void 0 && c >= "0" && c <= "9";
|
|
3787
|
+
var isWs = (c) => c === " " || c === " " || c === "\n" || c === "\r" || c === "\f";
|
|
3788
|
+
var identStart = (css, i) => {
|
|
3789
|
+
const c = css[i];
|
|
3790
|
+
if (isAlpha(c) || c === "_") return true;
|
|
3791
|
+
if (c === "-") return isAlpha(css[i + 1]) || css[i + 1] === "_" || css[i + 1] === "-";
|
|
3792
|
+
return false;
|
|
3793
|
+
};
|
|
3794
|
+
var startsNumber = (css, i) => {
|
|
3795
|
+
const c = css[i];
|
|
3796
|
+
if (isDigit2(c)) return true;
|
|
3797
|
+
if (c === ".") return isDigit2(css[i + 1]);
|
|
3798
|
+
if (c === "+" || c === "-") return isDigit2(css[i + 1]) || css[i + 1] === "." && isDigit2(css[i + 2]);
|
|
3799
|
+
return false;
|
|
3800
|
+
};
|
|
3801
|
+
function tokenize(css) {
|
|
3802
|
+
const out = [];
|
|
3803
|
+
let i = 0;
|
|
3804
|
+
while (i < css.length) {
|
|
3805
|
+
const c = css[i];
|
|
3806
|
+
const code = c.charCodeAt(0);
|
|
3807
|
+
const pos = i;
|
|
3808
|
+
if (c === "\\") {
|
|
3809
|
+
throw forbidden2("Backslash escapes are not allowed", pos);
|
|
3810
|
+
}
|
|
3811
|
+
if (code > 126 || code < 32 && !isWs(c)) {
|
|
3812
|
+
throw syntax2("Only printable ASCII is allowed outside comments", pos);
|
|
3813
|
+
}
|
|
3814
|
+
if (isWs(c)) {
|
|
3815
|
+
while (isWs(css[i])) i += 1;
|
|
3816
|
+
out.push({ t: "ws", pos });
|
|
3817
|
+
} else if (c === "/" && css[i + 1] === "*") {
|
|
3818
|
+
const end = css.indexOf("*/", i + 2);
|
|
3819
|
+
if (end === -1) throw syntax2("This comment is never closed", pos);
|
|
3820
|
+
i = end + 2;
|
|
3821
|
+
out.push({ t: "ws", pos });
|
|
3822
|
+
} else if (c === '"' || c === "'") {
|
|
3823
|
+
i += 1;
|
|
3824
|
+
let value = "";
|
|
3825
|
+
for (; ; ) {
|
|
3826
|
+
const ch = css[i];
|
|
3827
|
+
if (ch === void 0 || ch === "\n" || ch === "\r" || ch === "\f") {
|
|
3828
|
+
throw syntax2("This string is never closed", pos);
|
|
3829
|
+
}
|
|
3830
|
+
if (ch === c) break;
|
|
3831
|
+
const cc = ch.charCodeAt(0);
|
|
3832
|
+
if (ch === "\\") throw forbidden2("Backslash escapes are not allowed", i);
|
|
3833
|
+
if (cc < 32 || cc > 126 || ch === "<" || ch === ">" || ch === '"') {
|
|
3834
|
+
throw forbidden2('A string can hold printable ASCII except < > and "', i);
|
|
3835
|
+
}
|
|
3836
|
+
value += ch;
|
|
3837
|
+
i += 1;
|
|
3838
|
+
}
|
|
3839
|
+
i += 1;
|
|
3840
|
+
if (value.length > MAX_STRING) throw syntax2("This string is too long", pos);
|
|
3841
|
+
out.push({ t: "string", v: value, pos });
|
|
3842
|
+
} else if (c === "#") {
|
|
3843
|
+
let value = "";
|
|
3844
|
+
i += 1;
|
|
3845
|
+
while (isAlpha(css[i]) || isDigit2(css[i]) || css[i] === "_" || css[i] === "-") {
|
|
3846
|
+
value += css[i];
|
|
3847
|
+
i += 1;
|
|
3848
|
+
}
|
|
3849
|
+
out.push({ t: "hash", v: value, pos });
|
|
3850
|
+
} else if (c === "@") {
|
|
3851
|
+
i += 1;
|
|
3852
|
+
if (!identStart(css, i)) throw syntax2("A stray @", pos);
|
|
3853
|
+
let value = "";
|
|
3854
|
+
while (isAlpha(css[i]) || isDigit2(css[i]) || css[i] === "_" || css[i] === "-") {
|
|
3855
|
+
value += css[i];
|
|
3856
|
+
i += 1;
|
|
3857
|
+
}
|
|
3858
|
+
out.push({ t: "atkw", v: value, pos });
|
|
3859
|
+
} else if (startsNumber(css, i)) {
|
|
3860
|
+
let value = "";
|
|
3861
|
+
if (css[i] === "+" || css[i] === "-") {
|
|
3862
|
+
value += css[i];
|
|
3863
|
+
i += 1;
|
|
3864
|
+
}
|
|
3865
|
+
while (isDigit2(css[i])) {
|
|
3866
|
+
value += css[i];
|
|
3867
|
+
i += 1;
|
|
3868
|
+
}
|
|
3869
|
+
if (css[i] === "." && isDigit2(css[i + 1])) {
|
|
3870
|
+
value += ".";
|
|
3871
|
+
i += 1;
|
|
3872
|
+
while (isDigit2(css[i])) {
|
|
3873
|
+
value += css[i];
|
|
3874
|
+
i += 1;
|
|
3875
|
+
}
|
|
3876
|
+
}
|
|
3877
|
+
if (value.length > 16) throw syntax2("This number is too long", pos);
|
|
3878
|
+
if (css[i] === "%") {
|
|
3879
|
+
i += 1;
|
|
3880
|
+
out.push({ t: "pct", v: value, pos });
|
|
3881
|
+
} else if (isAlpha(css[i])) {
|
|
3882
|
+
let unit = "";
|
|
3883
|
+
while (isAlpha(css[i]) || isDigit2(css[i]) || css[i] === "_" || css[i] === "-") {
|
|
3884
|
+
unit += css[i];
|
|
3885
|
+
i += 1;
|
|
3886
|
+
}
|
|
3887
|
+
out.push({ t: "dim", v: value, unit, pos });
|
|
3888
|
+
} else out.push({ t: "num", v: value, pos });
|
|
3889
|
+
} else if (identStart(css, i)) {
|
|
3890
|
+
let value = "";
|
|
3891
|
+
while (isAlpha(css[i]) || isDigit2(css[i]) || css[i] === "_" || css[i] === "-") {
|
|
3892
|
+
value += css[i];
|
|
3893
|
+
i += 1;
|
|
3894
|
+
}
|
|
3895
|
+
if (css[i] === "(") {
|
|
3896
|
+
const name = value.toLowerCase();
|
|
3897
|
+
if (LOADING_FUNCTIONS.has(name)) {
|
|
3898
|
+
throw forbidden2(`${name}( can load a resource or run code and is not allowed`, pos);
|
|
3899
|
+
}
|
|
3900
|
+
i += 1;
|
|
3901
|
+
out.push({ t: "func", v: value, pos });
|
|
3902
|
+
} else out.push({ t: "ident", v: value, pos });
|
|
3903
|
+
} else {
|
|
3904
|
+
i += 1;
|
|
3905
|
+
if (c === ":") out.push({ t: "colon", pos });
|
|
3906
|
+
else if (c === ";") out.push({ t: "semi", pos });
|
|
3907
|
+
else if (c === ",") out.push({ t: "comma", pos });
|
|
3908
|
+
else if (c === "(" || c === "[" || c === "{") out.push({ t: "open", v: c, pos });
|
|
3909
|
+
else if (c === ")" || c === "]" || c === "}") out.push({ t: "close", v: c, pos });
|
|
3910
|
+
else out.push({ t: "delim", v: c, pos });
|
|
3911
|
+
}
|
|
3912
|
+
}
|
|
3913
|
+
return out;
|
|
3914
|
+
}
|
|
3915
|
+
var PAIRS = { "(": ")", "[": "]", "{": "}" };
|
|
3916
|
+
function buildTree(tokens) {
|
|
3917
|
+
const root = [];
|
|
3918
|
+
const stack = [];
|
|
3919
|
+
let current = root;
|
|
3920
|
+
for (const tok of tokens) {
|
|
3921
|
+
if (tok.t === "open" || tok.t === "func") {
|
|
3922
|
+
if (stack.length >= MAX_NESTING) throw syntax2("Too many nested brackets", tok.pos);
|
|
3923
|
+
const children = [];
|
|
3924
|
+
const node = tok.t === "open" ? { t: "block", v: tok.v, children, pos: tok.pos } : { t: "fn", v: tok.v, children, pos: tok.pos };
|
|
3925
|
+
current.push(node);
|
|
3926
|
+
stack.push({ node, close: tok.t === "open" ? PAIRS[tok.v] : ")", children: current });
|
|
3927
|
+
current = children;
|
|
3928
|
+
} else if (tok.t === "close") {
|
|
3929
|
+
const top = stack.pop();
|
|
3930
|
+
if (top === void 0 || top.close !== tok.v) {
|
|
3931
|
+
throw syntax2(`Unbalanced "${tok.v}"`, tok.pos);
|
|
3932
|
+
}
|
|
3933
|
+
current = top.children;
|
|
3934
|
+
} else current.push(tok);
|
|
3935
|
+
}
|
|
3936
|
+
const open = stack[stack.length - 1];
|
|
3937
|
+
if (open !== void 0) throw syntax2(`Unbalanced: "${open.close === ")" ? "(" : open.close === "}" ? "{" : "["}" is never closed`, open.node.pos);
|
|
3938
|
+
return root;
|
|
3939
|
+
}
|
|
3940
|
+
var isWsNode = (n) => n.t === "ws";
|
|
3941
|
+
var trimWs = (nodes) => {
|
|
3942
|
+
let start = 0;
|
|
3943
|
+
let end = nodes.length;
|
|
3944
|
+
while (start < end && isWsNode(nodes[start])) start += 1;
|
|
3945
|
+
while (end > start && isWsNode(nodes[end - 1])) end -= 1;
|
|
3946
|
+
return nodes.slice(start, end);
|
|
3947
|
+
};
|
|
3948
|
+
function raw(node) {
|
|
3949
|
+
switch (node.t) {
|
|
3950
|
+
case "ident":
|
|
3951
|
+
case "num":
|
|
3952
|
+
return node.v;
|
|
3953
|
+
case "dim":
|
|
3954
|
+
return node.v + node.unit;
|
|
3955
|
+
case "delim":
|
|
3956
|
+
return node.v;
|
|
3957
|
+
default:
|
|
3958
|
+
return "?";
|
|
3959
|
+
}
|
|
3960
|
+
}
|
|
3961
|
+
function parseCompoundList(nodes, pos) {
|
|
3962
|
+
const selectors = [];
|
|
3963
|
+
let part = [];
|
|
3964
|
+
const parts = [];
|
|
3965
|
+
for (const node of nodes) {
|
|
3966
|
+
if (node.t === "comma") {
|
|
3967
|
+
parts.push(part);
|
|
3968
|
+
part = [];
|
|
3969
|
+
} else part.push(node);
|
|
3970
|
+
}
|
|
3971
|
+
parts.push(part);
|
|
3972
|
+
if (parts.length > MAX_SELECTORS) throw syntax2(`At most ${String(MAX_SELECTORS)} selectors per rule`, pos);
|
|
3973
|
+
for (const p of parts) selectors.push(parseSelector(trimWs(p), pos));
|
|
3974
|
+
return selectors;
|
|
3975
|
+
}
|
|
3976
|
+
function parseSelector(nodes, pos) {
|
|
3977
|
+
if (nodes.length === 0) throw syntax2("An empty selector", pos);
|
|
3978
|
+
let out = "";
|
|
3979
|
+
let compounds = 0;
|
|
3980
|
+
let inCompound = false;
|
|
3981
|
+
let expectCompound = true;
|
|
3982
|
+
let pseudos = 0;
|
|
3983
|
+
const pseudo = (at2) => {
|
|
3984
|
+
pseudos += 1;
|
|
3985
|
+
if (pseudos > MAX_PSEUDOS) {
|
|
3986
|
+
throw forbidden2(`At most ${String(MAX_PSEUDOS)} pseudo-classes per compound selector`, at2);
|
|
3987
|
+
}
|
|
3988
|
+
};
|
|
3989
|
+
const begin = (at2) => {
|
|
3990
|
+
if (inCompound) return;
|
|
3991
|
+
if (!expectCompound) out += " ";
|
|
3992
|
+
compounds += 1;
|
|
3993
|
+
if (compounds > MAX_COMPOUNDS) {
|
|
3994
|
+
throw syntax2(`At most ${String(MAX_COMPOUNDS)} parts in a selector`, at2);
|
|
3995
|
+
}
|
|
3996
|
+
inCompound = true;
|
|
3997
|
+
expectCompound = false;
|
|
3998
|
+
pseudos = 0;
|
|
3999
|
+
};
|
|
4000
|
+
for (let i = 0; i < nodes.length; i += 1) {
|
|
4001
|
+
const node = nodes[i];
|
|
4002
|
+
const next = nodes[i + 1];
|
|
4003
|
+
if (node.t === "ws") {
|
|
4004
|
+
inCompound = false;
|
|
4005
|
+
continue;
|
|
4006
|
+
}
|
|
4007
|
+
if (node.t === "delim" && (node.v === ">" || node.v === "+" || node.v === "~")) {
|
|
4008
|
+
if (expectCompound) throw syntax2(`Unexpected "${node.v}" in a selector`, node.pos);
|
|
4009
|
+
out += ` ${node.v} `;
|
|
4010
|
+
expectCompound = true;
|
|
4011
|
+
inCompound = false;
|
|
4012
|
+
continue;
|
|
4013
|
+
}
|
|
4014
|
+
if (node.t === "ident" || node.t === "delim" && node.v === "*") {
|
|
4015
|
+
if (inCompound) throw syntax2("A type selector must start a compound selector", node.pos);
|
|
4016
|
+
const name = node.t === "ident" ? node.v.toLowerCase() : "*";
|
|
4017
|
+
if (node.t === "ident" && !ELEMENTS2.has(name)) {
|
|
4018
|
+
throw forbidden2(`"${node.v}" is not an element a template can use`, node.pos);
|
|
4019
|
+
}
|
|
4020
|
+
begin(node.pos);
|
|
4021
|
+
out += name;
|
|
4022
|
+
continue;
|
|
4023
|
+
}
|
|
4024
|
+
if (node.t === "delim" && node.v === ".") {
|
|
4025
|
+
if (next?.t !== "ident") throw syntax2("A class selector is .name", node.pos);
|
|
4026
|
+
if (!CLASS_RE.test(next.v)) {
|
|
4027
|
+
throw forbidden2(`The class "${next.v}" must be lower case letters, digits and -`, next.pos);
|
|
4028
|
+
}
|
|
4029
|
+
if (isReservedClass(next.v)) {
|
|
4030
|
+
throw forbidden2(`The class "${next.v}" starts with a prefix reserved for the platform`, next.pos);
|
|
4031
|
+
}
|
|
4032
|
+
begin(node.pos);
|
|
4033
|
+
out += `.${next.v}`;
|
|
4034
|
+
i += 1;
|
|
4035
|
+
continue;
|
|
4036
|
+
}
|
|
4037
|
+
if (node.t === "colon") {
|
|
4038
|
+
if (next?.t === "colon") throw forbidden2("Pseudo-elements (::) are not allowed", node.pos);
|
|
4039
|
+
if (next?.t === "ident") {
|
|
4040
|
+
const name = next.v.toLowerCase();
|
|
4041
|
+
if (!PSEUDO_CLASSES.has(name)) throw forbidden2(`:${next.v} is not allowed`, next.pos);
|
|
4042
|
+
begin(node.pos);
|
|
4043
|
+
pseudo(node.pos);
|
|
4044
|
+
out += `:${name}`;
|
|
4045
|
+
i += 1;
|
|
4046
|
+
continue;
|
|
4047
|
+
}
|
|
4048
|
+
if (next?.t === "fn") {
|
|
4049
|
+
const name = next.v.toLowerCase();
|
|
4050
|
+
const arg = trimWs(next.children).map(raw).join("");
|
|
4051
|
+
if (!NTH_FUNCTIONS.has(name) || !/^(?:odd|even|[+-]?[0-9]*n(?:[+-][0-9]+)?|[+-]?[0-9]+)$/i.test(arg)) {
|
|
4052
|
+
throw forbidden2(`:${next.v}(...) is not allowed`, next.pos);
|
|
4053
|
+
}
|
|
4054
|
+
begin(node.pos);
|
|
4055
|
+
pseudo(node.pos);
|
|
4056
|
+
out += `:${name}(${arg.toLowerCase()})`;
|
|
4057
|
+
i += 1;
|
|
4058
|
+
continue;
|
|
4059
|
+
}
|
|
4060
|
+
throw syntax2("A pseudo-class is :name", node.pos);
|
|
4061
|
+
}
|
|
4062
|
+
if (node.t === "hash") throw forbidden2("ID selectors are not allowed", node.pos);
|
|
4063
|
+
if (node.t === "block" && node.v === "[") {
|
|
4064
|
+
throw forbidden2("Attribute selectors are not allowed", node.pos);
|
|
4065
|
+
}
|
|
4066
|
+
throw forbidden2("This is not allowed in a selector", node.pos);
|
|
4067
|
+
}
|
|
4068
|
+
if (expectCompound) {
|
|
4069
|
+
throw syntax2("A selector cannot end with a combinator", nodes[nodes.length - 1]?.pos ?? pos);
|
|
4070
|
+
}
|
|
4071
|
+
return out;
|
|
4072
|
+
}
|
|
4073
|
+
function serializeValue(nodes, property, vars, nested) {
|
|
4074
|
+
let out = "";
|
|
4075
|
+
let space = false;
|
|
4076
|
+
let afterComma = false;
|
|
4077
|
+
const emit = (text) => {
|
|
4078
|
+
if (space && out !== "" && !afterComma) out += " ";
|
|
4079
|
+
out += text;
|
|
4080
|
+
space = false;
|
|
4081
|
+
afterComma = false;
|
|
4082
|
+
};
|
|
4083
|
+
for (const node of trimWs(nodes)) {
|
|
4084
|
+
switch (node.t) {
|
|
4085
|
+
case "ws":
|
|
4086
|
+
space = true;
|
|
4087
|
+
break;
|
|
4088
|
+
case "ident": {
|
|
4089
|
+
const lower = node.v.toLowerCase();
|
|
4090
|
+
if (node.v.startsWith("--")) throw forbidden2("Custom properties are only read through var(--w-<setting>)", node.pos);
|
|
4091
|
+
if (FORBIDDEN_IDENTS.has(lower)) throw forbidden2(`"${node.v}" is not allowed in a value`, node.pos);
|
|
4092
|
+
emit(node.v);
|
|
4093
|
+
break;
|
|
4094
|
+
}
|
|
4095
|
+
case "num":
|
|
4096
|
+
emit(node.v);
|
|
4097
|
+
break;
|
|
4098
|
+
case "pct":
|
|
4099
|
+
emit(`${node.v}%`);
|
|
4100
|
+
break;
|
|
4101
|
+
case "dim": {
|
|
4102
|
+
const unit = node.unit.toLowerCase();
|
|
4103
|
+
if (!UNITS.has(unit)) throw forbidden2(`The unit "${node.unit}" is not allowed`, node.pos);
|
|
4104
|
+
emit(node.v + unit);
|
|
4105
|
+
break;
|
|
4106
|
+
}
|
|
4107
|
+
case "hash":
|
|
4108
|
+
if (!/^(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(node.v)) {
|
|
4109
|
+
throw forbidden2("A # value must be a hex colour", node.pos);
|
|
4110
|
+
}
|
|
4111
|
+
emit(`#${node.v.toLowerCase()}`);
|
|
4112
|
+
break;
|
|
4113
|
+
case "string":
|
|
4114
|
+
if (!STRING_PROPERTIES.has(property)) {
|
|
4115
|
+
throw forbidden2(`${property} does not take a string`, node.pos);
|
|
4116
|
+
}
|
|
4117
|
+
emit(`"${node.v}"`);
|
|
4118
|
+
break;
|
|
4119
|
+
case "comma":
|
|
4120
|
+
if (out === "" || afterComma) throw syntax2("Unexpected ,", node.pos);
|
|
4121
|
+
out += ",";
|
|
4122
|
+
space = false;
|
|
4123
|
+
afterComma = true;
|
|
4124
|
+
break;
|
|
4125
|
+
case "delim":
|
|
4126
|
+
if (node.v === "!") throw forbidden2("!important is not allowed", node.pos);
|
|
4127
|
+
if (node.v !== "/" && node.v !== "+" && node.v !== "-" && node.v !== "*") {
|
|
4128
|
+
throw syntax2(`"${node.v}" is not allowed in a value`, node.pos);
|
|
4129
|
+
}
|
|
4130
|
+
emit(node.v);
|
|
4131
|
+
break;
|
|
4132
|
+
case "colon":
|
|
4133
|
+
throw forbidden2('":" is not allowed in a value', node.pos);
|
|
4134
|
+
case "semi":
|
|
4135
|
+
throw syntax2("Unexpected ;", node.pos);
|
|
4136
|
+
case "atkw":
|
|
4137
|
+
throw forbidden2("@ rules are not allowed in a value", node.pos);
|
|
4138
|
+
case "block":
|
|
4139
|
+
if (node.v !== "(" || !nested) {
|
|
4140
|
+
throw forbidden2(`"${node.v}" blocks are not allowed in a value`, node.pos);
|
|
4141
|
+
}
|
|
4142
|
+
emit(`(${serializeValue(node.children, property, vars, true)})`);
|
|
4143
|
+
break;
|
|
4144
|
+
case "fn": {
|
|
4145
|
+
const name = node.v.toLowerCase();
|
|
4146
|
+
if (!FUNCTIONS.has(name)) throw forbidden2(`The function ${node.v}() is not allowed`, node.pos);
|
|
4147
|
+
if (name === "var") emit(`var(${serializeVar(node, property, vars)})`);
|
|
4148
|
+
else emit(`${name}(${serializeValue(node.children, property, vars, true)})`);
|
|
4149
|
+
break;
|
|
4150
|
+
}
|
|
4151
|
+
}
|
|
4152
|
+
}
|
|
4153
|
+
return out;
|
|
4154
|
+
}
|
|
4155
|
+
function serializeVar(node, property, vars) {
|
|
4156
|
+
const children = trimWs(node.children);
|
|
4157
|
+
const first = children[0];
|
|
4158
|
+
if (first?.t !== "ident" || !VAR_NAME_RE.test(first.v)) {
|
|
4159
|
+
throw forbidden2("var() reads only --w-<setting key> custom properties", node.pos);
|
|
4160
|
+
}
|
|
4161
|
+
vars.add(first.v.slice("--w-".length));
|
|
4162
|
+
const rest = children.slice(1);
|
|
4163
|
+
if (rest.length === 0) return first.v;
|
|
4164
|
+
const comma = trimWs(rest);
|
|
4165
|
+
if (comma[0]?.t !== "comma") throw syntax2("var() takes a name and an optional fallback", node.pos);
|
|
4166
|
+
return `${first.v},${serializeValue(comma.slice(1), property, vars, true)}`;
|
|
4167
|
+
}
|
|
4168
|
+
function parseDeclarations(nodes, vars, issues, css) {
|
|
4169
|
+
const out = [];
|
|
4170
|
+
const decls = [];
|
|
4171
|
+
let current = [];
|
|
4172
|
+
for (const node of nodes) {
|
|
4173
|
+
if (node.t === "semi") {
|
|
4174
|
+
decls.push(current);
|
|
4175
|
+
current = [];
|
|
4176
|
+
} else current.push(node);
|
|
4177
|
+
}
|
|
4178
|
+
decls.push(current);
|
|
4179
|
+
for (const decl of decls) {
|
|
4180
|
+
const body = trimWs(decl);
|
|
4181
|
+
if (body.length === 0) continue;
|
|
4182
|
+
try {
|
|
4183
|
+
const name = body[0];
|
|
4184
|
+
if (name?.t !== "ident") throw syntax2("Expected a property name", body[0]?.pos ?? 0);
|
|
4185
|
+
const rest = trimWs(body.slice(1));
|
|
4186
|
+
if (rest[0]?.t !== "colon") throw syntax2(`Expected ":" after ${name.v}`, name.pos);
|
|
4187
|
+
const property = name.v.toLowerCase();
|
|
4188
|
+
if (name.v.startsWith("--")) {
|
|
4189
|
+
throw forbidden2("Custom properties cannot be declared. Settings arrive as --w-<key>.", name.pos);
|
|
4190
|
+
}
|
|
4191
|
+
if (!PROPERTIES.has(property)) {
|
|
4192
|
+
throw new CssError("CSS_PROPERTY_NOT_ALLOWED", `The property "${name.v}" is not allowed`, name.pos);
|
|
4193
|
+
}
|
|
4194
|
+
const value = serializeValue(rest.slice(1), property, vars, false);
|
|
4195
|
+
if (value === "") throw syntax2(`${name.v} has no value`, name.pos);
|
|
4196
|
+
out.push(`${property}:${value}`);
|
|
4197
|
+
} catch (error) {
|
|
4198
|
+
if (!(error instanceof CssError)) throw error;
|
|
4199
|
+
issues.push(cssIssue(css, error));
|
|
4200
|
+
}
|
|
4201
|
+
}
|
|
4202
|
+
return out;
|
|
4203
|
+
}
|
|
4204
|
+
function parseMedia(prelude, pos) {
|
|
4205
|
+
const nodes = trimWs(prelude).filter((n) => n.t !== "ws");
|
|
4206
|
+
const conditions = /* @__PURE__ */ new Map();
|
|
4207
|
+
if (nodes.length % 2 === 0) throw syntax2('@media takes conditions joined with "and"', pos);
|
|
4208
|
+
for (let i = 0; i < nodes.length; i += 1) {
|
|
4209
|
+
const node = nodes[i];
|
|
4210
|
+
if (i % 2 === 1) {
|
|
4211
|
+
if (node.t !== "ident" || node.v.toLowerCase() !== "and") {
|
|
4212
|
+
throw forbidden2("@media takes (min-width: ...) and (max-width: ...) only", node.pos);
|
|
4213
|
+
}
|
|
4214
|
+
continue;
|
|
4215
|
+
}
|
|
4216
|
+
if (node.t !== "block" || node.v !== "(") {
|
|
4217
|
+
throw forbidden2("@media takes (min-width: ...) and (max-width: ...) only", node.pos);
|
|
4218
|
+
}
|
|
4219
|
+
const inner = trimWs(node.children).filter((n) => n.t !== "ws");
|
|
4220
|
+
const [feature, colon, value] = inner;
|
|
4221
|
+
if (inner.length !== 3 || feature?.t !== "ident" || colon?.t !== "colon" || value?.t !== "dim" || value.unit.toLowerCase() !== "px") {
|
|
4222
|
+
throw forbidden2("@media takes (min-width: Npx) and (max-width: Npx) only", node.pos);
|
|
4223
|
+
}
|
|
4224
|
+
const name = feature.v.toLowerCase();
|
|
4225
|
+
const px = Number(value.v);
|
|
4226
|
+
const allowed = name === "min-width" ? MIN_WIDTHS : name === "max-width" ? MAX_WIDTHS : [];
|
|
4227
|
+
if (!allowed.includes(px) || conditions.has(name)) {
|
|
4228
|
+
throw forbidden2(
|
|
4229
|
+
"Only the breakpoints (min-width: 1025px), (min-width: 768px), (max-width: 1024px) and (max-width: 767px) are allowed",
|
|
4230
|
+
node.pos
|
|
4231
|
+
);
|
|
4232
|
+
}
|
|
4233
|
+
conditions.set(name, px);
|
|
4234
|
+
}
|
|
4235
|
+
const min = conditions.get("min-width");
|
|
4236
|
+
const max = conditions.get("max-width");
|
|
4237
|
+
if (min === void 0 && max === void 0) throw syntax2("@media needs a condition", pos);
|
|
4238
|
+
if (min !== void 0 && max !== void 0 && !(min === 768 && max === 1024)) {
|
|
4239
|
+
throw forbidden2("Combine breakpoints only as (min-width: 768px) and (max-width: 1024px)", pos);
|
|
4240
|
+
}
|
|
4241
|
+
const parts = [];
|
|
4242
|
+
if (min !== void 0) parts.push(`(min-width:${String(min)}px)`);
|
|
4243
|
+
if (max !== void 0) parts.push(`(max-width:${String(max)}px)`);
|
|
4244
|
+
return parts.join(" and ");
|
|
4245
|
+
}
|
|
4246
|
+
function cssIssue(css, error) {
|
|
4247
|
+
const { line, col } = lineCol(css, error.pos);
|
|
4248
|
+
return makeIssue(`css:${String(line)}:${String(col)}`, error.code, error.message);
|
|
4249
|
+
}
|
|
4250
|
+
function parseRules(nodes, media, vars, issues, css, rules) {
|
|
4251
|
+
let i = 0;
|
|
4252
|
+
while (i < nodes.length) {
|
|
4253
|
+
const node = nodes[i];
|
|
4254
|
+
if (node.t === "ws") {
|
|
4255
|
+
i += 1;
|
|
4256
|
+
continue;
|
|
4257
|
+
}
|
|
4258
|
+
if (node.t === "atkw" && node.v.toLowerCase() !== "media") {
|
|
4259
|
+
throw forbidden2(`@${node.v} is not allowed. Only @media with the three breakpoints is.`, node.pos);
|
|
4260
|
+
}
|
|
4261
|
+
const start = i;
|
|
4262
|
+
while (i < nodes.length && !(nodes[i].t === "block" && nodes[i].v === "{")) {
|
|
4263
|
+
if (nodes[i].t === "semi") throw syntax2("Unexpected ; outside a rule", nodes[i].pos);
|
|
4264
|
+
i += 1;
|
|
4265
|
+
}
|
|
4266
|
+
const block = nodes[i];
|
|
4267
|
+
if (block === void 0) throw syntax2("A rule needs a { } block", node.pos);
|
|
4268
|
+
const prelude = nodes.slice(start, i);
|
|
4269
|
+
i += 1;
|
|
4270
|
+
if (node.t === "atkw") {
|
|
4271
|
+
if (media !== null) throw forbidden2("@media cannot be nested", node.pos);
|
|
4272
|
+
const condition = parseMedia(prelude.slice(1), node.pos);
|
|
4273
|
+
parseRules(block.children, condition, vars, issues, css, rules);
|
|
4274
|
+
continue;
|
|
4275
|
+
}
|
|
4276
|
+
try {
|
|
4277
|
+
const selectors = parseCompoundList(prelude, node.pos);
|
|
4278
|
+
const declarations = parseDeclarations(block.children, vars, issues, css);
|
|
4279
|
+
if (declarations.length > 0) rules.push({ media, selectors, declarations });
|
|
4280
|
+
} catch (error) {
|
|
4281
|
+
if (!(error instanceof CssError)) throw error;
|
|
4282
|
+
issues.push(cssIssue(css, error));
|
|
4283
|
+
}
|
|
4284
|
+
}
|
|
4285
|
+
}
|
|
4286
|
+
function serialize(rules, scope) {
|
|
4287
|
+
let out = "";
|
|
4288
|
+
let open = null;
|
|
4289
|
+
for (const rule of rules) {
|
|
4290
|
+
if (rule.media !== open) {
|
|
4291
|
+
if (open !== null) out += "}";
|
|
4292
|
+
if (rule.media !== null) out += `@media ${rule.media}{`;
|
|
4293
|
+
open = rule.media;
|
|
4294
|
+
}
|
|
4295
|
+
const selector = rule.selectors.map((s) => scope === "" ? s : `${scope} ${s}`).join(",");
|
|
4296
|
+
out += `${selector}{${rule.declarations.join(";")}}`;
|
|
4297
|
+
}
|
|
4298
|
+
if (open !== null) out += "}";
|
|
4299
|
+
return out;
|
|
4300
|
+
}
|
|
4301
|
+
function sanitizeWidgetCss(css, type) {
|
|
4302
|
+
if (typeof css !== "string" || !WIDGET_TYPE.test(type)) {
|
|
4303
|
+
return {
|
|
4304
|
+
ok: false,
|
|
4305
|
+
issues: [makeIssue("css", "INVALID_VALUE", "The css must be text and the type custom.<slug>")]
|
|
4306
|
+
};
|
|
4307
|
+
}
|
|
4308
|
+
const bytes = utf8Length(css);
|
|
4309
|
+
if (bytes > LIMITS.widgetCssBytes) {
|
|
4310
|
+
return {
|
|
4311
|
+
ok: false,
|
|
4312
|
+
issues: [
|
|
4313
|
+
makeIssue(
|
|
4314
|
+
"css",
|
|
4315
|
+
"LIMIT_EXCEEDED",
|
|
4316
|
+
`CSS is ${String(bytes)} bytes, over the limit of ${String(LIMITS.widgetCssBytes)}`
|
|
4317
|
+
)
|
|
4318
|
+
]
|
|
4319
|
+
};
|
|
4320
|
+
}
|
|
4321
|
+
const issues = [];
|
|
4322
|
+
const vars = /* @__PURE__ */ new Set();
|
|
4323
|
+
const rules = [];
|
|
4324
|
+
try {
|
|
4325
|
+
parseRules(buildTree(tokenize(css)), null, vars, issues, css, rules);
|
|
4326
|
+
} catch (error) {
|
|
4327
|
+
if (!(error instanceof CssError)) throw error;
|
|
4328
|
+
issues.push(cssIssue(css, error));
|
|
4329
|
+
}
|
|
4330
|
+
if (issues.length > 0) return { ok: false, issues: issues.slice(0, 50) };
|
|
4331
|
+
return {
|
|
4332
|
+
ok: true,
|
|
4333
|
+
css: serialize(rules, `[data-b-w="${type}"]`),
|
|
4334
|
+
source: serialize(rules, ""),
|
|
4335
|
+
vars: [...vars].sort()
|
|
4336
|
+
};
|
|
4337
|
+
}
|
|
4338
|
+
|
|
4339
|
+
// src/custom-widget.ts
|
|
4340
|
+
import { z as z6 } from "zod";
|
|
4341
|
+
var SETTING_KEY_RE = /^[a-z][A-Za-z0-9]{0,39}$/;
|
|
4342
|
+
var settingKey = z6.string().regex(SETTING_KEY_RE);
|
|
4343
|
+
var inputName = z6.string().regex(/^[a-z][A-Za-z0-9]{0,39}$/);
|
|
4344
|
+
var dataInputShape = {
|
|
4345
|
+
accepts: z6.array(z6.enum(DATA_RESULT_TYPES)).min(1).max(DATA_RESULT_TYPES.length),
|
|
4346
|
+
required: z6.boolean(),
|
|
4347
|
+
label: z6.string().min(1).max(100)
|
|
4348
|
+
};
|
|
4349
|
+
var common = {
|
|
4350
|
+
type: z6.string().regex(/^custom\.[a-z][a-z0-9-]{0,63}$/),
|
|
4351
|
+
v: z6.number().int().min(1).max(9999),
|
|
4352
|
+
title: z6.string().min(1).max(100),
|
|
4353
|
+
description: z6.string().min(1).max(500),
|
|
4354
|
+
icon: z6.string().min(1).max(40),
|
|
4355
|
+
group: z6.literal("custom"),
|
|
4356
|
+
// The common props (hidden, anchor, spacing) are added on normalisation and do not count.
|
|
4357
|
+
settings: z6.array(settingFieldSchema).max(LIMITS.widgetSettings + COMMON_SETTING_KEYS.length),
|
|
4358
|
+
renamed: safeRecord(settingKey, settingKey).optional(),
|
|
4359
|
+
removed: z6.array(settingKey).max(LIMITS.widgetSettings).optional()
|
|
4360
|
+
};
|
|
4361
|
+
function limitInputs(data, ctx) {
|
|
4362
|
+
if (data !== void 0 && Object.keys(data).length > LIMITS.customWidgetDataInputs) {
|
|
4363
|
+
customIssue(
|
|
4364
|
+
ctx,
|
|
4365
|
+
"LIMIT_EXCEEDED",
|
|
4366
|
+
`A custom widget has at most ${String(LIMITS.customWidgetDataInputs)} data inputs`,
|
|
4367
|
+
["data"]
|
|
4368
|
+
);
|
|
4369
|
+
}
|
|
4370
|
+
}
|
|
4371
|
+
var templateSchema = z6.object({
|
|
4372
|
+
kind: z6.literal("template"),
|
|
4373
|
+
...common,
|
|
4374
|
+
data: safeRecord(z6.object(dataInputShape).strict(), inputName).optional(),
|
|
4375
|
+
template: z6.string(),
|
|
4376
|
+
css: z6.string().optional()
|
|
4377
|
+
}).strict().superRefine((def, ctx) => limitInputs(def.data, ctx));
|
|
4378
|
+
var targetNode = nodeIdSchema;
|
|
4379
|
+
var compositeSchema = z6.object({
|
|
4380
|
+
kind: z6.literal("composite"),
|
|
4381
|
+
...common,
|
|
4382
|
+
body: z6.object({
|
|
4383
|
+
columns: z6.array(z6.unknown()).optional(),
|
|
4384
|
+
stack: z6.array(z6.unknown()).optional()
|
|
4385
|
+
}).strict(),
|
|
4386
|
+
bindings: z6.array(
|
|
4387
|
+
z6.object({
|
|
4388
|
+
setting: settingKey,
|
|
4389
|
+
targets: z6.array(z6.object({ node: targetNode, prop: settingKey }).strict()).min(1).max(20)
|
|
4390
|
+
}).strict()
|
|
4391
|
+
).max(LIMITS.widgetSettings),
|
|
4392
|
+
data: safeRecord(
|
|
4393
|
+
z6.object({
|
|
4394
|
+
...dataInputShape,
|
|
4395
|
+
targets: z6.array(z6.object({ node: targetNode, input: inputName }).strict()).min(1).max(20)
|
|
4396
|
+
}).strict(),
|
|
4397
|
+
inputName
|
|
4398
|
+
).optional()
|
|
4399
|
+
}).strict().superRefine((def, ctx) => {
|
|
4400
|
+
limitInputs(def.data, ctx);
|
|
4401
|
+
const kinds = [def.body.columns, def.body.stack].filter((b) => b !== void 0).length;
|
|
4402
|
+
if (kinds !== 1) {
|
|
4403
|
+
customIssue(ctx, "INVALID_VALUE", "A composite body has exactly one of columns or stack", ["body"]);
|
|
4404
|
+
}
|
|
4405
|
+
});
|
|
4406
|
+
var MAX_DEPTH = 24;
|
|
4407
|
+
var MAX_VALUES = 1e5;
|
|
4408
|
+
function pathOf(frame) {
|
|
4409
|
+
const out = [];
|
|
4410
|
+
for (let f = frame; f !== null && f.parent !== null; f = f.parent) out.unshift(f.key);
|
|
4411
|
+
return out;
|
|
4412
|
+
}
|
|
4413
|
+
function scan(input) {
|
|
4414
|
+
const issues = [];
|
|
4415
|
+
const stack = [{ value: input, key: "", parent: null, depth: 0 }];
|
|
4416
|
+
let seen = 0;
|
|
4417
|
+
while (stack.length > 0 && issues.length < 50) {
|
|
4418
|
+
const frame = stack.pop();
|
|
4419
|
+
const { value } = frame;
|
|
4420
|
+
seen += 1;
|
|
4421
|
+
if (seen > MAX_VALUES) {
|
|
4422
|
+
issues.push(makeIssue("", "WIDGET_TOO_LARGE", "The definition has far too many values"));
|
|
4423
|
+
break;
|
|
4424
|
+
}
|
|
4425
|
+
const at2 = () => pathOf(frame);
|
|
4426
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") continue;
|
|
4427
|
+
if (value === void 0) {
|
|
4428
|
+
issues.push(makeIssue(at2(), "INVALID_SHAPE", "Only JSON values are allowed"));
|
|
4429
|
+
continue;
|
|
4430
|
+
}
|
|
4431
|
+
if (typeof value === "number") {
|
|
4432
|
+
if (!Number.isFinite(value)) issues.push(makeIssue(at2(), "INVALID_SHAPE", "Numbers must be finite"));
|
|
4433
|
+
continue;
|
|
4434
|
+
}
|
|
4435
|
+
if (typeof value !== "object") {
|
|
4436
|
+
issues.push(makeIssue(at2(), "INVALID_SHAPE", "Only JSON values are allowed"));
|
|
4437
|
+
continue;
|
|
4438
|
+
}
|
|
4439
|
+
if (frame.depth >= MAX_DEPTH) {
|
|
4440
|
+
issues.push(makeIssue(at2(), "LIMIT_EXCEEDED", `Nested more than ${String(MAX_DEPTH)} levels`));
|
|
4441
|
+
continue;
|
|
4442
|
+
}
|
|
4443
|
+
if (Array.isArray(value)) {
|
|
4444
|
+
value.forEach((item, i) => stack.push({ value: item, key: i, parent: frame, depth: frame.depth + 1 }));
|
|
4445
|
+
continue;
|
|
4446
|
+
}
|
|
4447
|
+
const proto = Object.getPrototypeOf(value);
|
|
4448
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
4449
|
+
issues.push(makeIssue(at2(), "INVALID_SHAPE", "Expected a plain JSON object"));
|
|
4450
|
+
continue;
|
|
4451
|
+
}
|
|
4452
|
+
for (const key of Object.getOwnPropertyNames(value)) {
|
|
4453
|
+
if (FORBIDDEN_KEYS.has(key)) {
|
|
4454
|
+
issues.push(makeIssue([...at2(), key], "FORBIDDEN_KEY", `The key "${key}" is not allowed`));
|
|
4455
|
+
continue;
|
|
4456
|
+
}
|
|
4457
|
+
const item = Object.getOwnPropertyDescriptor(value, key)?.value;
|
|
4458
|
+
if (item === void 0) continue;
|
|
4459
|
+
stack.push({ value: item, key, parent: frame, depth: frame.depth + 1 });
|
|
4460
|
+
}
|
|
4461
|
+
}
|
|
4462
|
+
return issues;
|
|
4463
|
+
}
|
|
4464
|
+
var Collector = class {
|
|
4465
|
+
constructor() {
|
|
4466
|
+
this.issues = [];
|
|
4467
|
+
}
|
|
4468
|
+
add(path, code, message) {
|
|
4469
|
+
this.issues.push(makeIssue(path, code, message));
|
|
4470
|
+
}
|
|
4471
|
+
};
|
|
4472
|
+
var COMMON_BY_KEY = new Map(COMMON_WIDGET_SETTINGS.map((f) => [f.key, f]));
|
|
4473
|
+
function sameField(a, b) {
|
|
4474
|
+
const entries = (f) => Object.entries(f).filter(([, v]) => v !== void 0);
|
|
4475
|
+
const left = entries(a);
|
|
4476
|
+
const right = new Map(entries(b));
|
|
4477
|
+
return left.length === right.size && left.every(([k, v]) => right.has(k) && JSON.stringify(v) === JSON.stringify(right.get(k)));
|
|
4478
|
+
}
|
|
4479
|
+
function withCommonSettings(settings, out) {
|
|
4480
|
+
let own = 0;
|
|
4481
|
+
settings.forEach((field2, i) => {
|
|
4482
|
+
const common2 = COMMON_BY_KEY.get(field2.key);
|
|
4483
|
+
if (common2 === void 0) own += 1;
|
|
4484
|
+
else if (!sameField(field2, common2)) {
|
|
4485
|
+
out.add(["settings", i, "key"], "DUPLICATE_KEY", `"${field2.key}" is a common prop and cannot be redefined`);
|
|
4486
|
+
}
|
|
4487
|
+
});
|
|
4488
|
+
if (own > LIMITS.widgetSettings) {
|
|
4489
|
+
out.add("settings", "LIMIT_EXCEEDED", `A custom widget has at most ${String(LIMITS.widgetSettings)} settings, not ${String(own)}`);
|
|
4490
|
+
}
|
|
4491
|
+
const present = new Set(settings.map((f) => f.key));
|
|
4492
|
+
return [...settings, ...COMMON_WIDGET_SETTINGS.filter((f) => !present.has(f.key))];
|
|
4493
|
+
}
|
|
4494
|
+
function checkText(def, out) {
|
|
4495
|
+
for (const key of ["title", "description"]) {
|
|
4496
|
+
if (BIDI_CONTROL_RE.test(def[key])) {
|
|
4497
|
+
out.add(key, "INVALID_VALUE", `The ${key} cannot contain bidirectional override characters`);
|
|
4498
|
+
}
|
|
4499
|
+
}
|
|
4500
|
+
}
|
|
4501
|
+
function checkSettings(settings, out) {
|
|
4502
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4503
|
+
settings.forEach((field2, i) => {
|
|
4504
|
+
if (seen.has(field2.key)) {
|
|
4505
|
+
out.add(["settings", i, "key"], "DUPLICATE_KEY", `The setting key "${field2.key}" is used twice`);
|
|
4506
|
+
}
|
|
4507
|
+
seen.add(field2.key);
|
|
4508
|
+
if (field2.control === "select" && (field2.options === void 0 || field2.options.length === 0)) {
|
|
4509
|
+
out.add(["settings", i, "options"], "REQUIRED", "A select setting needs options");
|
|
4510
|
+
}
|
|
4511
|
+
if (BIDI_CONTROL_RE.test(JSON.stringify(field2))) {
|
|
4512
|
+
out.add(["settings", i], "INVALID_VALUE", "A setting cannot contain bidirectional override characters");
|
|
4513
|
+
}
|
|
4514
|
+
const problem = validateSettingValue(field2, field2.default);
|
|
4515
|
+
if (problem !== null) out.add(["settings", i, "default"], "INVALID_VALUE", `The default is invalid: ${problem}`);
|
|
4516
|
+
});
|
|
4517
|
+
}
|
|
4518
|
+
function checkVersion(def, registry, out) {
|
|
4519
|
+
const renamed = def.renamed ?? {};
|
|
4520
|
+
const removed = def.removed ?? [];
|
|
4521
|
+
const renameEntries = Object.entries(renamed);
|
|
4522
|
+
if (def.v === 1) {
|
|
4523
|
+
if (renameEntries.length > 0 || removed.length > 0) {
|
|
4524
|
+
out.add("renamed", "VERSION_RULE", "Version 1 has nothing to rename or remove");
|
|
4525
|
+
}
|
|
4526
|
+
return;
|
|
4527
|
+
}
|
|
4528
|
+
const previous = registry.widget(def.type, def.v - 1);
|
|
4529
|
+
if (previous === void 0) {
|
|
4530
|
+
out.add("v", "VERSION_RULE", `Version ${String(def.v - 1)} of ${def.type} is not registered`);
|
|
4531
|
+
return;
|
|
4532
|
+
}
|
|
4533
|
+
if (previous.kind !== void 0 && previous.kind !== def.kind) {
|
|
4534
|
+
out.add("kind", "VERSION_RULE", `A new version stays a ${previous.kind} widget`);
|
|
4535
|
+
}
|
|
4536
|
+
const before = new Map(previous.settings.map((f) => [f.key, f]));
|
|
4537
|
+
const after = new Map(def.settings.map((f) => [f.key, f]));
|
|
4538
|
+
const renamedTo = /* @__PURE__ */ new Set();
|
|
4539
|
+
for (const [from, to] of renameEntries) {
|
|
4540
|
+
const old = before.get(from);
|
|
4541
|
+
const next = after.get(to);
|
|
4542
|
+
if (old === void 0) out.add(["renamed", from], "VERSION_RULE", `"${from}" is not a setting of version ${String(previous.v)}`);
|
|
4543
|
+
else if (next === void 0) out.add(["renamed", from], "VERSION_RULE", `"${to}" is not a setting of this version`);
|
|
4544
|
+
else if (after.has(from) || before.has(to)) {
|
|
4545
|
+
out.add(["renamed", from], "VERSION_RULE", `Renaming "${from}" to "${to}" collides with another setting`);
|
|
4546
|
+
} else if (old.control !== next.control) {
|
|
4547
|
+
out.add(["renamed", from], "VERSION_RULE", `"${from}" and "${to}" must use the same control`);
|
|
4548
|
+
}
|
|
4549
|
+
if (renamedTo.has(to)) out.add(["renamed", from], "VERSION_RULE", `"${to}" is the target of two renames`);
|
|
4550
|
+
renamedTo.add(to);
|
|
4551
|
+
}
|
|
4552
|
+
removed.forEach((key, i) => {
|
|
4553
|
+
if (!before.has(key)) out.add(["removed", i], "VERSION_RULE", `"${key}" is not a setting of version ${String(previous.v)}`);
|
|
4554
|
+
else if (after.has(key)) out.add(["removed", i], "VERSION_RULE", `"${key}" is removed but still declared`);
|
|
4555
|
+
});
|
|
4556
|
+
for (const key of before.keys()) {
|
|
4557
|
+
if (!after.has(key) && !removed.includes(key) && !renameEntries.some(([from]) => from === key)) {
|
|
4558
|
+
out.add("settings", "VERSION_RULE", `The setting "${key}" is gone. List it in removed, or rename it with renamed.`);
|
|
4559
|
+
}
|
|
4560
|
+
}
|
|
4561
|
+
for (const [key, field2] of after) {
|
|
4562
|
+
const old = before.get(key);
|
|
4563
|
+
if (old !== void 0 && old.control !== field2.control) {
|
|
4564
|
+
out.add("settings", "VERSION_RULE", `The setting "${key}" cannot change its control. Add a new key and remove the old one.`);
|
|
4565
|
+
}
|
|
4566
|
+
}
|
|
4567
|
+
}
|
|
4568
|
+
function controlMismatch(outer, inner) {
|
|
4569
|
+
if (outer.control !== inner.control) {
|
|
4570
|
+
return `"${outer.key}" is a ${outer.control} setting but ${inner.key} takes ${inner.control}`;
|
|
4571
|
+
}
|
|
4572
|
+
if (outer.translatable === true !== (inner.translatable === true)) {
|
|
4573
|
+
return `"${outer.key}" and ${inner.key} must both be translatable, or neither`;
|
|
4574
|
+
}
|
|
4575
|
+
if (outer.control === "select") {
|
|
4576
|
+
const allowed = new Set((inner.options ?? []).map((o) => o.value));
|
|
4577
|
+
const missing = (outer.options ?? []).find((o) => !allowed.has(o.value));
|
|
4578
|
+
if (missing !== void 0) {
|
|
4579
|
+
return `The option "${missing.value}" of "${outer.key}" is not an option of ${inner.key}`;
|
|
4580
|
+
}
|
|
4581
|
+
}
|
|
4582
|
+
return null;
|
|
4583
|
+
}
|
|
4584
|
+
var WRAP = { section: "zzwrapsection01", column: "zzwrapcolumn001", inner: "zzwrapinner0001" };
|
|
4585
|
+
var COLUMNS_PREFIX = "sections[0].columns[0].children[0].columns";
|
|
4586
|
+
var STACK_PREFIX = "sections[0].columns[0].children";
|
|
4587
|
+
function checkBody(def, out) {
|
|
4588
|
+
const useColumns = def.body.columns !== void 0;
|
|
4589
|
+
const children = useColumns ? [{ id: WRAP.inner, type: "inner-section", props: {}, columns: def.body.columns }] : def.body.stack ?? [];
|
|
4590
|
+
if (!useColumns) {
|
|
4591
|
+
(def.body.stack ?? []).forEach((node, i) => {
|
|
4592
|
+
if (node?.type === "inner-section") {
|
|
4593
|
+
out.add(["body", "stack", i, "type"], "INVALID_WIDGET_TYPE", "A stack holds widgets, not sections");
|
|
4594
|
+
}
|
|
4595
|
+
});
|
|
4596
|
+
}
|
|
4597
|
+
const wrapped = pageDocumentSchema.safeParse({
|
|
4598
|
+
schemaVersion: 1,
|
|
4599
|
+
sections: [
|
|
4600
|
+
{
|
|
4601
|
+
id: WRAP.section,
|
|
4602
|
+
type: "section",
|
|
4603
|
+
props: {},
|
|
4604
|
+
columns: [{ id: WRAP.column, type: "column", props: { width: 100 }, children }]
|
|
4605
|
+
}
|
|
4606
|
+
]
|
|
4607
|
+
});
|
|
4608
|
+
if (!wrapped.success) {
|
|
4609
|
+
const prefix = useColumns ? COLUMNS_PREFIX : STACK_PREFIX;
|
|
4610
|
+
const to = useColumns ? "body.columns" : "body.stack";
|
|
4611
|
+
for (const issue2 of zodIssues(wrapped.error)) {
|
|
4612
|
+
out.add(
|
|
4613
|
+
issue2.path.startsWith(prefix) ? `${to}${issue2.path.slice(prefix.length)}` : "body",
|
|
4614
|
+
issue2.code,
|
|
4615
|
+
issue2.message
|
|
4616
|
+
);
|
|
4617
|
+
}
|
|
4618
|
+
return null;
|
|
4619
|
+
}
|
|
4620
|
+
const column = wrapped.data.sections[0]?.columns[0];
|
|
4621
|
+
const first = column?.children[0];
|
|
4622
|
+
if (useColumns) {
|
|
4623
|
+
return first?.type === "inner-section" ? { columns: first.columns } : null;
|
|
4624
|
+
}
|
|
4625
|
+
return { stack: (column?.children ?? []).filter((c) => c.type !== "inner-section") };
|
|
4626
|
+
}
|
|
4627
|
+
function innerNodes(body) {
|
|
4628
|
+
const out = [];
|
|
4629
|
+
body.columns?.forEach(
|
|
4630
|
+
(column, i) => column.children.forEach(
|
|
4631
|
+
(node, j) => out.push({ node, path: ["body", "columns", i, "children", j] })
|
|
4632
|
+
)
|
|
4633
|
+
);
|
|
4634
|
+
body.stack?.forEach((node, i) => out.push({ node, path: ["body", "stack", i] }));
|
|
4635
|
+
return out;
|
|
4636
|
+
}
|
|
4637
|
+
function checkComposite(def, registry, out) {
|
|
4638
|
+
const body = checkBody(def, out);
|
|
4639
|
+
if (body === null) return null;
|
|
4640
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
4641
|
+
for (const ref of innerNodes(body)) {
|
|
4642
|
+
const { node, path } = ref;
|
|
4643
|
+
if (node.data !== void 0) {
|
|
4644
|
+
out.add([...path, "data"], "INVALID_VALUE", "Inner nodes get data through the widget's data inputs, not their own");
|
|
4645
|
+
}
|
|
4646
|
+
let inner;
|
|
4647
|
+
if (node.type === def.type) {
|
|
4648
|
+
out.add([...path, "type"], "NO_RECURSION", "A composite cannot contain itself");
|
|
4649
|
+
} else {
|
|
4650
|
+
inner = registry.widget(node.type, node.v);
|
|
4651
|
+
if (inner === void 0) {
|
|
4652
|
+
out.add([...path, "type"], "INVALID_WIDGET_TYPE", `${node.type}@${String(node.v)} is not an available widget`);
|
|
4653
|
+
} else if (node.type.startsWith("custom.") && inner.kind !== "template") {
|
|
4654
|
+
out.add(
|
|
4655
|
+
[...path, "type"],
|
|
4656
|
+
"NO_RECURSION",
|
|
4657
|
+
"A composite can contain basic, pack and template widgets, but not another composite"
|
|
4658
|
+
);
|
|
4659
|
+
} else {
|
|
4660
|
+
for (const problem of validateWidgetProps(inner, node.props)) {
|
|
4661
|
+
out.add([...path, "props", problem.path], "INVALID_VALUE", problem.message);
|
|
4662
|
+
}
|
|
4663
|
+
}
|
|
4664
|
+
}
|
|
4665
|
+
nodes.set(node.id, { ref, def: inner });
|
|
4666
|
+
}
|
|
4667
|
+
const settings = new Map(def.settings.map((f) => [f.key, f]));
|
|
4668
|
+
const bound = /* @__PURE__ */ new Set();
|
|
4669
|
+
def.bindings.forEach((binding, i) => {
|
|
4670
|
+
const field2 = settings.get(binding.setting);
|
|
4671
|
+
if (field2 === void 0) {
|
|
4672
|
+
out.add(["bindings", i, "setting"], "BINDING_TARGET_MISSING", `"${binding.setting}" is not one of this widget's settings`);
|
|
4673
|
+
}
|
|
4674
|
+
binding.targets.forEach((target2, j) => {
|
|
4675
|
+
const at2 = ["bindings", i, "targets", j];
|
|
4676
|
+
const entry = nodes.get(target2.node);
|
|
4677
|
+
if (entry === void 0) {
|
|
4678
|
+
out.add([...at2, "node"], "BINDING_TARGET_MISSING", `No node with id "${target2.node}" in the body`);
|
|
4679
|
+
return;
|
|
4680
|
+
}
|
|
4681
|
+
const key = `${target2.node}.${target2.prop}`;
|
|
4682
|
+
if (bound.has(key)) out.add(at2, "DUPLICATE_KEY", `${key} is bound by two settings`);
|
|
4683
|
+
bound.add(key);
|
|
4684
|
+
if (entry.def === void 0) return;
|
|
4685
|
+
const innerField = entry.def.settings.find((f) => f.key === target2.prop);
|
|
4686
|
+
if (innerField === void 0) {
|
|
4687
|
+
out.add([...at2, "prop"], "BINDING_TARGET_MISSING", `${entry.def.type} has no setting "${target2.prop}"`);
|
|
4688
|
+
} else if (field2 !== void 0) {
|
|
4689
|
+
const problem = controlMismatch(field2, innerField);
|
|
4690
|
+
if (problem !== null) out.add([...at2, "prop"], "BINDING_TYPE_MISMATCH", problem);
|
|
4691
|
+
}
|
|
4692
|
+
});
|
|
4693
|
+
});
|
|
4694
|
+
const claimed = /* @__PURE__ */ new Set();
|
|
4695
|
+
for (const [name, input] of Object.entries(def.data ?? {})) {
|
|
4696
|
+
input.targets.forEach((target2, j) => {
|
|
4697
|
+
const at2 = ["data", name, "targets", j];
|
|
4698
|
+
const entry = nodes.get(target2.node);
|
|
4699
|
+
if (entry === void 0) {
|
|
4700
|
+
out.add([...at2, "node"], "BINDING_TARGET_MISSING", `No node with id "${target2.node}" in the body`);
|
|
4701
|
+
return;
|
|
4702
|
+
}
|
|
4703
|
+
const key = `${target2.node}.${target2.input}`;
|
|
4704
|
+
if (claimed.has(key)) out.add(at2, "DUPLICATE_KEY", `${key} is fed by two data inputs`);
|
|
4705
|
+
claimed.add(key);
|
|
4706
|
+
if (entry.def === void 0) return;
|
|
4707
|
+
const innerInput = Object.entries(entry.def.data ?? {}).find(([n]) => n === target2.input)?.[1];
|
|
4708
|
+
if (innerInput === void 0) {
|
|
4709
|
+
out.add([...at2, "input"], "BINDING_TARGET_MISSING", `${entry.def.type} has no data input "${target2.input}"`);
|
|
4710
|
+
} else if (!input.accepts.every((a) => innerInput.accepts.includes(a))) {
|
|
4711
|
+
out.add(
|
|
4712
|
+
[...at2, "input"],
|
|
4713
|
+
"BINDING_TYPE_MISMATCH",
|
|
4714
|
+
`"${name}" accepts ${input.accepts.join(", ")} but ${target2.input} takes ${innerInput.accepts.join(", ")}`
|
|
4715
|
+
);
|
|
4716
|
+
}
|
|
4717
|
+
});
|
|
4718
|
+
}
|
|
4719
|
+
const normalized = {
|
|
4720
|
+
...def,
|
|
4721
|
+
body
|
|
4722
|
+
};
|
|
4723
|
+
if (body.columns !== void 0) normalized.placement = { topLevelOnly: true };
|
|
4724
|
+
return normalized;
|
|
4725
|
+
}
|
|
4726
|
+
function checkTemplate(def, registry, out) {
|
|
4727
|
+
const normalized = { ...def };
|
|
4728
|
+
if (def.css !== void 0) {
|
|
4729
|
+
const css = sanitizeWidgetCss(def.css, def.type);
|
|
4730
|
+
if (!css.ok) out.issues.push(...css.issues);
|
|
4731
|
+
else {
|
|
4732
|
+
const byKey = new Map(def.settings.map((f) => [f.key, f]));
|
|
4733
|
+
for (const key of css.vars) {
|
|
4734
|
+
const field2 = byKey.get(key);
|
|
4735
|
+
if (field2 === void 0) out.add("css", "UNKNOWN_REFERENCE", `var(--w-${key}) is not a setting of this widget`);
|
|
4736
|
+
else if (field2.output !== "css") {
|
|
4737
|
+
out.add("css", "FIELD_NOT_ALLOWED", `var(--w-${key}) reads a markup setting. Only css settings reach the CSS.`);
|
|
4738
|
+
}
|
|
4739
|
+
}
|
|
4740
|
+
normalized.css = css.source;
|
|
4741
|
+
}
|
|
4742
|
+
}
|
|
4743
|
+
const parsed = parseTemplate(def.template);
|
|
4744
|
+
if (!parsed.ok) {
|
|
4745
|
+
out.issues.push(...parsed.issues);
|
|
4746
|
+
return null;
|
|
4747
|
+
}
|
|
4748
|
+
out.issues.push(
|
|
4749
|
+
...validateTemplate(parsed.ast, {
|
|
4750
|
+
settings: def.settings,
|
|
4751
|
+
data: def.data ?? {},
|
|
4752
|
+
sources: registry.sources()
|
|
4753
|
+
})
|
|
4754
|
+
);
|
|
4755
|
+
return { normalized, ast: parsed.ast };
|
|
4756
|
+
}
|
|
4757
|
+
var plain2 = (value) => JSON.parse(JSON.stringify(value));
|
|
4758
|
+
function validateCustomWidget(def, registry) {
|
|
4759
|
+
const shape = scan(def);
|
|
4760
|
+
if (shape.length > 0) return { ok: false, issues: capIssues(shape) };
|
|
4761
|
+
let bytes;
|
|
4762
|
+
try {
|
|
4763
|
+
bytes = utf8Length(JSON.stringify(def));
|
|
4764
|
+
} catch {
|
|
4765
|
+
return { ok: false, issues: [makeIssue("", "INVALID_SHAPE", "The definition must be JSON")] };
|
|
4766
|
+
}
|
|
4767
|
+
if (bytes > LIMITS.widgetDefinitionBytes) {
|
|
4768
|
+
return {
|
|
4769
|
+
ok: false,
|
|
4770
|
+
issues: [
|
|
4771
|
+
makeIssue(
|
|
4772
|
+
"",
|
|
4773
|
+
"WIDGET_TOO_LARGE",
|
|
4774
|
+
`The definition is ${String(bytes)} bytes, over the limit of ${String(LIMITS.widgetDefinitionBytes)}`
|
|
4775
|
+
)
|
|
4776
|
+
]
|
|
4777
|
+
};
|
|
4778
|
+
}
|
|
4779
|
+
const kind = def?.kind;
|
|
4780
|
+
if (typeof def !== "object" || def === null || Array.isArray(def)) {
|
|
4781
|
+
return { ok: false, issues: [makeIssue("", "INVALID_SHAPE", "Expected a widget definition object")] };
|
|
4782
|
+
}
|
|
4783
|
+
if (kind !== "composite" && kind !== "template") {
|
|
4784
|
+
return { ok: false, issues: [makeIssue("kind", "INVALID_VALUE", 'kind is "composite" or "template"')] };
|
|
4785
|
+
}
|
|
4786
|
+
const out = new Collector();
|
|
4787
|
+
if (kind === "template") {
|
|
4788
|
+
const parsed2 = templateSchema.safeParse(def);
|
|
4789
|
+
if (!parsed2.success) return { ok: false, issues: zodIssues(parsed2.error) };
|
|
4790
|
+
const full2 = { ...parsed2.data, settings: withCommonSettings(parsed2.data.settings, out) };
|
|
4791
|
+
checkText(full2, out);
|
|
4792
|
+
checkSettings(full2.settings, out);
|
|
4793
|
+
const result = checkTemplate(full2, registry, out);
|
|
4794
|
+
checkVersion(full2, registry, out);
|
|
4795
|
+
if (out.issues.length > 0 || result === null) return { ok: false, issues: capIssues(out.issues) };
|
|
4796
|
+
return { ok: true, normalized: plain2(result.normalized), ast: result.ast };
|
|
4797
|
+
}
|
|
4798
|
+
const parsed = compositeSchema.safeParse(def);
|
|
4799
|
+
if (!parsed.success) return { ok: false, issues: zodIssues(parsed.error) };
|
|
4800
|
+
const full = { ...parsed.data, settings: withCommonSettings(parsed.data.settings, out) };
|
|
4801
|
+
checkText(full, out);
|
|
4802
|
+
checkSettings(full.settings, out);
|
|
4803
|
+
const normalized = checkComposite(full, registry, out);
|
|
4804
|
+
checkVersion(full, registry, out);
|
|
4805
|
+
if (out.issues.length > 0 || normalized === null) return { ok: false, issues: capIssues(out.issues) };
|
|
4806
|
+
return { ok: true, normalized: plain2(normalized) };
|
|
4807
|
+
}
|
|
1530
4808
|
export {
|
|
4809
|
+
AGENT_MAX_OPS,
|
|
4810
|
+
ALLOWED_ATTRS,
|
|
4811
|
+
ALLOWED_ELEMENTS,
|
|
4812
|
+
ALLOWED_ROLES,
|
|
1531
4813
|
ANCHOR_RE,
|
|
1532
4814
|
BASIC_WIDGET_DEFINITIONS,
|
|
4815
|
+
BIDI_CONTROL_RE,
|
|
1533
4816
|
BREAKPOINTS,
|
|
1534
4817
|
CATALOG_STRING_KEYS,
|
|
4818
|
+
CLASS_TOKEN_RE,
|
|
1535
4819
|
COLOR_VALUE_RE,
|
|
4820
|
+
COMMON_SETTING_KEYS,
|
|
1536
4821
|
COMMON_WIDGET_SETTINGS,
|
|
4822
|
+
CSS_CONTROLS,
|
|
1537
4823
|
CURRENT_SCHEMA_VERSION,
|
|
4824
|
+
DATA_ATTR_RE,
|
|
1538
4825
|
DATA_RESULT_TYPES,
|
|
4826
|
+
EACH_ITERATION_CAP,
|
|
1539
4827
|
ISSUE_CODES,
|
|
1540
4828
|
LIMITS,
|
|
1541
4829
|
LOCALE_TAG_RE,
|
|
1542
4830
|
MAX_ISSUES,
|
|
4831
|
+
MAX_TEMPLATE_WEIGHT,
|
|
1543
4832
|
NODE_ID_RE,
|
|
1544
4833
|
PREVIEW_WIDTHS,
|
|
4834
|
+
RESERVED_CLASS_PREFIXES,
|
|
4835
|
+
RESERVED_DATA_PREFIX,
|
|
1545
4836
|
SAFE_HREF,
|
|
1546
4837
|
SETTING_CONTROLS,
|
|
1547
4838
|
SETTING_TABS,
|
|
@@ -1553,12 +4844,20 @@ export {
|
|
|
1553
4844
|
SITE_STRING_KEYS,
|
|
1554
4845
|
SITE_STRING_NAMESPACES,
|
|
1555
4846
|
SPACING_TOKENS,
|
|
4847
|
+
TEMPLATE_FILTERS,
|
|
1556
4848
|
THROTTLE_PK_RE,
|
|
4849
|
+
VOID_ELEMENTS,
|
|
1557
4850
|
WIDGET_GROUPS,
|
|
1558
4851
|
WIDGET_TYPE_RE,
|
|
4852
|
+
agentDocOpSchema,
|
|
4853
|
+
agentDocOpsSchema,
|
|
4854
|
+
applyOps,
|
|
1559
4855
|
assetIdSchema,
|
|
4856
|
+
canPlace,
|
|
1560
4857
|
capIssues,
|
|
1561
4858
|
checkLimits,
|
|
4859
|
+
checkTopLevel,
|
|
4860
|
+
checkWidgetPart,
|
|
1562
4861
|
colorValueSchema,
|
|
1563
4862
|
columnPropsSchema,
|
|
1564
4863
|
createRegistry,
|
|
@@ -1566,10 +4865,14 @@ export {
|
|
|
1566
4865
|
dataBindingSchema,
|
|
1567
4866
|
dataSourceDescriptorSchema,
|
|
1568
4867
|
defaultSiteSettings,
|
|
4868
|
+
docOpSchema,
|
|
1569
4869
|
emptyDocument,
|
|
1570
4870
|
fieldSpecSchema,
|
|
1571
4871
|
formatPath,
|
|
1572
4872
|
frozenAssetSchema,
|
|
4873
|
+
innerSectionNodeSchema,
|
|
4874
|
+
invertOps,
|
|
4875
|
+
isReservedClass,
|
|
1573
4876
|
isSettingValue,
|
|
1574
4877
|
localeTagSchema,
|
|
1575
4878
|
localizedTextSchema,
|
|
@@ -1579,21 +4882,30 @@ export {
|
|
|
1579
4882
|
newNodeId,
|
|
1580
4883
|
nodeIdSchema,
|
|
1581
4884
|
pageDocumentSchema,
|
|
4885
|
+
parseTemplate,
|
|
1582
4886
|
resolveColumnProps,
|
|
1583
4887
|
resolveColumnWidths,
|
|
1584
4888
|
resolveResponsive,
|
|
4889
|
+
safeUrl,
|
|
4890
|
+
sanitizeWidgetCss,
|
|
4891
|
+
sectionNodeSchema,
|
|
1585
4892
|
sectionPropsSchema,
|
|
1586
4893
|
settingFieldSchema,
|
|
1587
4894
|
settingValueSchema,
|
|
1588
4895
|
siteSettingsSchema,
|
|
1589
4896
|
spacingValueSchema,
|
|
4897
|
+
templateWeight,
|
|
1590
4898
|
upgradeDocument,
|
|
4899
|
+
upgradeNodes,
|
|
1591
4900
|
utf8Length,
|
|
4901
|
+
validateCustomWidget,
|
|
1592
4902
|
validateDocument,
|
|
1593
4903
|
validateSettingValue,
|
|
4904
|
+
validateTemplate,
|
|
1594
4905
|
validateWidgetProps,
|
|
1595
4906
|
walkNodes,
|
|
1596
4907
|
widgetDefinitionSchema,
|
|
4908
|
+
widgetNodeSchema,
|
|
1597
4909
|
wrapColumnRows,
|
|
1598
4910
|
zodIssues
|
|
1599
4911
|
};
|