@marktiderman/genesis-forms 0.3.1 → 0.4.1
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 +85 -1
- package/dist/destinations.cjs +159 -6
- package/dist/destinations.cjs.map +1 -1
- package/dist/destinations.js +159 -6
- package/dist/destinations.js.map +1 -1
- package/dist/{engine-CPLtKVew.d.cts → engine-BkNuzlna.d.cts} +2 -1
- package/dist/{engine-DOrPgFDw.d.ts → engine-Dz9J5ej2.d.ts} +2 -1
- package/dist/index.cjs +859 -22
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +205 -4
- package/dist/index.d.ts +205 -4
- package/dist/index.js +838 -23
- package/dist/index.js.map +1 -1
- package/dist/server.cjs +767 -18
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +5 -1
- package/dist/server.d.ts +5 -1
- package/dist/server.js +767 -18
- package/dist/server.js.map +1 -1
- package/dist/testing.cjs +769 -18
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +2 -2
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +769 -18
- package/dist/testing.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -28,6 +28,537 @@ function fingerprint(value) {
|
|
|
28
28
|
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, "0");
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
// src/formula.ts
|
|
32
|
+
var FORMULA_FUNCTIONS = ["sum", "avg", "min", "max"];
|
|
33
|
+
var MAX_FORMULA_LENGTH = 2e3;
|
|
34
|
+
var MAX_DEPTH = 64;
|
|
35
|
+
var OP_ALIASES = { "\u2212": "-", "\xD7": "*", "\xF7": "/", "\u2260": "!=", "\u2264": "<=", "\u2265": ">=", "=": "==" };
|
|
36
|
+
var TWO_CHAR = /* @__PURE__ */ new Set(["==", "!=", "<=", ">="]);
|
|
37
|
+
var ONE_CHAR = /* @__PURE__ */ new Set(["+", "-", "*", "/", "<", ">", "(", ")", "?", ":", ",", ".", "=", "\u2212", "\xD7", "\xF7", "\u2260", "\u2264", "\u2265"]);
|
|
38
|
+
var COMPARISONS = /* @__PURE__ */ new Set(["==", "!=", "<", "<=", ">", ">="]);
|
|
39
|
+
var FormulaError = class extends Error {
|
|
40
|
+
constructor(message, at) {
|
|
41
|
+
super(message);
|
|
42
|
+
this.at = at;
|
|
43
|
+
}
|
|
44
|
+
at;
|
|
45
|
+
};
|
|
46
|
+
var isIdStart = (c) => c >= "a" && c <= "z" || c >= "A" && c <= "Z" || c === "_";
|
|
47
|
+
var isIdPart = (c) => isIdStart(c) || c >= "0" && c <= "9";
|
|
48
|
+
var isDigit = (c) => c >= "0" && c <= "9";
|
|
49
|
+
function tokenize(source) {
|
|
50
|
+
const tokens = [];
|
|
51
|
+
let i = 0;
|
|
52
|
+
while (i < source.length) {
|
|
53
|
+
const c = source[i];
|
|
54
|
+
if (c === " " || c === " " || c === "\n" || c === "\r") {
|
|
55
|
+
i++;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const at = i;
|
|
59
|
+
if (isDigit(c) || c === "." && isDigit(source[i + 1] ?? "")) {
|
|
60
|
+
while (isDigit(source[i] ?? "")) i++;
|
|
61
|
+
if (source[i] === "." && isDigit(source[i + 1] ?? "")) {
|
|
62
|
+
i++;
|
|
63
|
+
while (isDigit(source[i] ?? "")) i++;
|
|
64
|
+
}
|
|
65
|
+
if (isIdStart(source[i] ?? "")) throw new FormulaError("Write a number in digits only, like 1000000.", at);
|
|
66
|
+
const v = Number(source.slice(at, i));
|
|
67
|
+
if (!Number.isFinite(v)) throw new FormulaError("This number is too large.", at);
|
|
68
|
+
tokens.push({ t: "num", v, at });
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (isIdStart(c)) {
|
|
72
|
+
while (isIdPart(source[i] ?? "")) i++;
|
|
73
|
+
tokens.push({ t: "id", v: source.slice(at, i), at });
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (c === '"' || c === "'" || c === "\u201C") {
|
|
77
|
+
const close = c === "\u201C" ? "\u201D" : c;
|
|
78
|
+
const end = source.indexOf(close, i + 1);
|
|
79
|
+
if (end === -1) throw new FormulaError("This text has no closing quote.", at);
|
|
80
|
+
tokens.push({ t: "str", v: source.slice(i + 1, end), at });
|
|
81
|
+
i = end + 1;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
const two = source.slice(i, i + 2);
|
|
85
|
+
if (TWO_CHAR.has(two)) {
|
|
86
|
+
tokens.push({ t: "op", v: two, at });
|
|
87
|
+
i += 2;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (ONE_CHAR.has(c)) {
|
|
91
|
+
tokens.push({ t: "op", v: OP_ALIASES[c] ?? c, at });
|
|
92
|
+
i++;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
throw new FormulaError(`"${c}" can't be used in a formula.`, at);
|
|
96
|
+
}
|
|
97
|
+
tokens.push({ t: "end", at: source.length });
|
|
98
|
+
return tokens;
|
|
99
|
+
}
|
|
100
|
+
function parseFormula(source) {
|
|
101
|
+
if (typeof source !== "string" || source.trim() === "") return { ok: false, message: "Write a formula.", at: 0 };
|
|
102
|
+
if (source.length > MAX_FORMULA_LENGTH) {
|
|
103
|
+
return { ok: false, message: `Keep the formula under ${MAX_FORMULA_LENGTH} characters.`, at: MAX_FORMULA_LENGTH };
|
|
104
|
+
}
|
|
105
|
+
let tokens;
|
|
106
|
+
try {
|
|
107
|
+
tokens = tokenize(source);
|
|
108
|
+
} catch (e) {
|
|
109
|
+
const err = e;
|
|
110
|
+
return { ok: false, message: err.message, at: err.at };
|
|
111
|
+
}
|
|
112
|
+
let pos = 0;
|
|
113
|
+
const refs = [];
|
|
114
|
+
const peek = () => tokens[pos];
|
|
115
|
+
const isOp = (v) => {
|
|
116
|
+
const tok = peek();
|
|
117
|
+
return tok.t === "op" && tok.v === v;
|
|
118
|
+
};
|
|
119
|
+
const expect = (v, message) => {
|
|
120
|
+
if (!isOp(v)) throw new FormulaError(message, peek().at);
|
|
121
|
+
pos++;
|
|
122
|
+
};
|
|
123
|
+
const describe = (tok) => tok.t === "end" ? "the formula ends there" : `found "${String(tok.v)}"`;
|
|
124
|
+
const guard = (depth) => {
|
|
125
|
+
if (depth > MAX_DEPTH) throw new FormulaError("The formula is nested too deeply.", peek().at);
|
|
126
|
+
};
|
|
127
|
+
const ternary = (depth) => {
|
|
128
|
+
guard(depth);
|
|
129
|
+
const test = comparison(depth);
|
|
130
|
+
if (!isOp("?")) return test;
|
|
131
|
+
pos++;
|
|
132
|
+
const then = ternary(depth + 1);
|
|
133
|
+
expect(":", "A `?` needs a `:` and the other value: `test ? a : b`.");
|
|
134
|
+
const otherwise = ternary(depth + 1);
|
|
135
|
+
return { kind: "if", test, then, else: otherwise };
|
|
136
|
+
};
|
|
137
|
+
const comparison = (depth) => {
|
|
138
|
+
const left = additive(depth);
|
|
139
|
+
const tok = peek();
|
|
140
|
+
if (tok.t !== "op" || !COMPARISONS.has(tok.v)) return left;
|
|
141
|
+
pos++;
|
|
142
|
+
const right = additive(depth);
|
|
143
|
+
const next = peek();
|
|
144
|
+
if (next.t === "op" && COMPARISONS.has(next.v)) {
|
|
145
|
+
throw new FormulaError("Compare two values at a time; combine comparisons with `? :`.", next.at);
|
|
146
|
+
}
|
|
147
|
+
return { kind: "binary", op: tok.v, left, right };
|
|
148
|
+
};
|
|
149
|
+
const additive = (depth) => {
|
|
150
|
+
let left = multiplicative(depth);
|
|
151
|
+
for (let tok = peek(); tok.t === "op" && (tok.v === "+" || tok.v === "-"); tok = peek()) {
|
|
152
|
+
pos++;
|
|
153
|
+
left = { kind: "binary", op: tok.v, left, right: multiplicative(depth) };
|
|
154
|
+
}
|
|
155
|
+
return left;
|
|
156
|
+
};
|
|
157
|
+
const multiplicative = (depth) => {
|
|
158
|
+
let left = unary(depth);
|
|
159
|
+
for (let tok = peek(); tok.t === "op" && (tok.v === "*" || tok.v === "/"); tok = peek()) {
|
|
160
|
+
pos++;
|
|
161
|
+
left = { kind: "binary", op: tok.v, left, right: unary(depth) };
|
|
162
|
+
}
|
|
163
|
+
return left;
|
|
164
|
+
};
|
|
165
|
+
const unary = (depth) => {
|
|
166
|
+
guard(depth);
|
|
167
|
+
if (isOp("-")) {
|
|
168
|
+
pos++;
|
|
169
|
+
return { kind: "unary", op: "-", arg: unary(depth + 1) };
|
|
170
|
+
}
|
|
171
|
+
if (isOp("+")) {
|
|
172
|
+
pos++;
|
|
173
|
+
return unary(depth + 1);
|
|
174
|
+
}
|
|
175
|
+
return primary(depth);
|
|
176
|
+
};
|
|
177
|
+
const primary = (depth) => {
|
|
178
|
+
const tok = peek();
|
|
179
|
+
if (tok.t === "num") {
|
|
180
|
+
pos++;
|
|
181
|
+
return { kind: "number", value: tok.v };
|
|
182
|
+
}
|
|
183
|
+
if (tok.t === "str") {
|
|
184
|
+
pos++;
|
|
185
|
+
return { kind: "text", value: tok.v };
|
|
186
|
+
}
|
|
187
|
+
if (tok.t === "op" && tok.v === "(") {
|
|
188
|
+
pos++;
|
|
189
|
+
const inner = ternary(depth + 1);
|
|
190
|
+
expect(")", "A `(` has no matching `)`.");
|
|
191
|
+
return inner;
|
|
192
|
+
}
|
|
193
|
+
if (tok.t === "id") {
|
|
194
|
+
pos++;
|
|
195
|
+
if (isOp("(")) {
|
|
196
|
+
if (!FORMULA_FUNCTIONS.includes(tok.v)) {
|
|
197
|
+
throw new FormulaError(`There is no function "${tok.v}"; use ${FORMULA_FUNCTIONS.join(", ")}.`, tok.at);
|
|
198
|
+
}
|
|
199
|
+
pos++;
|
|
200
|
+
const args = [];
|
|
201
|
+
if (!isOp(")")) {
|
|
202
|
+
args.push(ternary(depth + 1));
|
|
203
|
+
while (isOp(",")) {
|
|
204
|
+
pos++;
|
|
205
|
+
args.push(ternary(depth + 1));
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
expect(")", `"${tok.v}(" has no matching ")".`);
|
|
209
|
+
if (!args.length) throw new FormulaError(`${tok.v}() needs something to work on.`, tok.at);
|
|
210
|
+
return { kind: "call", fn: tok.v, args };
|
|
211
|
+
}
|
|
212
|
+
if (isOp(".")) {
|
|
213
|
+
pos++;
|
|
214
|
+
const column = peek();
|
|
215
|
+
if (column.t !== "id") throw new FormulaError(`Name a column after "${tok.v}.".`, column.at);
|
|
216
|
+
pos++;
|
|
217
|
+
refs.push({ key: tok.v, column: column.v });
|
|
218
|
+
return { kind: "ref", key: tok.v, column: column.v, at: tok.at };
|
|
219
|
+
}
|
|
220
|
+
refs.push({ key: tok.v });
|
|
221
|
+
return { kind: "ref", key: tok.v, at: tok.at };
|
|
222
|
+
}
|
|
223
|
+
throw new FormulaError(`Expected a number, an answer or "(", but ${describe(tok)}.`, tok.at);
|
|
224
|
+
};
|
|
225
|
+
try {
|
|
226
|
+
const ast = ternary(0);
|
|
227
|
+
const rest = peek();
|
|
228
|
+
if (rest.t !== "end") throw new FormulaError(`Expected an operator such as + or *, but ${describe(rest)}.`, rest.at);
|
|
229
|
+
return { ok: true, ast, refs };
|
|
230
|
+
} catch (e) {
|
|
231
|
+
if (e instanceof FormulaError) return { ok: false, message: e.message, at: e.at };
|
|
232
|
+
return { ok: false, message: "The formula is nested too deeply.", at: 0 };
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
function formulaRefs(source) {
|
|
236
|
+
const parsed = parseFormula(source);
|
|
237
|
+
if (!parsed.ok) return [];
|
|
238
|
+
const seen = /* @__PURE__ */ new Set();
|
|
239
|
+
return parsed.refs.filter((r) => {
|
|
240
|
+
const id = `${r.key}\0${r.column ?? ""}`;
|
|
241
|
+
if (seen.has(id)) return false;
|
|
242
|
+
seen.add(id);
|
|
243
|
+
return true;
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
function renameFormulaKey(source, from, to) {
|
|
247
|
+
let tokens;
|
|
248
|
+
try {
|
|
249
|
+
tokens = tokenize(source);
|
|
250
|
+
} catch {
|
|
251
|
+
return source;
|
|
252
|
+
}
|
|
253
|
+
let out = "";
|
|
254
|
+
let last = 0;
|
|
255
|
+
tokens.forEach((tok, i) => {
|
|
256
|
+
if (tok.t !== "id" || tok.v !== from) return;
|
|
257
|
+
const prev = tokens[i - 1];
|
|
258
|
+
const next = tokens[i + 1];
|
|
259
|
+
if (prev?.t === "op" && prev.v === ".") return;
|
|
260
|
+
if (next?.t === "op" && next.v === "(") return;
|
|
261
|
+
out += source.slice(last, tok.at) + to;
|
|
262
|
+
last = tok.at + from.length;
|
|
263
|
+
});
|
|
264
|
+
return out + source.slice(last);
|
|
265
|
+
}
|
|
266
|
+
var NUMERIC = /^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;
|
|
267
|
+
function formulaNumber(v) {
|
|
268
|
+
if (typeof v === "number") return Number.isFinite(v) ? v : null;
|
|
269
|
+
if (typeof v === "boolean") return v ? 1 : 0;
|
|
270
|
+
if (typeof v === "string") {
|
|
271
|
+
const t = v.trim().replace(/,/g, "");
|
|
272
|
+
return t.length <= 64 && NUMERIC.test(t) ? finite(Number(t)) : null;
|
|
273
|
+
}
|
|
274
|
+
return null;
|
|
275
|
+
}
|
|
276
|
+
var finite = (n) => Number.isFinite(n) ? n : null;
|
|
277
|
+
var scalar = (v) => Array.isArray(v) ? null : v;
|
|
278
|
+
function truthy(v) {
|
|
279
|
+
if (v === null) return false;
|
|
280
|
+
if (typeof v === "boolean") return v;
|
|
281
|
+
if (typeof v === "number") return v !== 0;
|
|
282
|
+
if (typeof v === "string") return v.trim() !== "";
|
|
283
|
+
return v.length > 0;
|
|
284
|
+
}
|
|
285
|
+
function numbersIn(values, out = []) {
|
|
286
|
+
for (const v of values) {
|
|
287
|
+
if (Array.isArray(v)) numbersIn(v, out);
|
|
288
|
+
else {
|
|
289
|
+
const n = formulaNumber(v);
|
|
290
|
+
if (n !== null) out.push(n);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
return out;
|
|
294
|
+
}
|
|
295
|
+
var listTotals = /* @__PURE__ */ new WeakMap();
|
|
296
|
+
var ownLists = /* @__PURE__ */ new WeakSet();
|
|
297
|
+
function ownFormulaList(list) {
|
|
298
|
+
Object.freeze(list);
|
|
299
|
+
ownLists.add(list);
|
|
300
|
+
return list;
|
|
301
|
+
}
|
|
302
|
+
function totalsOf(list) {
|
|
303
|
+
const own2 = ownLists.has(list);
|
|
304
|
+
let t = own2 ? listTotals.get(list) : void 0;
|
|
305
|
+
if (t) return t;
|
|
306
|
+
const nums = numbersIn(list);
|
|
307
|
+
t = { sum: 0, count: nums.length, min: Infinity, max: -Infinity };
|
|
308
|
+
for (const n of nums) {
|
|
309
|
+
t.sum += n;
|
|
310
|
+
if (n < t.min) t.min = n;
|
|
311
|
+
if (n > t.max) t.max = n;
|
|
312
|
+
}
|
|
313
|
+
if (own2) listTotals.set(list, t);
|
|
314
|
+
return t;
|
|
315
|
+
}
|
|
316
|
+
function compare(op, a, b) {
|
|
317
|
+
const blank2 = (v) => v === null || Array.isArray(v) || typeof v === "string" && v.trim() === "";
|
|
318
|
+
if (blank2(a) || blank2(b)) return op === "!=";
|
|
319
|
+
const x = formulaNumber(a);
|
|
320
|
+
const y = formulaNumber(b);
|
|
321
|
+
if (x !== null && y !== null) {
|
|
322
|
+
if (op === "==") return x === y;
|
|
323
|
+
if (op === "!=") return x !== y;
|
|
324
|
+
if (op === "<") return x < y;
|
|
325
|
+
if (op === "<=") return x <= y;
|
|
326
|
+
if (op === ">") return x > y;
|
|
327
|
+
return x >= y;
|
|
328
|
+
}
|
|
329
|
+
if (op === "==") return String(a) === String(b);
|
|
330
|
+
if (op === "!=") return String(a) !== String(b);
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
function evaluateFormula(ast, read) {
|
|
334
|
+
const run = (node) => {
|
|
335
|
+
switch (node.kind) {
|
|
336
|
+
case "number":
|
|
337
|
+
case "text":
|
|
338
|
+
return node.value;
|
|
339
|
+
case "ref":
|
|
340
|
+
return read(node);
|
|
341
|
+
case "unary": {
|
|
342
|
+
const n = formulaNumber(scalar(run(node.arg)));
|
|
343
|
+
return n === null ? null : -n;
|
|
344
|
+
}
|
|
345
|
+
case "if":
|
|
346
|
+
return truthy(run(node.test)) ? run(node.then) : run(node.else);
|
|
347
|
+
case "call": {
|
|
348
|
+
let total = 0;
|
|
349
|
+
let count = 0;
|
|
350
|
+
let min = Infinity;
|
|
351
|
+
let max = -Infinity;
|
|
352
|
+
for (const arg of node.args) {
|
|
353
|
+
const v = run(arg);
|
|
354
|
+
if (Array.isArray(v)) {
|
|
355
|
+
const t = totalsOf(v);
|
|
356
|
+
total += t.sum;
|
|
357
|
+
count += t.count;
|
|
358
|
+
if (t.min < min) min = t.min;
|
|
359
|
+
if (t.max > max) max = t.max;
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
const n = formulaNumber(v);
|
|
363
|
+
if (n === null) continue;
|
|
364
|
+
total += n;
|
|
365
|
+
count++;
|
|
366
|
+
if (n < min) min = n;
|
|
367
|
+
if (n > max) max = n;
|
|
368
|
+
}
|
|
369
|
+
if (node.fn === "sum") return finite(total);
|
|
370
|
+
if (!count) return null;
|
|
371
|
+
if (node.fn === "avg") return finite(total / count);
|
|
372
|
+
return node.fn === "min" ? min : max;
|
|
373
|
+
}
|
|
374
|
+
case "binary": {
|
|
375
|
+
const a = run(node.left);
|
|
376
|
+
const b = run(node.right);
|
|
377
|
+
if (node.op === "+" || node.op === "-" || node.op === "*" || node.op === "/") {
|
|
378
|
+
const x = formulaNumber(scalar(a));
|
|
379
|
+
const y = formulaNumber(scalar(b));
|
|
380
|
+
if (x === null || y === null) return null;
|
|
381
|
+
if (node.op === "+") return finite(x + y);
|
|
382
|
+
if (node.op === "-") return finite(x - y);
|
|
383
|
+
if (node.op === "*") return finite(x * y);
|
|
384
|
+
return y === 0 ? null : finite(x / y);
|
|
385
|
+
}
|
|
386
|
+
return compare(node.op, a, b);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
try {
|
|
391
|
+
return run(ast);
|
|
392
|
+
} catch {
|
|
393
|
+
return null;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// src/calculated.ts
|
|
398
|
+
var CALCULATED_TYPE = "calculated";
|
|
399
|
+
var COMPUTED_FIELD_TYPES = [CALCULATED_TYPE];
|
|
400
|
+
var MAX_FORM_FORMULA_LENGTH = 2e4;
|
|
401
|
+
var MAX_CALCULATED_DECIMALS = 10;
|
|
402
|
+
function calculatedProps(field2) {
|
|
403
|
+
const p = field2.props ?? {};
|
|
404
|
+
const out = { formula: typeof p.formula === "string" ? p.formula : "" };
|
|
405
|
+
if (p.format === "number" || p.format === "percent" || p.format === "text") out.format = p.format;
|
|
406
|
+
if (typeof p.decimals === "number" && Number.isInteger(p.decimals) && p.decimals >= 0 && p.decimals <= MAX_CALCULATED_DECIMALS) {
|
|
407
|
+
out.decimals = p.decimals;
|
|
408
|
+
}
|
|
409
|
+
return out;
|
|
410
|
+
}
|
|
411
|
+
var isCalculated = (field2) => field2?.type === CALCULATED_TYPE;
|
|
412
|
+
var round = (n, decimals) => {
|
|
413
|
+
if (decimals === void 0) return n;
|
|
414
|
+
const r = Number(n.toFixed(decimals));
|
|
415
|
+
return Object.is(r, -0) ? 0 : r;
|
|
416
|
+
};
|
|
417
|
+
function calculatedValue(result, field2) {
|
|
418
|
+
const { format, decimals } = calculatedProps(field2);
|
|
419
|
+
if (result === null || Array.isArray(result)) return void 0;
|
|
420
|
+
if (format === "number" || format === "percent") {
|
|
421
|
+
const n = formulaNumber(result);
|
|
422
|
+
return n === null ? void 0 : round(n, decimals);
|
|
423
|
+
}
|
|
424
|
+
if (format === "text") {
|
|
425
|
+
if (typeof result === "number") return decimals === void 0 ? String(result) : result.toFixed(decimals);
|
|
426
|
+
return typeof result === "boolean" ? result ? "Yes" : "No" : result;
|
|
427
|
+
}
|
|
428
|
+
return typeof result === "number" ? round(result, decimals) : result;
|
|
429
|
+
}
|
|
430
|
+
function formatCalculated(value, field2) {
|
|
431
|
+
if (value === void 0 || value === null) return "";
|
|
432
|
+
const { format, decimals } = calculatedProps(field2);
|
|
433
|
+
const fixed = (n) => decimals === void 0 ? String(Number(n.toFixed(6))) : n.toFixed(decimals);
|
|
434
|
+
if (typeof value === "number") return format === "percent" ? `${fixed(value * 100)}%` : fixed(value);
|
|
435
|
+
if (typeof value === "boolean") return value ? "Yes" : "No";
|
|
436
|
+
return typeof value === "string" ? value : "";
|
|
437
|
+
}
|
|
438
|
+
var MAX_FORMULA_ITEMS = 1e4;
|
|
439
|
+
var MAX_SETTLE_ITEMS = 5e4;
|
|
440
|
+
var extract = (value, column) => column !== void 0 ? value.flatMap((row) => {
|
|
441
|
+
if (!row || typeof row !== "object" || Array.isArray(row)) return [];
|
|
442
|
+
const cell = row[column];
|
|
443
|
+
return typeof cell === "string" || typeof cell === "number" ? [cell] : [];
|
|
444
|
+
}) : value.flatMap((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean" ? [v] : []);
|
|
445
|
+
var extracted = /* @__PURE__ */ new WeakMap();
|
|
446
|
+
function cachedList(value, column) {
|
|
447
|
+
let byColumn = extracted.get(value);
|
|
448
|
+
if (!byColumn) extracted.set(value, byColumn = /* @__PURE__ */ new Map());
|
|
449
|
+
const key = column ?? "";
|
|
450
|
+
let list = byColumn.get(key);
|
|
451
|
+
if (!list) byColumn.set(key, list = ownFormulaList(extract(value, column)));
|
|
452
|
+
return list;
|
|
453
|
+
}
|
|
454
|
+
function readAnswer(value, column) {
|
|
455
|
+
if (Array.isArray(value)) return cachedList(value, column);
|
|
456
|
+
return column !== void 0 ? null : formulaInput(value);
|
|
457
|
+
}
|
|
458
|
+
function formulaInput(value, column) {
|
|
459
|
+
if (value === void 0 || value === null) return null;
|
|
460
|
+
if (Array.isArray(value) && value.length > MAX_FORMULA_ITEMS) return null;
|
|
461
|
+
if (column !== void 0) {
|
|
462
|
+
if (!Array.isArray(value)) return null;
|
|
463
|
+
return extract(value, column);
|
|
464
|
+
}
|
|
465
|
+
if (Array.isArray(value)) return extract(value, void 0);
|
|
466
|
+
return typeof value === "object" ? null : value;
|
|
467
|
+
}
|
|
468
|
+
function refNodes(node, out = []) {
|
|
469
|
+
if (node.kind === "ref") out.push(node);
|
|
470
|
+
else if (node.kind === "unary") refNodes(node.arg, out);
|
|
471
|
+
else if (node.kind === "binary") refNodes(node.left, out), refNodes(node.right, out);
|
|
472
|
+
else if (node.kind === "if") refNodes(node.test, out), refNodes(node.then, out), refNodes(node.else, out);
|
|
473
|
+
else if (node.kind === "call") for (const a of node.args) refNodes(a, out);
|
|
474
|
+
return out;
|
|
475
|
+
}
|
|
476
|
+
var UNREAD = /* @__PURE__ */ Symbol("unread");
|
|
477
|
+
var OVER = /* @__PURE__ */ Symbol("over");
|
|
478
|
+
function calculator(definition) {
|
|
479
|
+
const compiled = [];
|
|
480
|
+
const idByKey = /* @__PURE__ */ new Map();
|
|
481
|
+
for (const block of definition.blocks) {
|
|
482
|
+
if (block.kind !== "field") continue;
|
|
483
|
+
idByKey.set(block.key, block.id);
|
|
484
|
+
}
|
|
485
|
+
for (const block of definition.blocks) {
|
|
486
|
+
if (block.kind !== "field" || !isCalculated(block)) continue;
|
|
487
|
+
const parsed = parseFormula(calculatedProps(block).formula);
|
|
488
|
+
const reads = [];
|
|
489
|
+
const slots = /* @__PURE__ */ new Map();
|
|
490
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
491
|
+
for (const ref of parsed.ok ? refNodes(parsed.ast) : []) {
|
|
492
|
+
const id = idByKey.get(ref.key);
|
|
493
|
+
const key = `${id ?? ""}\0${ref.column ?? ""}`;
|
|
494
|
+
let slot = byKey.get(key);
|
|
495
|
+
if (slot === void 0) {
|
|
496
|
+
slot = reads.push({ id, column: ref.column, key }) - 1;
|
|
497
|
+
byKey.set(key, slot);
|
|
498
|
+
}
|
|
499
|
+
slots.set(ref, slot);
|
|
500
|
+
}
|
|
501
|
+
compiled.push({ field: block, ast: parsed.ok ? parsed.ast : null, reads, slots, last: null });
|
|
502
|
+
}
|
|
503
|
+
const withCalculated = (values, path) => {
|
|
504
|
+
if (!compiled.length) return values;
|
|
505
|
+
const visible = new Set(path);
|
|
506
|
+
let next = values;
|
|
507
|
+
let budget = MAX_SETTLE_ITEMS;
|
|
508
|
+
const within = /* @__PURE__ */ new Map();
|
|
509
|
+
const input = ({ id, key }) => {
|
|
510
|
+
if (id === void 0 || !visible.has(id) || !Object.prototype.hasOwnProperty.call(next, id)) return UNREAD;
|
|
511
|
+
const value = next[id];
|
|
512
|
+
if (!Array.isArray(value)) return value;
|
|
513
|
+
let ok = within.get(key);
|
|
514
|
+
if (ok === void 0) {
|
|
515
|
+
ok = value.length <= MAX_FORMULA_ITEMS && value.length <= budget;
|
|
516
|
+
if (ok) budget -= value.length;
|
|
517
|
+
within.set(key, ok);
|
|
518
|
+
}
|
|
519
|
+
return ok ? value : OVER;
|
|
520
|
+
};
|
|
521
|
+
for (const entry of compiled) {
|
|
522
|
+
const { field: field2, ast } = entry;
|
|
523
|
+
const inputs = entry.reads.map(input);
|
|
524
|
+
let value;
|
|
525
|
+
if (entry.last && entry.last.inputs.length === inputs.length && entry.last.inputs.every((v, i) => v === inputs[i])) {
|
|
526
|
+
value = entry.last.value;
|
|
527
|
+
} else {
|
|
528
|
+
const resolved = new Array(inputs.length);
|
|
529
|
+
const read = (ref) => {
|
|
530
|
+
const slot = entry.slots.get(ref);
|
|
531
|
+
if (slot === void 0) return null;
|
|
532
|
+
let v = resolved[slot];
|
|
533
|
+
if (v === void 0) {
|
|
534
|
+
const raw = inputs[slot];
|
|
535
|
+
v = resolved[slot] = raw === UNREAD ? null : readAnswer(raw, entry.reads[slot].column);
|
|
536
|
+
}
|
|
537
|
+
return v;
|
|
538
|
+
};
|
|
539
|
+
value = ast && !inputs.includes(OVER) ? calculatedValue(evaluateFormula(ast, read), field2) : void 0;
|
|
540
|
+
entry.last = { inputs, value };
|
|
541
|
+
}
|
|
542
|
+
const current = Object.prototype.hasOwnProperty.call(next, field2.id) ? next[field2.id] : void 0;
|
|
543
|
+
if (current !== value) next = { ...next, [field2.id]: value };
|
|
544
|
+
}
|
|
545
|
+
return next;
|
|
546
|
+
};
|
|
547
|
+
return { active: compiled.length > 0, withCalculated };
|
|
548
|
+
}
|
|
549
|
+
var numberOps = ["eq", "neq", "lt", "lte", "gt", "gte", "in", "answered", "empty"];
|
|
550
|
+
var calculatedFieldType = {
|
|
551
|
+
type: CALCULATED_TYPE,
|
|
552
|
+
label: "Calculated",
|
|
553
|
+
category: "advanced",
|
|
554
|
+
value: { json: true },
|
|
555
|
+
operators: numberOps,
|
|
556
|
+
a11y: { semantics: "control" },
|
|
557
|
+
// The engine works the value out; any number, text or true / false it made is valid.
|
|
558
|
+
validate: (value) => typeof value === "number" || typeof value === "string" || typeof value === "boolean" ? null : "This value is worked out from other answers.",
|
|
559
|
+
summarize: (value, field2) => formatCalculated(value, field2)
|
|
560
|
+
};
|
|
561
|
+
|
|
31
562
|
// src/events.ts
|
|
32
563
|
function isPlainObject(value) {
|
|
33
564
|
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
@@ -322,7 +853,7 @@ function intRange(field2, min, maxDefault) {
|
|
|
322
853
|
const max = typeof field2.props?.max === "number" ? field2.props.max : maxDefault;
|
|
323
854
|
return { min, max };
|
|
324
855
|
}
|
|
325
|
-
var
|
|
856
|
+
var numberOps2 = ["eq", "neq", "lt", "lte", "gt", "gte", "in", "answered", "empty"];
|
|
326
857
|
var textOps = ["eq", "neq", "contains", "answered", "empty"];
|
|
327
858
|
function maxLength(field2, fallback) {
|
|
328
859
|
return typeof field2.props?.maxLength === "number" ? field2.props.maxLength : fallback;
|
|
@@ -400,23 +931,30 @@ var builtins = [
|
|
|
400
931
|
label: "Rating",
|
|
401
932
|
category: "scale",
|
|
402
933
|
value: { json: true },
|
|
403
|
-
operators:
|
|
934
|
+
operators: numberOps2,
|
|
404
935
|
a11y: { semantics: "group" },
|
|
405
936
|
validate: (value, field2) => {
|
|
406
937
|
const { min, max } = intRange(field2, 1, 5);
|
|
407
938
|
return Number.isInteger(value) && value >= min && value <= max ? null : `Choose a rating from ${min} to ${max}.`;
|
|
408
939
|
},
|
|
409
|
-
summarize: (value, field2) =>
|
|
940
|
+
summarize: (value, field2) => {
|
|
941
|
+
const { max } = intRange(field2, 1, 5);
|
|
942
|
+
const end = scaleEndLabel(field2, value, 1, max);
|
|
943
|
+
return end ? `${value}/${max} (${end})` : `${value}/${max}`;
|
|
944
|
+
}
|
|
410
945
|
},
|
|
411
946
|
{
|
|
412
947
|
type: "nps",
|
|
413
948
|
label: "Net Promoter Score",
|
|
414
949
|
category: "scale",
|
|
415
950
|
value: { json: true },
|
|
416
|
-
operators:
|
|
951
|
+
operators: numberOps2,
|
|
417
952
|
a11y: { semantics: "group" },
|
|
418
953
|
validate: (value) => Number.isInteger(value) && value >= 0 && value <= 10 ? null : "Choose a score from 0 to 10.",
|
|
419
|
-
summarize: (value) =>
|
|
954
|
+
summarize: (value, field2) => {
|
|
955
|
+
const end = scaleEndLabel(field2, value, 0, 10);
|
|
956
|
+
return end ? `${value}/10 (${end})` : `${value}/10`;
|
|
957
|
+
}
|
|
420
958
|
},
|
|
421
959
|
{
|
|
422
960
|
type: "single-choice",
|
|
@@ -450,9 +988,125 @@ var builtins = [
|
|
|
450
988
|
a11y: { semantics: "group" },
|
|
451
989
|
validate: (value) => typeof value === "boolean" ? null : "Choose yes or no.",
|
|
452
990
|
summarize: (value) => value ? "Yes" : "No"
|
|
991
|
+
},
|
|
992
|
+
{
|
|
993
|
+
type: "dropdown",
|
|
994
|
+
label: "Dropdown",
|
|
995
|
+
category: "choice",
|
|
996
|
+
value: { json: true },
|
|
997
|
+
operators: ["eq", "neq", "in", "answered", "empty"],
|
|
998
|
+
a11y: { semantics: "control" },
|
|
999
|
+
validate: (value, field2) => typeof value === "string" && choiceOptions(field2).some((o) => o.value === value) ? null : "Choose one of the options.",
|
|
1000
|
+
summarize: (value, field2) => optionLabel(field2, String(value))
|
|
1001
|
+
},
|
|
1002
|
+
{
|
|
1003
|
+
type: "number",
|
|
1004
|
+
label: "Number",
|
|
1005
|
+
category: "text",
|
|
1006
|
+
value: { json: true },
|
|
1007
|
+
operators: numberOps2,
|
|
1008
|
+
a11y: { semantics: "control", inputMode: "decimal" },
|
|
1009
|
+
validate: (value, field2) => {
|
|
1010
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return "Enter a number.";
|
|
1011
|
+
const { min, max, step } = numberLimits(field2);
|
|
1012
|
+
if (min !== void 0 && max !== void 0 && (value < min || value > max)) {
|
|
1013
|
+
return `Enter a number from ${min} to ${max}.`;
|
|
1014
|
+
}
|
|
1015
|
+
if (min !== void 0 && value < min) return `Enter ${min} or more.`;
|
|
1016
|
+
if (max !== void 0 && value > max) return `Enter ${max} or less.`;
|
|
1017
|
+
if (step !== void 0 && !onStep(value, min ?? 0, step)) {
|
|
1018
|
+
return step === 1 && Number.isInteger(min ?? 0) ? "Enter a whole number." : `Enter a number in steps of ${step}.`;
|
|
1019
|
+
}
|
|
1020
|
+
return null;
|
|
1021
|
+
},
|
|
1022
|
+
summarize: (value) => String(value),
|
|
1023
|
+
samples: (field2) => {
|
|
1024
|
+
const { min, max } = numberLimits(field2);
|
|
1025
|
+
return [min, max, 0, 1].filter((v) => v !== void 0);
|
|
1026
|
+
}
|
|
1027
|
+
},
|
|
1028
|
+
{
|
|
1029
|
+
type: "date",
|
|
1030
|
+
label: "Date",
|
|
1031
|
+
category: "date",
|
|
1032
|
+
value: { json: true },
|
|
1033
|
+
operators: ["eq", "neq", "answered", "empty"],
|
|
1034
|
+
a11y: { semantics: "control" },
|
|
1035
|
+
validate: (value, field2) => {
|
|
1036
|
+
if (typeof value !== "string" || !isIsoDate(value.trim())) return "Enter a date like 2026-10-22.";
|
|
1037
|
+
const date = value.trim();
|
|
1038
|
+
const { min, max } = dateLimits(field2);
|
|
1039
|
+
if (min && max && (date < min || date > max)) return `Choose a date from ${min} to ${max}.`;
|
|
1040
|
+
if (min && date < min) return `Choose ${min} or later.`;
|
|
1041
|
+
if (max && date > max) return `Choose ${max} or earlier.`;
|
|
1042
|
+
return null;
|
|
1043
|
+
},
|
|
1044
|
+
normalize: (value) => typeof value === "string" ? value.trim() : value,
|
|
1045
|
+
samples: (field2) => {
|
|
1046
|
+
const { min, max } = dateLimits(field2);
|
|
1047
|
+
return [min ?? max ?? "2000-01-01"];
|
|
1048
|
+
}
|
|
1049
|
+
},
|
|
1050
|
+
{
|
|
1051
|
+
type: "consent",
|
|
1052
|
+
label: "Consent checkbox",
|
|
1053
|
+
category: "choice",
|
|
1054
|
+
value: { json: true },
|
|
1055
|
+
operators: ["answered", "empty"],
|
|
1056
|
+
a11y: { semantics: "group" },
|
|
1057
|
+
// Unchecked is unanswered, so a required consent must be checked.
|
|
1058
|
+
isEmpty: (value) => value === void 0 || value === null || value === false,
|
|
1059
|
+
validate: (value) => value === true ? null : "Check the box to agree.",
|
|
1060
|
+
summarize: () => "Agreed",
|
|
1061
|
+
samples: () => [true]
|
|
453
1062
|
}
|
|
454
1063
|
];
|
|
455
|
-
|
|
1064
|
+
function scaleLabels(field2) {
|
|
1065
|
+
const out = {};
|
|
1066
|
+
const low = field2.props?.lowLabel;
|
|
1067
|
+
const high = field2.props?.highLabel;
|
|
1068
|
+
if (typeof low === "string" && low.trim()) out.low = low.trim();
|
|
1069
|
+
if (typeof high === "string" && high.trim()) out.high = high.trim();
|
|
1070
|
+
return out;
|
|
1071
|
+
}
|
|
1072
|
+
function ratingDisplay(field2) {
|
|
1073
|
+
return field2.props?.display === "stars" ? "stars" : "numbers";
|
|
1074
|
+
}
|
|
1075
|
+
function scaleEndLabel(field2, value, min, max) {
|
|
1076
|
+
const { low, high } = scaleLabels(field2);
|
|
1077
|
+
return value === min ? low : value === max ? high : void 0;
|
|
1078
|
+
}
|
|
1079
|
+
var finite2 = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
|
|
1080
|
+
function numberLimits(field2) {
|
|
1081
|
+
const out = {};
|
|
1082
|
+
const min = finite2(field2.props?.min);
|
|
1083
|
+
const max = finite2(field2.props?.max);
|
|
1084
|
+
const step = finite2(field2.props?.step);
|
|
1085
|
+
if (min !== void 0) out.min = min;
|
|
1086
|
+
if (max !== void 0) out.max = max;
|
|
1087
|
+
if (step !== void 0 && step > 0) out.step = step;
|
|
1088
|
+
return out;
|
|
1089
|
+
}
|
|
1090
|
+
function onStep(value, base, step) {
|
|
1091
|
+
const n = (value - base) / step;
|
|
1092
|
+
return Math.abs(n - Math.round(n)) < 1e-9 * Math.max(1, Math.abs(n));
|
|
1093
|
+
}
|
|
1094
|
+
function isIsoDate(value) {
|
|
1095
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
|
|
1096
|
+
const [y, m, d] = value.split("-").map(Number);
|
|
1097
|
+
if (y < 1 || m < 1 || m > 12 || d < 1) return false;
|
|
1098
|
+
const days = [31, y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
1099
|
+
return d <= days[m - 1];
|
|
1100
|
+
}
|
|
1101
|
+
function dateLimits(field2) {
|
|
1102
|
+
const out = {};
|
|
1103
|
+
const min = field2.props?.min;
|
|
1104
|
+
const max = field2.props?.max;
|
|
1105
|
+
if (typeof min === "string" && isIsoDate(min)) out.min = min;
|
|
1106
|
+
if (typeof max === "string" && isIsoDate(max)) out.max = max;
|
|
1107
|
+
return out;
|
|
1108
|
+
}
|
|
1109
|
+
for (const manifest of [...builtins, ...structuredFieldTypes, calculatedFieldType]) registerFieldType(manifest);
|
|
456
1110
|
|
|
457
1111
|
// src/logic.ts
|
|
458
1112
|
function own(record, key) {
|
|
@@ -624,8 +1278,15 @@ var LITERAL_TYPE = {
|
|
|
624
1278
|
"single-choice": "string",
|
|
625
1279
|
"multi-choice": "string",
|
|
626
1280
|
"yes-no": "boolean",
|
|
627
|
-
list: "string"
|
|
1281
|
+
list: "string",
|
|
1282
|
+
dropdown: "string",
|
|
1283
|
+
number: "number",
|
|
1284
|
+
date: "string",
|
|
1285
|
+
consent: "boolean",
|
|
1286
|
+
// A calculated field holds a number unless its format says text; see `literalType`.
|
|
1287
|
+
calculated: "number"
|
|
628
1288
|
};
|
|
1289
|
+
var CHOICE_TYPES = /* @__PURE__ */ new Set(["single-choice", "multi-choice", "dropdown"]);
|
|
629
1290
|
var ORDERING = /* @__PURE__ */ new Set(["lt", "lte", "gt", "gte"]);
|
|
630
1291
|
var OPERATORS = /* @__PURE__ */ new Set([
|
|
631
1292
|
"eq",
|
|
@@ -705,8 +1366,45 @@ function parseForm(input) {
|
|
|
705
1366
|
} else if (type === "text-highlights") {
|
|
706
1367
|
optionalText(props2.text, `${path}.text`);
|
|
707
1368
|
optionalInt(props2.maxHighlights, `${path}.maxHighlights`, 1);
|
|
1369
|
+
} else if (type === CALCULATED_TYPE) {
|
|
1370
|
+
if (props2.format !== void 0 && props2.format !== "number" && props2.format !== "percent" && props2.format !== "text") {
|
|
1371
|
+
issue(`${path}.format`, "Must be number, percent or text.");
|
|
1372
|
+
}
|
|
1373
|
+
if (props2.decimals !== void 0 && !(isInt(props2.decimals) && props2.decimals >= 0 && props2.decimals <= MAX_CALCULATED_DECIMALS)) {
|
|
1374
|
+
issue(`${path}.decimals`, `Must be a whole number from 0 to ${MAX_CALCULATED_DECIMALS}.`);
|
|
1375
|
+
}
|
|
708
1376
|
}
|
|
709
1377
|
};
|
|
1378
|
+
const isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v);
|
|
1379
|
+
const fieldProps = (type, props2, path) => {
|
|
1380
|
+
if (type === "rating" || type === "nps") {
|
|
1381
|
+
optionalText(props2.lowLabel, `${path}.lowLabel`);
|
|
1382
|
+
optionalText(props2.highLabel, `${path}.highLabel`);
|
|
1383
|
+
}
|
|
1384
|
+
if (type === "rating" && props2.display !== void 0 && props2.display !== "numbers" && props2.display !== "stars") {
|
|
1385
|
+
issue(`${path}.display`, "Must be numbers or stars.");
|
|
1386
|
+
}
|
|
1387
|
+
if (type === "number") {
|
|
1388
|
+
for (const k of ["min", "max", "step"]) {
|
|
1389
|
+
if (props2[k] !== void 0 && !isFiniteNumber(props2[k])) issue(`${path}.${k}`, "Must be a number.");
|
|
1390
|
+
}
|
|
1391
|
+
if (isFiniteNumber(props2.step) && props2.step <= 0) issue(`${path}.step`, "Must be above 0.");
|
|
1392
|
+
if (isFiniteNumber(props2.min) && isFiniteNumber(props2.max) && props2.min > props2.max) {
|
|
1393
|
+
issue(`${path}.min`, "Can't be more than the largest number.");
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
if (type === "date") {
|
|
1397
|
+
for (const k of ["min", "max"]) {
|
|
1398
|
+
if (props2[k] !== void 0 && !(typeof props2[k] === "string" && isIsoDate(props2[k]))) {
|
|
1399
|
+
issue(`${path}.${k}`, "Must be a date like 2026-10-22.");
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
if (typeof props2.min === "string" && typeof props2.max === "string" && isIsoDate(props2.min) && isIsoDate(props2.max) && props2.min > props2.max) {
|
|
1403
|
+
issue(`${path}.min`, "Can't be after the latest date.");
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
if (type === "consent") optionalText(props2.text, `${path}.text`);
|
|
1407
|
+
};
|
|
710
1408
|
if (!isObject2(input)) {
|
|
711
1409
|
issue("", "A form definition must be an object.");
|
|
712
1410
|
return fail();
|
|
@@ -740,7 +1438,9 @@ function parseForm(input) {
|
|
|
740
1438
|
const keys = /* @__PURE__ */ new Map();
|
|
741
1439
|
const fieldTypes = /* @__PURE__ */ new Map();
|
|
742
1440
|
const order = /* @__PURE__ */ new Map();
|
|
1441
|
+
const tableColumnKeys = /* @__PURE__ */ new Map();
|
|
743
1442
|
const choices = /* @__PURE__ */ new Map();
|
|
1443
|
+
const calculatedLiteral = /* @__PURE__ */ new Map();
|
|
744
1444
|
input.blocks.forEach((block, i) => {
|
|
745
1445
|
const path = `blocks[${i}]`;
|
|
746
1446
|
if (!isObject2(block) || typeof block.id !== "string" || !block.id) {
|
|
@@ -790,12 +1490,24 @@ function parseForm(input) {
|
|
|
790
1490
|
}
|
|
791
1491
|
if (typeof block.type === "string" && (block.props === void 0 || isObject2(block.props))) {
|
|
792
1492
|
structuredProps(block.type, block.props ?? {}, `${path}.props`);
|
|
1493
|
+
fieldProps(block.type, block.props ?? {}, `${path}.props`);
|
|
793
1494
|
}
|
|
794
1495
|
if (validKey) {
|
|
795
1496
|
if (keys.has(block.key)) issue(`${path}.key`, `Duplicate key "${String(block.key)}".`);
|
|
796
1497
|
keys.set(block.key, block.id);
|
|
797
1498
|
}
|
|
798
1499
|
fieldTypes.set(block.id, typeof block.type === "string" ? block.type : "");
|
|
1500
|
+
if (block.type === CALCULATED_TYPE) {
|
|
1501
|
+
const format = isObject2(block.props) ? block.props.format : void 0;
|
|
1502
|
+
if (format === "text") calculatedLiteral.set(block.id, "string");
|
|
1503
|
+
else if (format !== "number" && format !== "percent") calculatedLiteral.set(block.id, void 0);
|
|
1504
|
+
}
|
|
1505
|
+
if (block.type === "table" && isObject2(block.props) && Array.isArray(block.props.columns)) {
|
|
1506
|
+
tableColumnKeys.set(
|
|
1507
|
+
block.id,
|
|
1508
|
+
new Set(block.props.columns.flatMap((c) => isObject2(c) && typeof c.key === "string" ? [c.key] : []))
|
|
1509
|
+
);
|
|
1510
|
+
}
|
|
799
1511
|
} else if (block.kind === "content") {
|
|
800
1512
|
if (block.type !== "heading" && block.type !== "text") issue(`${path}.type`, "Must be heading or text.");
|
|
801
1513
|
text(block.text, `${path}.text`);
|
|
@@ -805,6 +1517,44 @@ function parseForm(input) {
|
|
|
805
1517
|
issue(`${path}.kind`, "Unknown block kind.");
|
|
806
1518
|
}
|
|
807
1519
|
});
|
|
1520
|
+
let formulaChars = 0;
|
|
1521
|
+
input.blocks.forEach((block, i) => {
|
|
1522
|
+
if (!isObject2(block) || block.kind !== "field" || block.type !== CALCULATED_TYPE) return;
|
|
1523
|
+
const path = `blocks[${i}].props.formula`;
|
|
1524
|
+
const source = isObject2(block.props) && typeof block.props.formula === "string" ? block.props.formula : "";
|
|
1525
|
+
formulaChars += source.length;
|
|
1526
|
+
if (formulaChars > MAX_FORM_FORMULA_LENGTH && formulaChars - source.length <= MAX_FORM_FORMULA_LENGTH) {
|
|
1527
|
+
issue(path, `The form's formulas together are over ${MAX_FORM_FORMULA_LENGTH} characters; shorten some, or work part out once in an earlier calculated field.`);
|
|
1528
|
+
}
|
|
1529
|
+
if (block.required === true) {
|
|
1530
|
+
warnings.push({ path: `blocks[${i}].required`, message: "A calculated field is worked out, not answered, so it is never required." });
|
|
1531
|
+
}
|
|
1532
|
+
const formula = isObject2(block.props) ? block.props.formula : void 0;
|
|
1533
|
+
if (typeof formula !== "string" || !formula.trim()) return issue(path, "A calculated field needs a formula.");
|
|
1534
|
+
const parsed = parseFormula(formula);
|
|
1535
|
+
if (!parsed.ok) return issue(path, `${parsed.message} (at character ${parsed.at + 1})`);
|
|
1536
|
+
const reported = /* @__PURE__ */ new Set();
|
|
1537
|
+
for (const ref of parsed.refs) {
|
|
1538
|
+
const name2 = ref.column === void 0 ? ref.key : `${ref.key}.${ref.column}`;
|
|
1539
|
+
if (reported.has(name2)) continue;
|
|
1540
|
+
reported.add(name2);
|
|
1541
|
+
const target = keys.get(ref.key);
|
|
1542
|
+
const targetType = target === void 0 ? void 0 : fieldTypes.get(target);
|
|
1543
|
+
const at = target === void 0 ? void 0 : order.get(target);
|
|
1544
|
+
if (target === void 0 || targetType === void 0) issue(path, `The formula uses "${ref.key}", which is not the answer name of a question in this form.`);
|
|
1545
|
+
else if (target === block.id) issue(path, "The formula uses this field's own value.");
|
|
1546
|
+
else if (targetType === CALCULATED_TYPE && (at ?? 0) > i) {
|
|
1547
|
+
issue(path, `The formula uses "${ref.key}", a calculated field that comes after this one; move it earlier.`);
|
|
1548
|
+
} else if (targetType === "table") {
|
|
1549
|
+
const columns = tableColumnKeys.get(target);
|
|
1550
|
+
if (ref.column === void 0) issue(path, `"${ref.key}" is a table: name one of its columns, like ${ref.key}.${[...columns ?? []][0] ?? "column"}.`);
|
|
1551
|
+
else if (columns && !columns.has(ref.column)) issue(path, `The table "${ref.key}" has no column "${ref.column}".`);
|
|
1552
|
+
} else if (ref.column !== void 0) issue(path, `"${ref.key}" is not a table, so it has no column "${ref.column}".`);
|
|
1553
|
+
else if (targetType === "media-notes" || targetType === "text-highlights") {
|
|
1554
|
+
warnings.push({ path, message: `"${ref.key}" holds notes, not numbers; the formula reads it as blank.` });
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
});
|
|
808
1558
|
const hiddenNames = /* @__PURE__ */ new Set();
|
|
809
1559
|
const hiddenTypes = /* @__PURE__ */ new Map();
|
|
810
1560
|
if (input.hidden !== void 0 && !Array.isArray(input.hidden)) issue("hidden", "Must be an array.");
|
|
@@ -888,8 +1638,8 @@ function parseForm(input) {
|
|
|
888
1638
|
if (typeof left.field === "string" && fieldTypes.has(left.field)) {
|
|
889
1639
|
const fieldType = fieldTypes.get(left.field);
|
|
890
1640
|
what = `"${keyOf(left.field)}"`;
|
|
891
|
-
type = LITERAL_TYPE[fieldType];
|
|
892
|
-
if (fieldType
|
|
1641
|
+
type = calculatedLiteral.has(left.field) ? calculatedLiteral.get(left.field) : LITERAL_TYPE[fieldType];
|
|
1642
|
+
if (CHOICE_TYPES.has(fieldType)) options = choices.get(left.field);
|
|
893
1643
|
} else if (typeof left.hidden === "string" && hiddenTypes.has(left.hidden)) {
|
|
894
1644
|
what = `hidden input "${left.hidden}"`;
|
|
895
1645
|
type = hiddenTypes.get(left.hidden);
|
|
@@ -1035,11 +1785,33 @@ var f = {
|
|
|
1035
1785
|
longText: (key, o) => field("long-text", key, o, o.maxLength ? { maxLength: o.maxLength } : void 0),
|
|
1036
1786
|
email: (key, o) => field("email", key, o),
|
|
1037
1787
|
phone: (key, o) => field("phone", key, o),
|
|
1038
|
-
|
|
1039
|
-
|
|
1788
|
+
/**
|
|
1789
|
+
* A 1-to-`max` scale. `lowLabel` and `highLabel` are optional words under
|
|
1790
|
+
* its ends ("Poor", "Great"); `display: "stars"` draws stars instead of numbers.
|
|
1791
|
+
*/
|
|
1792
|
+
rating: (key, o) => field(
|
|
1793
|
+
"rating",
|
|
1794
|
+
key,
|
|
1795
|
+
o,
|
|
1796
|
+
props({ max: o.max ?? 5, lowLabel: o.lowLabel || void 0, highLabel: o.highLabel || void 0, display: o.display })
|
|
1797
|
+
),
|
|
1798
|
+
/** A 0-to-10 Net Promoter Score. The end labels default to "Not likely" and "Very likely" in the renderer. */
|
|
1799
|
+
nps: (key, o) => field("nps", key, o, props({ lowLabel: o.lowLabel || void 0, highLabel: o.highLabel || void 0 })),
|
|
1040
1800
|
singleChoice: (key, o) => field("single-choice", key, o, choiceProps(o.options)),
|
|
1041
1801
|
multiChoice: (key, o) => field("multi-choice", key, o, choiceProps(o.options)),
|
|
1042
1802
|
yesNo: (key, o) => field("yes-no", key, o),
|
|
1803
|
+
/** One option from a compact menu: for a long list (a country, a class), where single choice would be a wall of buttons. */
|
|
1804
|
+
dropdown: (key, o) => field("dropdown", key, o, choiceProps(o.options)),
|
|
1805
|
+
/** A number, optionally between `min` and `max` and on a `step` (from `min`, else 0): `step: 1` for whole numbers. */
|
|
1806
|
+
number: (key, o) => field("number", key, o, props({ min: o.min, max: o.max, step: o.step })),
|
|
1807
|
+
/** A calendar day, stored as `YYYY-MM-DD`, optionally between `min` and `max` (also `YYYY-MM-DD`). */
|
|
1808
|
+
date: (key, o) => field("date", key, o, props({ min: o.min, max: o.max })),
|
|
1809
|
+
/**
|
|
1810
|
+
* A single checkbox to agree to something. `text` is the checkbox's own
|
|
1811
|
+
* words ("I agree to the terms"); the renderer defaults to "I agree".
|
|
1812
|
+
* Checked stores `true`; unchecked is unanswered, so `required` means it must be checked.
|
|
1813
|
+
*/
|
|
1814
|
+
consent: (key, o) => field("consent", key, o, props({ text: o.text || void 0 })),
|
|
1043
1815
|
/** Several short answers, one per line: goals, action items, three things that went well. */
|
|
1044
1816
|
list: (key, o) => field(
|
|
1045
1817
|
"list",
|
|
@@ -1047,6 +1819,12 @@ var f = {
|
|
|
1047
1819
|
o,
|
|
1048
1820
|
props({ min: o.min, max: o.max, itemMaxLength: o.itemMaxLength, placeholder: o.itemPlaceholder })
|
|
1049
1821
|
),
|
|
1822
|
+
/**
|
|
1823
|
+
* A value worked out from other answers and shown read-only, such as a
|
|
1824
|
+
* total or a score: `formula` names answers by key (`hours * rate`,
|
|
1825
|
+
* `sum(plan.cost)`). Stored with the answers; never required.
|
|
1826
|
+
*/
|
|
1827
|
+
calculated: (key, o) => field("calculated", key, o, props({ formula: o.formula, format: o.format, decimals: o.decimals })),
|
|
1050
1828
|
/**
|
|
1051
1829
|
* A small table each answer fills row by row, one answer per column: an
|
|
1052
1830
|
* action plan (What / Who / By when), pros and cons.
|
|
@@ -1106,9 +1884,9 @@ function effects(fromKey, condition) {
|
|
|
1106
1884
|
})
|
|
1107
1885
|
};
|
|
1108
1886
|
}
|
|
1109
|
-
var
|
|
1887
|
+
var compare2 = (key, op, value) => (r) => value === void 0 ? { op, left: { field: r(key) } } : { op, left: { field: r(key) }, right: { value } };
|
|
1110
1888
|
function when(key) {
|
|
1111
|
-
const on = (op, value) => effects(key,
|
|
1889
|
+
const on = (op, value) => effects(key, compare2(key, op, value));
|
|
1112
1890
|
return {
|
|
1113
1891
|
is: (value) => on("eq", value),
|
|
1114
1892
|
isNot: (value) => on("neq", value),
|
|
@@ -1236,7 +2014,7 @@ function runCustom(validator, value) {
|
|
|
1236
2014
|
}
|
|
1237
2015
|
function validateField(field2, value, options = {}) {
|
|
1238
2016
|
if (isEmptyValue(value, field2)) {
|
|
1239
|
-
return field2.required && options.requireAnswers !== false ? REQUIRED_MESSAGE : null;
|
|
2017
|
+
return field2.required && field2.type !== CALCULATED_TYPE && options.requireAnswers !== false ? REQUIRED_MESSAGE : null;
|
|
1240
2018
|
}
|
|
1241
2019
|
const manifest = getFieldType(field2.type);
|
|
1242
2020
|
if (!manifest) return `Unknown field type "${field2.type}".`;
|
|
@@ -1267,9 +2045,21 @@ function build(definition, options, replaying = false) {
|
|
|
1267
2045
|
if (!declared.has(name)) initialHidden[name] = value;
|
|
1268
2046
|
}
|
|
1269
2047
|
Object.assign(initialHidden, coerceHidden(definition, options.hidden).values);
|
|
1270
|
-
const
|
|
2048
|
+
const calc = calculator(definition);
|
|
2049
|
+
const settle = (values, hidden) => {
|
|
2050
|
+
let { path } = computePath(definition, scopeOf(values, hidden));
|
|
2051
|
+
if (!calc.active) return { values, path };
|
|
2052
|
+
for (let round2 = 0; round2 < 4; round2++) {
|
|
2053
|
+
const next = calc.withCalculated(values, path);
|
|
2054
|
+
if (next === values) break;
|
|
2055
|
+
values = next;
|
|
2056
|
+
path = computePath(definition, scopeOf(values, hidden)).path;
|
|
2057
|
+
}
|
|
2058
|
+
return { values, path };
|
|
2059
|
+
};
|
|
2060
|
+
const first = settle({}, initialHidden);
|
|
1271
2061
|
let state = {
|
|
1272
|
-
values:
|
|
2062
|
+
values: first.values,
|
|
1273
2063
|
hidden: initialHidden,
|
|
1274
2064
|
path: first.path,
|
|
1275
2065
|
current: first.path[0] ?? null,
|
|
@@ -1304,12 +2094,25 @@ function build(definition, options, replaying = false) {
|
|
|
1304
2094
|
}
|
|
1305
2095
|
return errors;
|
|
1306
2096
|
};
|
|
2097
|
+
let unsettled = false;
|
|
2098
|
+
const settleNow = () => {
|
|
2099
|
+
if (!unsettled) return;
|
|
2100
|
+
unsettled = false;
|
|
2101
|
+
const { values, path } = settle(state.values, state.hidden);
|
|
2102
|
+
state = { ...state, values, path };
|
|
2103
|
+
};
|
|
1307
2104
|
const answer = (id, value, event) => {
|
|
1308
|
-
if (state.status === "completed" || own(state.values, id) === value) return;
|
|
1309
|
-
const values = { ...state.values, [id]: value };
|
|
1310
|
-
const { path } = computePath(definition, scopeOf(values, state.hidden));
|
|
2105
|
+
if (state.status === "completed" || own(state.values, id) === value || isCalculated(fields.get(id))) return;
|
|
1311
2106
|
const errors = { ...state.errors };
|
|
1312
2107
|
delete errors[id];
|
|
2108
|
+
if (batch) {
|
|
2109
|
+
state.values = { ...state.values, [id]: value };
|
|
2110
|
+
state.errors = errors;
|
|
2111
|
+
log(event);
|
|
2112
|
+
unsettled = true;
|
|
2113
|
+
return;
|
|
2114
|
+
}
|
|
2115
|
+
const { values, path } = settle({ ...state.values, [id]: value }, state.hidden);
|
|
1313
2116
|
emit({ ...state, values, path, errors, events: log(event) });
|
|
1314
2117
|
};
|
|
1315
2118
|
const engine = {
|
|
@@ -1381,10 +2184,14 @@ function build(definition, options, replaying = false) {
|
|
|
1381
2184
|
}
|
|
1382
2185
|
};
|
|
1383
2186
|
if (options.initialValues) {
|
|
2187
|
+
const wasBatch = batch;
|
|
2188
|
+
batch = true;
|
|
1384
2189
|
for (const [id, value] of Object.entries(options.initialValues)) {
|
|
1385
2190
|
if (!fields.has(id) || value === void 0) continue;
|
|
1386
2191
|
answer(id, value, stamp({ type: "answer", field: id, value, source: "prefill" }));
|
|
1387
2192
|
}
|
|
2193
|
+
settleNow();
|
|
2194
|
+
batch = wasBatch;
|
|
1388
2195
|
}
|
|
1389
2196
|
const apply = (event) => {
|
|
1390
2197
|
if (event.type === "answer") {
|
|
@@ -1392,11 +2199,19 @@ function build(definition, options, replaying = false) {
|
|
|
1392
2199
|
const { at: _at, ...logged } = event;
|
|
1393
2200
|
answer(event.field, event.value, logged);
|
|
1394
2201
|
}
|
|
1395
|
-
} else if (event.type === "next")
|
|
1396
|
-
|
|
1397
|
-
|
|
2202
|
+
} else if (event.type === "next") {
|
|
2203
|
+
settleNow();
|
|
2204
|
+
engine.next();
|
|
2205
|
+
} else if (event.type === "back") {
|
|
2206
|
+
settleNow();
|
|
2207
|
+
engine.back();
|
|
2208
|
+
} else if (event.type === "submit") {
|
|
2209
|
+
settleNow();
|
|
2210
|
+
engine.submit();
|
|
2211
|
+
}
|
|
1398
2212
|
};
|
|
1399
2213
|
const finish = () => {
|
|
2214
|
+
settleNow();
|
|
1400
2215
|
batch = false;
|
|
1401
2216
|
state = { ...state, events: [...state.events] };
|
|
1402
2217
|
};
|
|
@@ -1545,6 +2360,6 @@ function describeCondition(condition, def, fields = fieldMap(def)) {
|
|
|
1545
2360
|
return `${left} ${op} ${right}`;
|
|
1546
2361
|
}
|
|
1547
2362
|
|
|
1548
|
-
export { HIGHLIGHT_NOTE_MESSAGE, MAX_HIDDEN_STRING_LENGTH, MAX_HIGHLIGHT_NOTE_LENGTH, MAX_HIGHLIGHT_QUOTE_LENGTH, MAX_TABLE_CELL_LENGTH, MAX_TABLE_COLUMNS, MAX_TIMESTAMP_SECONDS, REQUIRED_MESSAGE, STRUCTURED_FIELD_TYPES, canonicalJson, choiceOptions, coerceHidden, coerceHiddenValue, computePath, createForm, defineForm, describeCondition, evaluate, explain, f, fingerprint, formatTimestamp, getFieldType, isEmptyValue, isFormEvent, isJson, isSensitive, listFieldTypes, listLimits, normalizeValue, parseForm, parseTimestamp, recall, registerFieldType, replay, ruleVisible, steps, summarizeValue, tableColumns, tableLimits, validateField, when };
|
|
2363
|
+
export { CALCULATED_TYPE, COMPUTED_FIELD_TYPES, FORMULA_FUNCTIONS, HIGHLIGHT_NOTE_MESSAGE, MAX_CALCULATED_DECIMALS, MAX_FORMULA_ITEMS, MAX_FORMULA_LENGTH, MAX_FORM_FORMULA_LENGTH, MAX_HIDDEN_STRING_LENGTH, MAX_HIGHLIGHT_NOTE_LENGTH, MAX_HIGHLIGHT_QUOTE_LENGTH, MAX_SETTLE_ITEMS, MAX_TABLE_CELL_LENGTH, MAX_TABLE_COLUMNS, MAX_TIMESTAMP_SECONDS, REQUIRED_MESSAGE, STRUCTURED_FIELD_TYPES, calculatedProps, calculatedValue, canonicalJson, choiceOptions, coerceHidden, coerceHiddenValue, computePath, createForm, dateLimits, defineForm, describeCondition, evaluate, evaluateFormula, explain, f, fingerprint, formatCalculated, formatTimestamp, formulaInput, formulaNumber, formulaRefs, getFieldType, isEmptyValue, isFormEvent, isIsoDate, isJson, isSensitive, listFieldTypes, listLimits, normalizeValue, numberLimits, parseForm, parseFormula, parseTimestamp, ratingDisplay, recall, registerFieldType, renameFormulaKey, replay, ruleVisible, scaleLabels, steps, summarizeValue, tableColumns, tableLimits, validateField, when };
|
|
1549
2364
|
//# sourceMappingURL=index.js.map
|
|
1550
2365
|
//# sourceMappingURL=index.js.map
|