@niscorp/prism 0.2.2 → 0.3.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.
Files changed (45) hide show
  1. package/CHANGELOG.md +187 -0
  2. package/DESIGN.md +9 -8
  3. package/DOCS.md +68 -25
  4. package/README.md +35 -22
  5. package/dist/agent.cjs +4 -4
  6. package/dist/agent.js +2 -2
  7. package/dist/{chunk-26VYDHHC.cjs → chunk-66YSI4PX.cjs} +268 -97
  8. package/dist/chunk-66YSI4PX.cjs.map +1 -0
  9. package/dist/{chunk-O3OJAQWA.js → chunk-7VMFSXBM.js} +262 -98
  10. package/dist/chunk-7VMFSXBM.js.map +1 -0
  11. package/dist/{chunk-XRK55NPE.js → chunk-BKXCULZV.js} +5 -3
  12. package/dist/chunk-BKXCULZV.js.map +1 -0
  13. package/dist/{chunk-W32JXP33.cjs → chunk-OLZQK2ZF.cjs} +7 -5
  14. package/dist/chunk-OLZQK2ZF.cjs.map +1 -0
  15. package/dist/examples/index.cjs +25 -2
  16. package/dist/examples/index.cjs.map +1 -1
  17. package/dist/examples/index.d.cts +1 -1
  18. package/dist/examples/index.d.ts +1 -1
  19. package/dist/examples/index.js +25 -2
  20. package/dist/examples/index.js.map +1 -1
  21. package/dist/index.cjs +1224 -137
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +9 -6
  24. package/dist/index.d.ts +9 -6
  25. package/dist/index.js +1120 -26
  26. package/dist/index.js.map +1 -1
  27. package/dist/migrations/index.cjs +15 -7
  28. package/dist/migrations/index.cjs.map +1 -1
  29. package/dist/migrations/index.d.cts +0 -2
  30. package/dist/migrations/index.d.ts +0 -2
  31. package/dist/migrations/index.js +14 -2
  32. package/dist/migrations/index.js.map +1 -1
  33. package/dist/{profiles-C6r-x-Vj.d.cts → profiles-CPVfysxC.d.cts} +2 -1
  34. package/dist/{profiles-C6r-x-Vj.d.ts → profiles-CPVfysxC.d.ts} +2 -1
  35. package/package.json +4 -4
  36. package/dist/chunk-26VYDHHC.cjs.map +0 -1
  37. package/dist/chunk-O3OJAQWA.js.map +0 -1
  38. package/dist/chunk-V426VIRI.cjs +0 -1168
  39. package/dist/chunk-V426VIRI.cjs.map +0 -1
  40. package/dist/chunk-VC4PRB4H.js +0 -1086
  41. package/dist/chunk-VC4PRB4H.js.map +0 -1
  42. package/dist/chunk-W32JXP33.cjs.map +0 -1
  43. package/dist/chunk-XRK55NPE.js.map +0 -1
  44. package/dist/transform-DcVcOBzQ.d.cts +0 -3
  45. package/dist/transform-DcVcOBzQ.d.ts +0 -3
package/dist/index.js CHANGED
@@ -1,16 +1,930 @@
1
- export { MAPPING_OPS, getConfigJsonSchema, getNodeJsonSchema, getProfileJsonSchema } from './chunk-XRK55NPE.js';
2
- import { PrismError, ErrorCode, explainIssues, desugar, primeJsonPathCache, createBudget, evaluateNode, measure, parseJsonPath, opConst, opRef, opVar, opGet, opWith, opMap, opFilter, opReduce, opSlice, opFlatten, opUnique, opSortBy, opAdd, opSub, opMul, opDiv, opRound, opJoin, opToString, opInterpolate, opFill, opTrim, opLower, opUpper, opSplit, opReplace, opEq, opNeq, opGt, opGte, opLt, opLte, opEmpty, opStartsWith, opEndsWith, opContains, opNot, opAnd, opOr, opMerge, opCoalesce, opCase, opEntriesOf, opKeyBy, opGroupBy, opKeys, opValues, opFromEntries, opPick, opOmit, opType, opLength, opHas, opRenameKeys, opUpdate, opAssert, opWalk, opDate, opDateAdd, opDateDiff, opLocaleDate, opLocaleMoney, opLocaleNumber } from './chunk-VC4PRB4H.js';
3
- export { DEFAULT_LIMITS, ErrorCode, PrismError, evaluate, evaluateSafe, prismTransform } from './chunk-VC4PRB4H.js';
4
- import { ConfigSchema, isJsonObject, isConstNode, isRefNode, isVarNode, isGetNode, isWithNode, isMapNode, isFilterNode, isReduceNode, isSliceNode, isFlattenNode, isUniqueNode, isSortByNode, isAddNode, isSubNode, isMulNode, isDivNode, isRoundNode, isJoinNode, isToStringNode, isInterpolateNode, isFillNode, isTrimNode, isLowerNode, isUpperNode, isSplitNode, isReplaceNode, isEqNode, isNeqNode, isGtNode, isGteNode, isLtNode, isLteNode, isEmptyNode, isStartsWithNode, isEndsWithNode, isContainsNode, isNotNode, isAndNode, isOrNode, isMergeNode, isCoalesceNode, isCaseNode, isEntriesOfNode, isKeyByNode, isGroupByNode, isKeysNode, isValuesNode, isFromEntriesNode, isPickNode, isOmitNode, isTypeNode, isLengthNode, isHasNode, isRenameKeysNode, isUpdateNode, isAssertNode, isWalkNode, isDateNode, isDateAddNode, isDateDiffNode, isLocaleDateNode, isLocaleMoneyNode, isLocaleNumberNode } from './chunk-O3OJAQWA.js';
5
- export { ConfigSchema, NodeSchema, OP_KEYS } from './chunk-O3OJAQWA.js';
1
+ export { MAPPING_OPS, getConfigJsonSchema, getNodeJsonSchema, getProfileJsonSchema } from './chunk-BKXCULZV.js';
2
+ import { PrismError, ErrorCode, ConfigSchema, isWithNode, isRenameKeysNode, isConstNode, isSumNode, isAvgNode, isCountNode, isMinNode, isMaxNode, isPluckNode, isTakeNode, isDropNode, isMatchNode, isFlatMapNode, isJsonObject, isRefNode, parseJsonPath, isVarNode, isPlainObject, OPTIONAL_FIELDS_KEY, isGetNode, isMapNode, isFilterNode, isReduceNode, isSliceNode, isFlattenNode, isUniqueNode, isSortByNode, isAddNode, isSubNode, isMulNode, isDivNode, isRoundNode, isModNode, isToNumberNode, isJoinNode, isToStringNode, isInterpolateNode, isFillNode, isTrimNode, isLowerNode, isUpperNode, isSplitNode, isReplaceNode, isEqNode, isNeqNode, isGtNode, isGteNode, isLtNode, isLteNode, isEmptyNode, isStartsWithNode, isEndsWithNode, isContainsNode, isNotNode, isAndNode, isOrNode, isMergeNode, isCoalesceNode, isCaseNode, isEntriesOfNode, isKeyByNode, isGroupByNode, isKeysNode, isValuesNode, isFromEntriesNode, isPickNode, isOmitNode, isTypeNode, isLengthNode, isHasNode, isUpdateNode, isAssertNode, isWalkNode, isDateNode, isDateAddNode, isDateDiffNode, isLocaleDateNode, isLocaleMoneyNode, isLocaleNumberNode, parseJsonPathCached, getByPath, isJsonArray } from './chunk-7VMFSXBM.js';
3
+ export { ConfigSchema, ErrorCode, NodeSchema, OP_KEYS, PrismError } from './chunk-7VMFSXBM.js';
6
4
  import { exceedsDepth, depthRefusal } from '@niscorp/strata';
5
+ import dayjs from 'dayjs';
6
+ import utc from 'dayjs/plugin/utc.js';
7
7
 
8
- // src/engine/optimize.ts
9
- var HANDLER_KEY = "__op";
8
+ // src/utils/issues.ts
9
+ var segmentsOf = (path) => path.map((p) => typeof p === "number" ? p : String(p));
10
+ var explainOne = (issue, prefix) => {
11
+ const here = [...prefix, ...segmentsOf(issue.path)];
12
+ if (issue.code === "invalid_key") return [{ path: here, message: issue.issues[0]?.message ?? issue.message }];
13
+ if (issue.code !== "invalid_union" || issue.errors.length === 0) return [{ path: here, message: issue.message }];
14
+ let best = [];
15
+ let bestDepth = -1;
16
+ for (const branch of issue.errors) {
17
+ const explained = branch.flatMap((i) => explainOne(i, here));
18
+ const depth = Math.max(...explained.map((e) => e.path.length));
19
+ if (depth > bestDepth || depth === bestDepth && explained.length < best.length) {
20
+ best = explained;
21
+ bestDepth = depth;
22
+ }
23
+ }
24
+ return bestDepth <= here.length ? [{ path: here, message: "Not a Prism node: no op matches, and it is not a plain value." }] : best;
25
+ };
26
+ var explainIssues = (issues) => issues.flatMap((i) => explainOne(i, []));
27
+
28
+ // src/sugar/rewriters.ts
29
+ var rewriteSum = (node, recurse) => ({
30
+ $reduce: {
31
+ over: recurse(node.$sum.over),
32
+ as: "__x",
33
+ acc: "__acc",
34
+ init: { $const: 0 },
35
+ body: { $add: [{ $var: "__acc" }, { $var: "__x" }] }
36
+ }
37
+ });
38
+ var rewriteCount = (node, recurse) => ({
39
+ $reduce: {
40
+ over: recurse(node.$count.over),
41
+ as: "__x",
42
+ acc: "__acc",
43
+ init: { $const: 0 },
44
+ body: { $add: [{ $var: "__acc" }, { $const: 1 }] }
45
+ }
46
+ });
47
+ var rewriteAvg = (node, recurse) => {
48
+ const over = recurse(node.$avg.over);
49
+ return {
50
+ $div: [
51
+ {
52
+ $reduce: {
53
+ over,
54
+ as: "__x",
55
+ acc: "__acc",
56
+ init: { $const: 0 },
57
+ body: { $add: [{ $var: "__acc" }, { $var: "__x" }] }
58
+ }
59
+ },
60
+ {
61
+ $reduce: {
62
+ over,
63
+ as: "__x",
64
+ acc: "__acc",
65
+ init: { $const: 0 },
66
+ body: { $add: [{ $var: "__acc" }, { $const: 1 }] }
67
+ }
68
+ }
69
+ ]
70
+ };
71
+ };
72
+ var rewriteMin = (node, recurse) => ({
73
+ $reduce: {
74
+ over: recurse(node.$min.over),
75
+ as: "__x",
76
+ acc: "__acc",
77
+ init: { $const: null },
78
+ body: {
79
+ $case: {
80
+ branches: [
81
+ { when: { $eq: [{ $var: "__acc" }, null] }, then: { $var: "__x" } },
82
+ { when: { $lt: [{ $var: "__x" }, { $var: "__acc" }] }, then: { $var: "__x" } }
83
+ ],
84
+ else: { $var: "__acc" }
85
+ }
86
+ }
87
+ }
88
+ });
89
+ var rewriteMax = (node, recurse) => ({
90
+ $reduce: {
91
+ over: recurse(node.$max.over),
92
+ as: "__x",
93
+ acc: "__acc",
94
+ init: { $const: null },
95
+ body: {
96
+ $case: {
97
+ branches: [
98
+ { when: { $eq: [{ $var: "__acc" }, null] }, then: { $var: "__x" } },
99
+ { when: { $gt: [{ $var: "__x" }, { $var: "__acc" }] }, then: { $var: "__x" } }
100
+ ],
101
+ else: { $var: "__acc" }
102
+ }
103
+ }
104
+ }
105
+ });
106
+ var rewritePluck = (node, recurse) => ({
107
+ $map: {
108
+ over: recurse(node.$pluck.over),
109
+ as: "__item",
110
+ body: { $get: { from: { $var: "__item" }, path: [node.$pluck.key] } }
111
+ }
112
+ });
113
+ var rewriteTake = (node, recurse) => ({
114
+ $slice: {
115
+ from: recurse(node.$take.from),
116
+ start: 0,
117
+ end: node.$take.count
118
+ }
119
+ });
120
+ var rewriteDrop = (node, recurse) => ({
121
+ $slice: {
122
+ from: recurse(node.$drop.from),
123
+ start: node.$drop.count
124
+ }
125
+ });
126
+ var rewriteMatch = (node, recurse) => ({
127
+ $filter: {
128
+ over: recurse(node.$match.over),
129
+ as: node.$match.as,
130
+ when: {
131
+ $contains: {
132
+ value: { $var: node.$match.as },
133
+ search: recurse(node.$match.search)
134
+ }
135
+ }
136
+ }
137
+ });
138
+ var rewriteFlatMap = (node, recurse) => ({
139
+ $flatten: {
140
+ $map: {
141
+ over: recurse(node.$flatMap.over),
142
+ as: node.$flatMap.as,
143
+ body: recurse(node.$flatMap.body)
144
+ }
145
+ }
146
+ });
147
+
148
+ // src/sugar/desugar.ts
149
+ var desugar = (node) => {
150
+ if (node === null || node === void 0) return node;
151
+ if (typeof node !== "object") return node;
152
+ if (Array.isArray(node)) return node.map(desugar);
153
+ if (isWithNode(node)) {
154
+ const bindings = {};
155
+ for (const [name, expr] of Object.entries(node.$with.let)) bindings[name] = desugar(expr);
156
+ return { $with: { let: bindings, value: desugar(node.$with.value) } };
157
+ }
158
+ if (isRenameKeysNode(node)) return { $renameKeys: { ...node.$renameKeys, from: desugar(node.$renameKeys.from) } };
159
+ if (isConstNode(node)) return node;
160
+ if (isSumNode(node)) return rewriteSum(node, desugar);
161
+ if (isAvgNode(node)) return rewriteAvg(node, desugar);
162
+ if (isCountNode(node)) return rewriteCount(node, desugar);
163
+ if (isMinNode(node)) return rewriteMin(node, desugar);
164
+ if (isMaxNode(node)) return rewriteMax(node, desugar);
165
+ if (isPluckNode(node)) return rewritePluck(node, desugar);
166
+ if (isTakeNode(node)) return rewriteTake(node, desugar);
167
+ if (isDropNode(node)) return rewriteDrop(node, desugar);
168
+ if (isMatchNode(node)) return rewriteMatch(node, desugar);
169
+ if (isFlatMapNode(node)) return rewriteFlatMap(node, desugar);
170
+ if (isJsonObject(node)) {
171
+ const result = {};
172
+ for (const [key, value] of Object.entries(node)) {
173
+ result[key] = desugar(value);
174
+ }
175
+ return result;
176
+ }
177
+ return node;
178
+ };
179
+
180
+ // src/engine/budget.ts
181
+ var DEFAULT_LIMITS = { maxSteps: 1e6, maxStringLength: 1e6, maxValues: 1e6 };
182
+ var createBudget = (limits) => ({ limits: { ...DEFAULT_LIMITS, ...limits }, steps: 0, sizes: /* @__PURE__ */ new WeakMap() });
183
+ var refuse = (what, limit) => {
184
+ throw new PrismError(`Evaluation stopped: ${what} (limit ${limit})`, ErrorCode.BUDGET, { details: { limit } });
185
+ };
186
+ var spendStep = (budget) => {
187
+ budget.steps += 1;
188
+ if (budget.steps > budget.limits.maxSteps) refuse("it evaluated too many nodes", budget.limits.maxSteps);
189
+ };
190
+ var sizeOf = (value, budget) => {
191
+ if (value === null || typeof value !== "object") return 1;
192
+ const known = budget.sizes.get(value);
193
+ if (known !== void 0) return known;
194
+ let size = 1;
195
+ for (const inner of Array.isArray(value) ? value : Object.values(value)) {
196
+ size += sizeOf(inner, budget);
197
+ if (size > budget.limits.maxValues) break;
198
+ }
199
+ budget.sizes.set(value, size);
200
+ return size;
201
+ };
202
+ var measureString = (value, budget) => {
203
+ if (typeof value === "string" && value.length > budget.limits.maxStringLength) refuse(`a string of ${value.length} characters`, budget.limits.maxStringLength);
204
+ };
205
+ var measure = (value, budget) => {
206
+ if (budget === void 0) return;
207
+ measureString(value, budget);
208
+ if (value !== null && typeof value === "object" && sizeOf(value, budget) > budget.limits.maxValues) {
209
+ refuse("a result holding too many values", budget.limits.maxValues);
210
+ }
211
+ };
212
+
213
+ // src/ops/core.ops.ts
10
214
  var SEGMENTS_KEY = "__segments";
11
- var eraseOp = (op) => (node, context, evaluate2) => {
12
- return op.call(void 0, node, context, evaluate2);
215
+ var isSegmentsArray = (value) => Array.isArray(value);
216
+ var opRef = (node, context, _evaluate) => {
217
+ const attached = Reflect.get(node, SEGMENTS_KEY);
218
+ const segments = isSegmentsArray(attached) ? attached : parseJsonPathCached(node.$ref);
219
+ const resolved = getByPath(context.source, segments);
220
+ if (resolved === void 0)
221
+ throw new PrismError("Path not found", ErrorCode.MISSING_PATH, { op: "$ref", path: node.$ref });
222
+ return resolved;
223
+ };
224
+ var copyOf = (value) => {
225
+ if (value === null || typeof value !== "object") return value;
226
+ if (Array.isArray(value)) return value.map(copyOf);
227
+ const copy = {};
228
+ for (const [key, inner] of Object.entries(value)) copy[key] = copyOf(inner);
229
+ return copy;
230
+ };
231
+ var opConst = (node, context, _evaluate) => context.kept === true ? copyOf(node.$const) : node.$const;
232
+ var opVar = (node, context, _evaluate) => {
233
+ const value = context.vars[node.$var];
234
+ if (value === void 0)
235
+ throw new PrismError(`Variable not found: ${node.$var}`, ErrorCode.VAR_NOT_FOUND, { op: "$var", path: node.$var });
236
+ return value;
237
+ };
238
+ var opGet = (node, context, evaluate2) => {
239
+ const { from, path, fallback } = node.$get;
240
+ let current2 = evaluate2(from, context);
241
+ for (const segment of path) {
242
+ const evaluated = typeof segment === "object" && segment !== null ? evaluate2(segment, context) : segment;
243
+ if (typeof evaluated === "number") {
244
+ if (!isJsonArray(current2)) {
245
+ if (fallback !== void 0) return evaluate2(fallback, context);
246
+ throw new PrismError("Expected array for index access", ErrorCode.TYPE, { op: "$get" });
247
+ }
248
+ current2 = current2[evaluated];
249
+ } else {
250
+ const key = String(evaluated);
251
+ if (!isJsonObject(current2)) {
252
+ if (fallback !== void 0) return evaluate2(fallback, context);
253
+ throw new PrismError("Expected object for key access", ErrorCode.TYPE, { op: "$get" });
254
+ }
255
+ current2 = current2[key];
256
+ }
257
+ }
258
+ if (current2 === void 0) {
259
+ if (fallback !== void 0) return evaluate2(fallback, context);
260
+ throw new PrismError("Path not found", ErrorCode.MISSING_PATH, { op: "$get" });
261
+ }
262
+ return current2;
263
+ };
264
+ var opWith = (node, context, evaluate2) => {
265
+ const { let: declarations, value } = node.$with;
266
+ const extendedVars = { ...context.vars };
267
+ for (const [name, expr] of Object.entries(declarations)) {
268
+ extendedVars[name] = evaluate2(expr, context);
269
+ measure(extendedVars[name] ?? null, context.budget);
270
+ }
271
+ return evaluate2(value, { ...context, vars: extendedVars });
272
+ };
273
+
274
+ // src/utils/compare.ts
275
+ var jsonEqual = (a, b) => {
276
+ if (a === b) return true;
277
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
278
+ return JSON.stringify(a) === JSON.stringify(b);
279
+ };
280
+ var compare = (a, b) => {
281
+ if (typeof a === "number" && typeof b === "number") return a - b;
282
+ if (typeof a === "string" && typeof b === "string") return a < b ? -1 : a > b ? 1 : 0;
283
+ return void 0;
284
+ };
285
+
286
+ // src/ops/scope.ts
287
+ var loopScope = (context) => {
288
+ const vars = { ...context.vars };
289
+ return { scope: { ...context, vars }, vars };
290
+ };
291
+
292
+ // src/ops/array.ops.ts
293
+ var requireArray = (value, op) => {
294
+ if (!isJsonArray(value))
295
+ throw new PrismError(`Expected array for ${op}`, ErrorCode.TYPE, { op });
296
+ return value;
297
+ };
298
+ var opMap = (node, context, evaluate2) => {
299
+ const { over, as, body } = node.$map;
300
+ const input = requireArray(evaluate2(over, context), "$map.over");
301
+ const result = [];
302
+ const { scope, vars } = loopScope(context);
303
+ for (const item of input) {
304
+ vars[as] = item;
305
+ result.push(evaluate2(body, scope));
306
+ }
307
+ return result;
308
+ };
309
+ var opFilter = (node, context, evaluate2) => {
310
+ const { over, as, when } = node.$filter;
311
+ const input = requireArray(evaluate2(over, context), "$filter.over");
312
+ const result = [];
313
+ const { scope, vars } = loopScope(context);
314
+ for (const item of input) {
315
+ vars[as] = item;
316
+ const condition = evaluate2(when, scope);
317
+ if (condition) result.push(item);
318
+ }
319
+ return result;
320
+ };
321
+ var opReduce = (node, context, evaluate2) => {
322
+ const { over, as, acc: accName = "acc", init, body } = node.$reduce;
323
+ const input = requireArray(evaluate2(over, context), "$reduce.over");
324
+ let accumulator = evaluate2(init, context);
325
+ const { scope, vars } = loopScope(context);
326
+ for (const item of input) {
327
+ vars[as] = item;
328
+ vars[accName] = accumulator;
329
+ accumulator = evaluate2(body, scope);
330
+ measure(accumulator, context.budget);
331
+ }
332
+ return accumulator;
333
+ };
334
+ var opSlice = (node, context, evaluate2) => {
335
+ const { from, start, end } = node.$slice;
336
+ const input = evaluate2(from, context);
337
+ if (typeof input === "string") return input.slice(start, end);
338
+ if (isJsonArray(input)) return input.slice(start, end);
339
+ throw new PrismError("Expected array or string for $slice", ErrorCode.TYPE, { op: "$slice" });
340
+ };
341
+ var opFlatten = (node, context, evaluate2) => {
342
+ const input = requireArray(evaluate2(node.$flatten, context), "$flatten");
343
+ const result = [];
344
+ for (const item of input) {
345
+ if (isJsonArray(item)) result.push(...item);
346
+ else result.push(item);
347
+ }
348
+ return result;
349
+ };
350
+ var opUnique = (node, context, evaluate2) => {
351
+ const input = requireArray(evaluate2(node.$unique, context), "$unique");
352
+ const seen = /* @__PURE__ */ new Set();
353
+ const result = [];
354
+ for (const item of input) {
355
+ const key = JSON.stringify(item);
356
+ if (!seen.has(key)) {
357
+ seen.add(key);
358
+ result.push(item);
359
+ }
360
+ }
361
+ return result;
362
+ };
363
+ var sortKey = (key) => {
364
+ if (key !== null && typeof key === "object") {
365
+ throw new PrismError(
366
+ `$sortBy.by answered ${Array.isArray(key) ? "a list" : "an object"}; a sort key is a string or a number. To sort by two keys, sort by the second and then by the first: the sort keeps the order of equal items.`,
367
+ ErrorCode.TYPE,
368
+ { op: "$sortBy" }
369
+ );
370
+ }
371
+ return key;
372
+ };
373
+ var NULL_KIND = 3;
374
+ var kindOf = (key) => key === null ? NULL_KIND : typeof key === "number" ? 0 : typeof key === "string" ? 1 : 2;
375
+ var opSortBy = (node, context, evaluate2) => {
376
+ const { over, as, by, dir = "asc" } = node.$sortBy;
377
+ const input = requireArray(evaluate2(over, context), "$sortBy.over");
378
+ const { scope, vars } = loopScope(context);
379
+ const keyed = input.map((item) => {
380
+ vars[as] = item;
381
+ return { item, key: sortKey(evaluate2(by, scope)) };
382
+ });
383
+ keyed.sort((a, b) => {
384
+ const kindA = kindOf(a.key);
385
+ const kindB = kindOf(b.key);
386
+ if (kindA === NULL_KIND || kindB === NULL_KIND) return kindA - kindB;
387
+ const cmp = kindA !== kindB ? kindA - kindB : compare(a.key, b.key) ?? Number(a.key) - Number(b.key);
388
+ return dir === "desc" ? -cmp : cmp;
389
+ });
390
+ return keyed.map((k) => k.item);
391
+ };
392
+
393
+ // src/ops/math.ops.ts
394
+ var requireNumbers = (node, context, evaluate2, op) => {
395
+ const a = evaluate2(node[0], context);
396
+ const b = evaluate2(node[1], context);
397
+ if (typeof a !== "number" || typeof b !== "number")
398
+ throw new PrismError(`Expected numbers for ${op}`, ErrorCode.TYPE, { op });
399
+ return [a, b];
400
+ };
401
+ var opAdd = (node, context, evaluate2) => {
402
+ const [a, b] = requireNumbers(node.$add, context, evaluate2, "$add");
403
+ return a + b;
404
+ };
405
+ var opSub = (node, context, evaluate2) => {
406
+ const [a, b] = requireNumbers(node.$sub, context, evaluate2, "$sub");
407
+ return a - b;
408
+ };
409
+ var opMul = (node, context, evaluate2) => {
410
+ const [a, b] = requireNumbers(node.$mul, context, evaluate2, "$mul");
411
+ return a * b;
412
+ };
413
+ var opDiv = (node, context, evaluate2) => {
414
+ const [a, b] = requireNumbers(node.$div, context, evaluate2, "$div");
415
+ if (b === 0) throw new PrismError("Division by zero", ErrorCode.DIVISION_BY_ZERO, { op: "$div" });
416
+ return a / b;
417
+ };
418
+ var opMod = (node, context, evaluate2) => {
419
+ const [a, b] = requireNumbers(node.$mod, context, evaluate2, "$mod");
420
+ if (b === 0) throw new PrismError("Division by zero", ErrorCode.DIVISION_BY_ZERO, { op: "$mod" });
421
+ const remainder = a % b;
422
+ if (remainder === 0) return 0;
423
+ return remainder < 0 !== b < 0 ? remainder + b : remainder;
424
+ };
425
+ var ROUNDING = { nearest: Math.round, floor: Math.floor, ceil: Math.ceil };
426
+ var opRound = (node, context, evaluate2) => {
427
+ const value = evaluate2(node.$round.value, context);
428
+ if (typeof value !== "number")
429
+ throw new PrismError("Expected number for $round", ErrorCode.TYPE, { op: "$round" });
430
+ const digits = node.$round.digits ?? 0;
431
+ const factor = Math.pow(10, digits);
432
+ return ROUNDING[node.$round.mode ?? "nearest"](value * factor) / factor;
433
+ };
434
+ var NUMERIC_TEXT = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
435
+ var whatIs = (value) => {
436
+ if (typeof value === "string") return JSON.stringify(value.slice(0, 40));
437
+ if (value === null) return "null";
438
+ if (Array.isArray(value)) return "a list";
439
+ return typeof value === "object" ? "an object" : String(value);
440
+ };
441
+ var opToNumber = (node, context, evaluate2) => {
442
+ const value = evaluate2(node.$toNumber.value, context);
443
+ if (typeof value === "number") return value;
444
+ if (typeof value === "string") {
445
+ const text = value.trim();
446
+ const parsed = NUMERIC_TEXT.test(text) ? Number(text) : Number.NaN;
447
+ if (Number.isFinite(parsed)) return parsed;
448
+ }
449
+ if (node.$toNumber.fallback !== void 0) return evaluate2(node.$toNumber.fallback, context);
450
+ throw new PrismError(`Expected a number or numeric text for $toNumber, got ${whatIs(value)}`, ErrorCode.TYPE, { op: "$toNumber" });
451
+ };
452
+
453
+ // src/ops/string.ops.ts
454
+ var opJoin = (node, context, evaluate2) => {
455
+ const { parts, sep = "" } = node.$join;
456
+ const list = evaluate2(parts, context);
457
+ if (!Array.isArray(list)) throw new PrismError("Expected $join.parts to evaluate to an array", ErrorCode.TYPE, { op: "$join" });
458
+ return list.map((p) => String(p ?? "")).join(sep);
459
+ };
460
+ var opToString = (node, context, evaluate2) => {
461
+ const value = evaluate2(node.$toString, context);
462
+ if (value === null) return "null";
463
+ if (typeof value === "object") return JSON.stringify(value);
464
+ return String(value);
465
+ };
466
+ var opInterpolate = (node, context, evaluate2) => {
467
+ const { template, values: valuesNode } = node.$interpolate;
468
+ const values = evaluate2(valuesNode, context);
469
+ if (!isJsonObject(values))
470
+ throw new PrismError("Expected object for $interpolate.values", ErrorCode.TYPE, { op: "$interpolate" });
471
+ return template.replace(
472
+ /\{\{(\w+)\}\}/g,
473
+ (_match, key) => String(values[key] ?? "")
474
+ );
475
+ };
476
+ var fillOne = (value) => {
477
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return value;
478
+ const { phrase, slots } = value;
479
+ if (typeof phrase !== "string" || !isJsonObject(slots)) return value;
480
+ return phrase.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (hole, name) => {
481
+ const slot = slots[name];
482
+ if (slot === void 0 || slot === null) return hole;
483
+ const filled = fillOne(slot);
484
+ return typeof filled === "object" ? hole : String(filled);
485
+ });
486
+ };
487
+ var opFill = (node, context, evaluate2) => fillOne(evaluate2(node.$fill, context));
488
+ var opTrim = (node, context, evaluate2) => {
489
+ const value = evaluate2(node.$trim, context);
490
+ if (typeof value !== "string")
491
+ throw new PrismError("Expected string for $trim", ErrorCode.TYPE, { op: "$trim" });
492
+ return value.trim();
493
+ };
494
+ var opLower = (node, context, evaluate2) => {
495
+ const value = evaluate2(node.$lower, context);
496
+ if (typeof value !== "string")
497
+ throw new PrismError("Expected string for $lower", ErrorCode.TYPE, { op: "$lower" });
498
+ return value.toLowerCase();
499
+ };
500
+ var opUpper = (node, context, evaluate2) => {
501
+ const value = evaluate2(node.$upper, context);
502
+ if (typeof value !== "string")
503
+ throw new PrismError("Expected string for $upper", ErrorCode.TYPE, { op: "$upper" });
504
+ return value.toUpperCase();
505
+ };
506
+ var opSplit = (node, context, evaluate2) => {
507
+ const value = evaluate2(node.$split.value, context);
508
+ if (typeof value !== "string")
509
+ throw new PrismError("Expected string for $split", ErrorCode.TYPE, { op: "$split" });
510
+ return value.split(node.$split.sep);
511
+ };
512
+ var opReplace = (node, context, evaluate2) => {
513
+ const value = evaluate2(node.$replace.value, context);
514
+ if (typeof value !== "string")
515
+ throw new PrismError("Expected string for $replace", ErrorCode.TYPE, { op: "$replace" });
516
+ const { search, replacement, all } = node.$replace;
517
+ return all === true ? value.replaceAll(search, replacement) : value.replace(search, replacement);
518
+ };
519
+
520
+ // src/ops/predicate.ops.ts
521
+ var opEq = (node, context, evaluate2) => {
522
+ const a = evaluate2(node.$eq[0], context);
523
+ const b = evaluate2(node.$eq[1], context);
524
+ return jsonEqual(a, b);
525
+ };
526
+ var opNeq = (node, context, evaluate2) => {
527
+ const a = evaluate2(node.$neq[0], context);
528
+ const b = evaluate2(node.$neq[1], context);
529
+ return !jsonEqual(a, b);
530
+ };
531
+ var compareOp = (pair, context, evaluate2, op, test) => {
532
+ const a = evaluate2(pair[0], context);
533
+ const b = evaluate2(pair[1], context);
534
+ const cmp = compare(a, b);
535
+ if (cmp === void 0)
536
+ throw new PrismError(`Cannot compare values for ${op}`, ErrorCode.TYPE, { op });
537
+ return test(cmp);
13
538
  };
539
+ var opGt = (node, ctx, ev) => compareOp(node.$gt, ctx, ev, "$gt", (c) => c > 0);
540
+ var opGte = (node, ctx, ev) => compareOp(node.$gte, ctx, ev, "$gte", (c) => c >= 0);
541
+ var opLt = (node, ctx, ev) => compareOp(node.$lt, ctx, ev, "$lt", (c) => c < 0);
542
+ var opLte = (node, ctx, ev) => compareOp(node.$lte, ctx, ev, "$lte", (c) => c <= 0);
543
+ var opEmpty = (node, context, evaluate2) => {
544
+ const value = evaluate2(node.$empty, context);
545
+ if (value === null || value === void 0) return true;
546
+ if (typeof value === "string") return value.length === 0;
547
+ if (isJsonArray(value)) return value.length === 0;
548
+ if (isJsonObject(value)) return Object.keys(value).length === 0;
549
+ return false;
550
+ };
551
+ var opStartsWith = (node, context, evaluate2) => {
552
+ const value = evaluate2(node.$startsWith.value, context);
553
+ const prefix = evaluate2(node.$startsWith.prefix, context);
554
+ if (typeof value !== "string" || typeof prefix !== "string")
555
+ throw new PrismError("Expected strings for $startsWith", ErrorCode.TYPE, { op: "$startsWith" });
556
+ return value.startsWith(prefix);
557
+ };
558
+ var opEndsWith = (node, context, evaluate2) => {
559
+ const value = evaluate2(node.$endsWith.value, context);
560
+ const suffix = evaluate2(node.$endsWith.suffix, context);
561
+ if (typeof value !== "string" || typeof suffix !== "string")
562
+ throw new PrismError("Expected strings for $endsWith", ErrorCode.TYPE, { op: "$endsWith" });
563
+ return value.endsWith(suffix);
564
+ };
565
+ var opContains = (node, context, evaluate2) => {
566
+ const value = evaluate2(node.$contains.value, context);
567
+ const search = evaluate2(node.$contains.search, context);
568
+ if (typeof value !== "string" || typeof search !== "string")
569
+ throw new PrismError("Expected strings for $contains", ErrorCode.TYPE, { op: "$contains" });
570
+ return value.includes(search);
571
+ };
572
+
573
+ // src/ops/logic.ops.ts
574
+ var opNot = (node, context, evaluate2) => !evaluate2(node.$not, context);
575
+ var opAnd = (node, context, evaluate2) => {
576
+ let last = true;
577
+ for (const operand of node.$and) {
578
+ last = evaluate2(operand, context);
579
+ if (!last) return last;
580
+ }
581
+ return last;
582
+ };
583
+ var opOr = (node, context, evaluate2) => {
584
+ let last = false;
585
+ for (const operand of node.$or) {
586
+ last = evaluate2(operand, context);
587
+ if (last) return last;
588
+ }
589
+ return last;
590
+ };
591
+
592
+ // src/ops/structure.ops.ts
593
+ var opMerge = (node, context, evaluate2) => {
594
+ const result = {};
595
+ for (const part of node.$merge) {
596
+ const evaluated = evaluate2(part, context);
597
+ if (!isJsonObject(evaluated))
598
+ throw new PrismError("Expected object for $merge element", ErrorCode.TYPE, { op: "$merge" });
599
+ Object.assign(result, evaluated);
600
+ }
601
+ return result;
602
+ };
603
+ var opCoalesce = (node, context, evaluate2) => {
604
+ for (const candidate of node.$coalesce) {
605
+ const value = evaluate2(candidate, context);
606
+ if (value !== null && value !== void 0) return value;
607
+ }
608
+ return null;
609
+ };
610
+ var opCase = (node, context, evaluate2) => {
611
+ for (const branch of node.$case.branches) {
612
+ const condition = evaluate2(branch.when, context);
613
+ if (condition) return evaluate2(branch.then, context);
614
+ }
615
+ if (node.$case.else !== void 0) return evaluate2(node.$case.else, context);
616
+ return null;
617
+ };
618
+ var opEntriesOf = (node, context, evaluate2) => {
619
+ const value = evaluate2(node.$entriesOf, context);
620
+ if (!isJsonObject(value))
621
+ throw new PrismError("Expected object for $entriesOf", ErrorCode.TYPE, { op: "$entriesOf" });
622
+ return Object.entries(value).map(([k, v]) => [k, v]);
623
+ };
624
+ var opKeyBy = (node, context, evaluate2) => {
625
+ const { over, as, key: keyExpr } = node.$keyBy;
626
+ const input = evaluate2(over, context);
627
+ if (!isJsonArray(input))
628
+ throw new PrismError("Expected array for $keyBy.over", ErrorCode.TYPE, { op: "$keyBy" });
629
+ const result = {};
630
+ const { scope, vars } = loopScope(context);
631
+ for (const item of input) {
632
+ vars[as] = item;
633
+ const key = evaluate2(keyExpr, scope);
634
+ result[String(key)] = item;
635
+ }
636
+ return result;
637
+ };
638
+ var opGroupBy = (node, context, evaluate2) => {
639
+ const { over, as, key: keyExpr } = node.$groupBy;
640
+ const input = evaluate2(over, context);
641
+ if (!isJsonArray(input))
642
+ throw new PrismError("Expected array for $groupBy.over", ErrorCode.TYPE, { op: "$groupBy" });
643
+ const result = {};
644
+ const { scope, vars } = loopScope(context);
645
+ for (const item of input) {
646
+ vars[as] = item;
647
+ const key = String(evaluate2(keyExpr, scope));
648
+ if (!result[key]) result[key] = [];
649
+ result[key].push(item);
650
+ }
651
+ return result;
652
+ };
653
+
654
+ // src/ops/object.ops.ts
655
+ var opKeys = (node, context, evaluate2) => {
656
+ const value = evaluate2(node.$keys, context);
657
+ if (!isJsonObject(value))
658
+ throw new PrismError("Expected object for $keys", ErrorCode.TYPE, { op: "$keys" });
659
+ return Object.keys(value);
660
+ };
661
+ var opValues = (node, context, evaluate2) => {
662
+ const value = evaluate2(node.$values, context);
663
+ if (!isJsonObject(value))
664
+ throw new PrismError("Expected object for $values", ErrorCode.TYPE, { op: "$values" });
665
+ return Object.values(value);
666
+ };
667
+ var opFromEntries = (node, context, evaluate2) => {
668
+ const value = evaluate2(node.$fromEntries, context);
669
+ if (!isJsonArray(value))
670
+ throw new PrismError("Expected array for $fromEntries", ErrorCode.TYPE, { op: "$fromEntries" });
671
+ const result = {};
672
+ for (const entry of value) {
673
+ if (!isJsonArray(entry) || entry.length < 2)
674
+ throw new PrismError("Expected [key, value] pairs for $fromEntries", ErrorCode.TYPE, { op: "$fromEntries" });
675
+ result[String(entry[0])] = entry[1];
676
+ }
677
+ return result;
678
+ };
679
+ var opPick = (node, context, evaluate2) => {
680
+ const value = evaluate2(node.$pick.from, context);
681
+ if (!isJsonObject(value))
682
+ throw new PrismError("Expected object for $pick", ErrorCode.TYPE, { op: "$pick" });
683
+ const result = {};
684
+ for (const key of node.$pick.keys) {
685
+ if (key in value) result[key] = value[key];
686
+ }
687
+ return result;
688
+ };
689
+ var opOmit = (node, context, evaluate2) => {
690
+ const value = evaluate2(node.$omit.from, context);
691
+ if (!isJsonObject(value))
692
+ throw new PrismError("Expected object for $omit", ErrorCode.TYPE, { op: "$omit" });
693
+ const keysToOmit = new Set(node.$omit.keys);
694
+ const result = {};
695
+ for (const [k, v] of Object.entries(value)) {
696
+ if (!keysToOmit.has(k)) result[k] = v;
697
+ }
698
+ return result;
699
+ };
700
+ var opType = (node, context, evaluate2) => {
701
+ const value = evaluate2(node.$type, context);
702
+ if (value === null) return "null";
703
+ if (isJsonArray(value)) return "array";
704
+ return typeof value;
705
+ };
706
+ var opLength = (node, context, evaluate2) => {
707
+ const value = evaluate2(node.$length, context);
708
+ if (typeof value === "string") return value.length;
709
+ if (isJsonArray(value)) return value.length;
710
+ throw new PrismError("Expected array or string for $length", ErrorCode.TYPE, { op: "$length" });
711
+ };
712
+
713
+ // src/ops/transform.ops.ts
714
+ var has = (value, path) => {
715
+ let at = value;
716
+ for (const segment of path) {
717
+ if (typeof segment === "number") {
718
+ if (!isJsonArray(at) || segment >= at.length) return false;
719
+ at = at[segment] ?? null;
720
+ } else {
721
+ if (!isJsonObject(at) || !Object.prototype.hasOwnProperty.call(at, segment)) return false;
722
+ at = at[segment] ?? null;
723
+ }
724
+ }
725
+ return true;
726
+ };
727
+ var opHas = (node, context, evaluate2) => has(evaluate2(node.$has.from, context), node.$has.path);
728
+ var opRenameKeys = (node, context, evaluate2) => {
729
+ const value = evaluate2(node.$renameKeys.from, context);
730
+ if (!isJsonObject(value)) throw new PrismError("Expected object for $renameKeys", ErrorCode.TYPE, { op: "$renameKeys" });
731
+ const { map } = node.$renameKeys;
732
+ const renamedTo = new Set(Object.entries(map).filter(([from]) => Object.prototype.hasOwnProperty.call(value, from)).map(([, to]) => to));
733
+ const result = {};
734
+ for (const [key, v] of Object.entries(value)) {
735
+ const target = map[key];
736
+ if (target !== void 0) result[target] = v;
737
+ else if (!renamedTo.has(key)) result[key] = v;
738
+ }
739
+ return result;
740
+ };
741
+ var current = (value, path) => {
742
+ let at = value;
743
+ for (const segment of path) {
744
+ if (typeof segment === "number") at = isJsonArray(at) ? at[segment] ?? null : null;
745
+ else at = isJsonObject(at) ? at[segment] ?? null : null;
746
+ }
747
+ return at;
748
+ };
749
+ var setIn = (value, path, next, full) => {
750
+ const [head, ...rest] = path;
751
+ if (head === void 0) return next;
752
+ if (typeof head === "number") {
753
+ if (!isJsonArray(value) || head >= value.length) {
754
+ throw new PrismError(`No array item at ${full.join(".")}`, ErrorCode.MISSING_PATH, { op: "$update", path: full.join(".") });
755
+ }
756
+ return value.map((item, i) => i === head ? setIn(item, rest, next, full) : item);
757
+ }
758
+ const base = isJsonObject(value) ? value : {};
759
+ return { ...base, [head]: setIn(base[head] ?? null, rest, next, full) };
760
+ };
761
+ var opUpdate = (node, context, evaluate2) => {
762
+ const { from, path, value, as } = node.$update;
763
+ const source = evaluate2(from, context);
764
+ const next = evaluate2(value, { ...context, vars: { ...context.vars, [as ?? "current"]: current(source, path) } });
765
+ return setIn(source, path, next, path);
766
+ };
767
+ var opAssert = (node, context, evaluate2) => {
768
+ if (!evaluate2(node.$assert.when, context)) throw new PrismError(node.$assert.message, ErrorCode.ASSERT, { op: "$assert" });
769
+ return evaluate2(node.$assert.value, context);
770
+ };
771
+ var opWalk = (node, context, evaluate2) => {
772
+ const { over, as, rules, order } = node.$walk;
773
+ const rewrite = (value) => {
774
+ const scope = { ...context, vars: { ...context.vars, [as]: value } };
775
+ for (const rule of rules) {
776
+ if (evaluate2(rule.when, scope)) return { matched: true, value: evaluate2(rule.then, scope) };
777
+ }
778
+ return { matched: false, value };
779
+ };
780
+ const children = (value, visit) => {
781
+ if (isJsonArray(value)) return value.map(visit);
782
+ if (isJsonObject(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, visit(v)]));
783
+ return value;
784
+ };
785
+ const post = (value) => rewrite(children(value, post)).value;
786
+ const pre = (value) => children(rewrite(value).value, pre);
787
+ return (order ?? "post") === "pre" ? pre(evaluate2(over, context)) : post(evaluate2(over, context));
788
+ };
789
+ dayjs.extend(utc);
790
+ var DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
791
+ var isDateOnly = (value) => typeof value === "string" && DATE_ONLY.test(value);
792
+ var parseDate = (value, op) => {
793
+ if (typeof value !== "string" && typeof value !== "number")
794
+ throw new PrismError(`Expected string or number for ${op}`, ErrorCode.TYPE, { op });
795
+ const d = isDateOnly(value) ? dayjs.utc(value) : dayjs(value);
796
+ if (!d.isValid())
797
+ throw new PrismError(`Invalid date for ${op}: ${String(value)}`, ErrorCode.DATE_INVALID, { op });
798
+ return d;
799
+ };
800
+ var opDate = (node, context, evaluate2) => {
801
+ const value = evaluate2(node.$date.value, context);
802
+ const d = parseDate(value, "$date");
803
+ const instance = node.$date.utc ? d.utc() : d;
804
+ if (node.$date.format) return instance.format(node.$date.format);
805
+ return instance.toISOString();
806
+ };
807
+ var opDateAdd = (node, context, evaluate2) => {
808
+ const value = evaluate2(node.$dateAdd.date, context);
809
+ const d = parseDate(value, "$dateAdd");
810
+ const moved = d.add(node.$dateAdd.amount, node.$dateAdd.unit);
811
+ return isDateOnly(value) ? moved.format("YYYY-MM-DD") : moved.toISOString();
812
+ };
813
+ var opDateDiff = (node, context, evaluate2) => {
814
+ const from = evaluate2(node.$dateDiff.from, context);
815
+ const to = evaluate2(node.$dateDiff.to, context);
816
+ const fromDate = parseDate(from, "$dateDiff.from");
817
+ const toDate = parseDate(to, "$dateDiff.to");
818
+ return toDate.diff(fromDate, node.$dateDiff.unit);
819
+ };
820
+
821
+ // src/ops/intl.ops.ts
822
+ var DATE_FORMATTERS = /* @__PURE__ */ new Map();
823
+ var NUMBER_FORMATTERS = /* @__PURE__ */ new Map();
824
+ var DATE_ONLY2 = /^\d{4}-\d{2}-\d{2}$/;
825
+ var localeOf = (value, op) => {
826
+ if (typeof value !== "string" || value.trim() === "")
827
+ throw new PrismError(`${op} needs a locale tag (e.g. "de-AT")`, ErrorCode.TYPE, { op });
828
+ return value;
829
+ };
830
+ var isBlank = (value) => value === null || value === void 0 || value === "";
831
+ var fallbackOf = (raw, context, evaluate2) => {
832
+ if (raw === void 0) return "";
833
+ const resolved = evaluate2(raw, context);
834
+ return resolved === null || resolved === void 0 ? "" : resolved;
835
+ };
836
+ var numberOf = (value, op) => {
837
+ const parsed = typeof value === "number" ? value : Number(value);
838
+ if (!Number.isFinite(parsed)) throw new PrismError(`${op} expected a number, got ${JSON.stringify(value)}`, ErrorCode.TYPE, { op });
839
+ return parsed;
840
+ };
841
+ var opLocaleDate = (node, context, evaluate2) => {
842
+ const spec = node.$localeDate;
843
+ const value = evaluate2(spec.value, context);
844
+ if (isBlank(value)) return fallbackOf(spec.fallback, context, evaluate2);
845
+ const locale = localeOf(evaluate2(spec.locale, context), "$localeDate");
846
+ const authored = spec.options ?? { dateStyle: "medium" };
847
+ const dateOnly = typeof value === "string" && DATE_ONLY2.test(value);
848
+ const options = {
849
+ ...authored,
850
+ ...authored.timeZone === void 0 && dateOnly ? { timeZone: "UTC" } : {}
851
+ };
852
+ const parsed = typeof value === "number" ? new Date(value) : new Date(String(value));
853
+ if (Number.isNaN(parsed.getTime()))
854
+ throw new PrismError(`Invalid date for $localeDate: ${String(value)}`, ErrorCode.DATE_INVALID, { op: "$localeDate" });
855
+ const key = `${locale}\0${JSON.stringify(options)}`;
856
+ let formatter = DATE_FORMATTERS.get(key);
857
+ if (formatter === void 0) {
858
+ formatter = new Intl.DateTimeFormat(locale, options);
859
+ DATE_FORMATTERS.set(key, formatter);
860
+ }
861
+ return formatter.format(parsed);
862
+ };
863
+ var minorUnitDivisor = (locale, currency) => {
864
+ const key = `divisor\0${locale}\0${currency}`;
865
+ let formatter = NUMBER_FORMATTERS.get(key);
866
+ if (formatter === void 0) {
867
+ try {
868
+ formatter = new Intl.NumberFormat(locale, { style: "currency", currency });
869
+ } catch {
870
+ return 100;
871
+ }
872
+ NUMBER_FORMATTERS.set(key, formatter);
873
+ }
874
+ return 10 ** (formatter.resolvedOptions().maximumFractionDigits ?? 2);
875
+ };
876
+ var opLocaleMoney = (node, context, evaluate2) => {
877
+ const spec = node.$localeMoney;
878
+ const value = evaluate2(spec.value, context);
879
+ if (isBlank(value)) return fallbackOf(spec.fallback, context, evaluate2);
880
+ const locale = localeOf(evaluate2(spec.locale, context), "$localeMoney");
881
+ const rawCurrency = evaluate2(spec.currency, context);
882
+ if (typeof rawCurrency !== "string" || rawCurrency.trim() === "")
883
+ throw new PrismError("$localeMoney needs an ISO-4217 currency code", ErrorCode.TYPE, { op: "$localeMoney" });
884
+ const currency = rawCurrency.toUpperCase();
885
+ const amount = numberOf(value, "$localeMoney");
886
+ const major = spec.minorUnits === false ? amount : amount / minorUnitDivisor(locale, currency);
887
+ const options = {
888
+ style: "currency",
889
+ currency,
890
+ ...spec.digits === void 0 ? {} : { minimumFractionDigits: spec.digits, maximumFractionDigits: spec.digits }
891
+ };
892
+ const key = `${locale}\0${JSON.stringify(options)}`;
893
+ let formatter = NUMBER_FORMATTERS.get(key);
894
+ if (formatter === void 0) {
895
+ try {
896
+ formatter = new Intl.NumberFormat(locale, options);
897
+ } catch {
898
+ return `${currency} ${major.toFixed(spec.digits ?? 2)}`;
899
+ }
900
+ NUMBER_FORMATTERS.set(key, formatter);
901
+ }
902
+ return formatter.format(major);
903
+ };
904
+ var opLocaleNumber = (node, context, evaluate2) => {
905
+ const spec = node.$localeNumber;
906
+ const value = evaluate2(spec.value, context);
907
+ if (isBlank(value)) return fallbackOf(spec.fallback, context, evaluate2);
908
+ const locale = localeOf(evaluate2(spec.locale, context), "$localeNumber");
909
+ const options = {
910
+ style: spec.style ?? "decimal",
911
+ ...spec.digits === void 0 ? {} : { maximumFractionDigits: spec.digits },
912
+ ...spec.minDigits === void 0 ? {} : { minimumFractionDigits: spec.minDigits },
913
+ ...spec.compact === true ? { notation: "compact" } : {}
914
+ };
915
+ const key = `${locale}\0${JSON.stringify(options)}`;
916
+ let formatter = NUMBER_FORMATTERS.get(key);
917
+ if (formatter === void 0) {
918
+ formatter = new Intl.NumberFormat(locale, options);
919
+ NUMBER_FORMATTERS.set(key, formatter);
920
+ }
921
+ return formatter.format(numberOf(value, "$localeNumber"));
922
+ };
923
+
924
+ // src/engine/optimize.ts
925
+ var HANDLER_KEY = "__op";
926
+ var SEGMENTS_KEY2 = "__segments";
927
+ var eraseOp = (op) => op;
14
928
  var attachNonEnumerable = (target, key, value) => {
15
929
  Object.defineProperty(target, key, {
16
930
  value,
@@ -19,7 +933,12 @@ var attachNonEnumerable = (target, key, value) => {
19
933
  configurable: true
20
934
  });
21
935
  };
22
- var isPlainObject = (value) => isJsonObject(value);
936
+ var isPlainObject2 = (value) => isJsonObject(value);
937
+ var freezeConstant = (value) => {
938
+ if (value === null || typeof value !== "object" || Object.isFrozen(value)) return;
939
+ Object.freeze(value);
940
+ for (const inner of Object.values(value)) freezeConstant(inner);
941
+ };
23
942
  var resolveHandler = (node) => {
24
943
  if (isRefNode(node)) return eraseOp(opRef);
25
944
  if (isConstNode(node)) return eraseOp(opConst);
@@ -38,6 +957,8 @@ var resolveHandler = (node) => {
38
957
  if (isMulNode(node)) return eraseOp(opMul);
39
958
  if (isDivNode(node)) return eraseOp(opDiv);
40
959
  if (isRoundNode(node)) return eraseOp(opRound);
960
+ if (isModNode(node)) return eraseOp(opMod);
961
+ if (isToNumberNode(node)) return eraseOp(opToNumber);
41
962
  if (isJoinNode(node)) return eraseOp(opJoin);
42
963
  if (isToStringNode(node)) return eraseOp(opToString);
43
964
  if (isInterpolateNode(node)) return eraseOp(opInterpolate);
@@ -91,7 +1012,7 @@ var isFoldableLiteral = (node) => {
91
1012
  const t = typeof node;
92
1013
  if (t === "string" || t === "number" || t === "boolean") return true;
93
1014
  if (Array.isArray(node)) return node.every(isFoldableLiteral);
94
- if (!isPlainObject(node)) return false;
1015
+ if (!isPlainObject2(node)) return false;
95
1016
  if (isConstNode(node)) return isFoldableLiteral(node.$const);
96
1017
  if (Object.keys(node).some((k) => k.startsWith("$"))) return false;
97
1018
  return Object.values(node).every(isFoldableLiteral);
@@ -104,22 +1025,31 @@ var optimizeNode = (node, stats, evaluate2) => {
104
1025
  for (const child of node) out.push(optimizeNode(child, stats, evaluate2));
105
1026
  return out;
106
1027
  }
107
- if (!isPlainObject(node)) return node;
1028
+ if (!isPlainObject2(node)) return node;
108
1029
  if (isConstNode(node)) {
109
1030
  const literal = { ...node };
1031
+ freezeConstant(literal["$const"]);
110
1032
  attachNonEnumerable(literal, HANDLER_KEY, eraseOp(opConst));
111
1033
  stats.handlersAttached += 1;
112
1034
  return literal;
113
1035
  }
114
- const keys = Object.keys(node);
115
- const optimized = {};
116
- for (const key of keys) {
117
- optimized[key] = optimizeNode(node[key], stats, evaluate2);
1036
+ const optimizeValues = (record) => {
1037
+ const out = {};
1038
+ for (const key of Object.keys(record)) out[key] = optimizeNode(record[key], stats, evaluate2);
1039
+ return out;
1040
+ };
1041
+ let optimized;
1042
+ if (isWithNode(node)) {
1043
+ optimized = { $with: { let: optimizeValues(node.$with.let), value: optimizeNode(node.$with.value, stats, evaluate2) } };
1044
+ } else if (isRenameKeysNode(node)) {
1045
+ optimized = { $renameKeys: { ...node.$renameKeys, from: optimizeNode(node.$renameKeys.from, stats, evaluate2) } };
1046
+ } else {
1047
+ optimized = optimizeValues(node);
118
1048
  }
119
1049
  if (isRefNode(optimized)) {
120
1050
  const segments = parseJsonPath(optimized.$ref);
121
1051
  if (segments.length > 0) {
122
- attachNonEnumerable(optimized, SEGMENTS_KEY, segments);
1052
+ attachNonEnumerable(optimized, SEGMENTS_KEY2, segments);
123
1053
  stats.refsInlined += 1;
124
1054
  }
125
1055
  }
@@ -130,7 +1060,7 @@ var optimizeNode = (node, stats, evaluate2) => {
130
1060
  }
131
1061
  if (handler !== void 0 && !isConstNode(optimized) && !isRefNode(optimized) && !isVarNode(optimized)) {
132
1062
  const allFoldable = Object.entries(optimized).every(([key, value]) => {
133
- if (key === HANDLER_KEY || key === SEGMENTS_KEY) return true;
1063
+ if (key === HANDLER_KEY || key === SEGMENTS_KEY2) return true;
134
1064
  return isFoldableLiteral(value);
135
1065
  });
136
1066
  if (allFoldable) {
@@ -138,6 +1068,7 @@ var optimizeNode = (node, stats, evaluate2) => {
138
1068
  try {
139
1069
  const folded = handler(optimized, emptyCtx, evaluate2);
140
1070
  const replacement = { $const: folded };
1071
+ freezeConstant(folded);
141
1072
  attachNonEnumerable(replacement, HANDLER_KEY, eraseOp(opConst));
142
1073
  stats.constantsFolded += 1;
143
1074
  return replacement;
@@ -157,20 +1088,186 @@ var annotateNode = (node) => {
157
1088
  for (const child of node) annotateNode(child);
158
1089
  return;
159
1090
  }
160
- if (!isPlainObject(node)) return;
161
- if (!isConstNode(node)) {
1091
+ if (!isPlainObject2(node)) return;
1092
+ if (isWithNode(node)) {
1093
+ for (const value of Object.values(node.$with.let)) annotateNode(value);
1094
+ annotateNode(node.$with.value);
1095
+ } else if (isRenameKeysNode(node)) {
1096
+ annotateNode(node.$renameKeys.from);
1097
+ } else if (!isConstNode(node)) {
162
1098
  for (const value of Object.values(node)) annotateNode(value);
1099
+ } else {
1100
+ freezeConstant(node.$const);
163
1101
  }
164
1102
  if (isRefNode(node)) {
165
1103
  const segments = parseJsonPath(node.$ref);
166
- if (segments.length > 0) attachNonEnumerable(node, SEGMENTS_KEY, segments);
1104
+ if (segments.length > 0) attachNonEnumerable(node, SEGMENTS_KEY2, segments);
167
1105
  }
168
1106
  const handler = resolveHandler(node);
169
1107
  if (handler !== void 0) attachNonEnumerable(node, HANDLER_KEY, handler);
170
1108
  };
171
1109
  var rehydrate = (core) => annotateNode(core);
172
1110
 
173
- // src/engine/compile.ts
1111
+ // src/engine/evaluate.ts
1112
+ var HANDLER_KEY2 = "__op";
1113
+ var isAttachedFn = (value) => typeof value === "function";
1114
+ var evaluateNode = (node, context) => {
1115
+ const { budget } = context;
1116
+ if (budget === void 0) return evaluateUnbudgeted(node, context);
1117
+ spendStep(budget);
1118
+ const out = evaluateUnbudgeted(node, context);
1119
+ measureString(out, budget);
1120
+ return out;
1121
+ };
1122
+ var evaluateUnbudgeted = (node, context) => {
1123
+ if (node === null || node === void 0) return null;
1124
+ if (typeof node === "string" || typeof node === "number" || typeof node === "boolean") return node;
1125
+ if (Array.isArray(node)) return node.map((n) => evaluateNode(n, context));
1126
+ if (typeof node !== "object") return null;
1127
+ const obj = node;
1128
+ const attached = obj[HANDLER_KEY2];
1129
+ if (isAttachedFn(attached)) return attached(obj, context, evaluateNode);
1130
+ if (isPlainObject(obj)) {
1131
+ const result = {};
1132
+ if (!(OPTIONAL_FIELDS_KEY in obj)) {
1133
+ for (const key of Object.keys(obj)) result[key] = evaluateNode(obj[key], context);
1134
+ return result;
1135
+ }
1136
+ const optionalFields = new Set(
1137
+ Array.isArray(obj[OPTIONAL_FIELDS_KEY]) ? obj[OPTIONAL_FIELDS_KEY] : []
1138
+ );
1139
+ for (const [key, value] of Object.entries(obj)) {
1140
+ if (key === OPTIONAL_FIELDS_KEY) continue;
1141
+ const isOptional = optionalFields.has(key);
1142
+ try {
1143
+ const evaluated = evaluateNode(value, context);
1144
+ if (isOptional && (evaluated === null || evaluated === void 0)) continue;
1145
+ result[key] = evaluated;
1146
+ } catch (error) {
1147
+ if (isOptional && error instanceof PrismError && error.code === ErrorCode.MISSING_PATH) continue;
1148
+ throw error;
1149
+ }
1150
+ }
1151
+ return result;
1152
+ }
1153
+ if (isRefNode(obj)) return opRef(obj, context);
1154
+ if (isConstNode(obj)) return opConst(obj, context);
1155
+ if (isVarNode(obj)) return opVar(obj, context);
1156
+ if (isGetNode(obj)) return opGet(obj, context, evaluateNode);
1157
+ if (isWithNode(obj)) return opWith(obj, context, evaluateNode);
1158
+ if (isMapNode(obj)) return opMap(obj, context, evaluateNode);
1159
+ if (isFilterNode(obj)) return opFilter(obj, context, evaluateNode);
1160
+ if (isReduceNode(obj)) return opReduce(obj, context, evaluateNode);
1161
+ if (isSliceNode(obj)) return opSlice(obj, context, evaluateNode);
1162
+ if (isFlattenNode(obj)) return opFlatten(obj, context, evaluateNode);
1163
+ if (isUniqueNode(obj)) return opUnique(obj, context, evaluateNode);
1164
+ if (isSortByNode(obj)) return opSortBy(obj, context, evaluateNode);
1165
+ if (isAddNode(obj)) return opAdd(obj, context, evaluateNode);
1166
+ if (isSubNode(obj)) return opSub(obj, context, evaluateNode);
1167
+ if (isMulNode(obj)) return opMul(obj, context, evaluateNode);
1168
+ if (isDivNode(obj)) return opDiv(obj, context, evaluateNode);
1169
+ if (isRoundNode(obj)) return opRound(obj, context, evaluateNode);
1170
+ if (isModNode(obj)) return opMod(obj, context, evaluateNode);
1171
+ if (isToNumberNode(obj)) return opToNumber(obj, context, evaluateNode);
1172
+ if (isJoinNode(obj)) return opJoin(obj, context, evaluateNode);
1173
+ if (isToStringNode(obj)) return opToString(obj, context, evaluateNode);
1174
+ if (isInterpolateNode(obj)) return opInterpolate(obj, context, evaluateNode);
1175
+ if (isFillNode(obj)) return opFill(obj, context, evaluateNode);
1176
+ if (isTrimNode(obj)) return opTrim(obj, context, evaluateNode);
1177
+ if (isLowerNode(obj)) return opLower(obj, context, evaluateNode);
1178
+ if (isUpperNode(obj)) return opUpper(obj, context, evaluateNode);
1179
+ if (isSplitNode(obj)) return opSplit(obj, context, evaluateNode);
1180
+ if (isReplaceNode(obj)) return opReplace(obj, context, evaluateNode);
1181
+ if (isEqNode(obj)) return opEq(obj, context, evaluateNode);
1182
+ if (isNeqNode(obj)) return opNeq(obj, context, evaluateNode);
1183
+ if (isGtNode(obj)) return opGt(obj, context, evaluateNode);
1184
+ if (isGteNode(obj)) return opGte(obj, context, evaluateNode);
1185
+ if (isLtNode(obj)) return opLt(obj, context, evaluateNode);
1186
+ if (isLteNode(obj)) return opLte(obj, context, evaluateNode);
1187
+ if (isEmptyNode(obj)) return opEmpty(obj, context, evaluateNode);
1188
+ if (isStartsWithNode(obj)) return opStartsWith(obj, context, evaluateNode);
1189
+ if (isEndsWithNode(obj)) return opEndsWith(obj, context, evaluateNode);
1190
+ if (isContainsNode(obj)) return opContains(obj, context, evaluateNode);
1191
+ if (isNotNode(obj)) return opNot(obj, context, evaluateNode);
1192
+ if (isAndNode(obj)) return opAnd(obj, context, evaluateNode);
1193
+ if (isOrNode(obj)) return opOr(obj, context, evaluateNode);
1194
+ if (isMergeNode(obj)) return opMerge(obj, context, evaluateNode);
1195
+ if (isCoalesceNode(obj)) return opCoalesce(obj, context, evaluateNode);
1196
+ if (isCaseNode(obj)) return opCase(obj, context, evaluateNode);
1197
+ if (isEntriesOfNode(obj)) return opEntriesOf(obj, context, evaluateNode);
1198
+ if (isKeyByNode(obj)) return opKeyBy(obj, context, evaluateNode);
1199
+ if (isGroupByNode(obj)) return opGroupBy(obj, context, evaluateNode);
1200
+ if (isKeysNode(obj)) return opKeys(obj, context, evaluateNode);
1201
+ if (isValuesNode(obj)) return opValues(obj, context, evaluateNode);
1202
+ if (isFromEntriesNode(obj)) return opFromEntries(obj, context, evaluateNode);
1203
+ if (isPickNode(obj)) return opPick(obj, context, evaluateNode);
1204
+ if (isOmitNode(obj)) return opOmit(obj, context, evaluateNode);
1205
+ if (isTypeNode(obj)) return opType(obj, context, evaluateNode);
1206
+ if (isLengthNode(obj)) return opLength(obj, context, evaluateNode);
1207
+ if (isHasNode(obj)) return opHas(obj, context, evaluateNode);
1208
+ if (isRenameKeysNode(obj)) return opRenameKeys(obj, context, evaluateNode);
1209
+ if (isUpdateNode(obj)) return opUpdate(obj, context, evaluateNode);
1210
+ if (isAssertNode(obj)) return opAssert(obj, context, evaluateNode);
1211
+ if (isWalkNode(obj)) return opWalk(obj, context, evaluateNode);
1212
+ if (isDateNode(obj)) return opDate(obj, context, evaluateNode);
1213
+ if (isDateAddNode(obj)) return opDateAdd(obj, context, evaluateNode);
1214
+ if (isDateDiffNode(obj)) return opDateDiff(obj, context, evaluateNode);
1215
+ if (isLocaleDateNode(obj)) return opLocaleDate(obj, context, evaluateNode);
1216
+ if (isLocaleMoneyNode(obj)) return opLocaleMoney(obj, context, evaluateNode);
1217
+ if (isLocaleNumberNode(obj)) return opLocaleNumber(obj, context, evaluateNode);
1218
+ const unknownKeys = Object.keys(obj).filter((k) => k.startsWith("$"));
1219
+ throw new PrismError("Unsupported node shape", ErrorCode.NODE_SHAPE, {
1220
+ details: { keys: unknownKeys, preview: JSON.stringify(obj).slice(0, 100) }
1221
+ });
1222
+ };
1223
+ var isJsonValue = (value) => {
1224
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
1225
+ if (typeof value === "number") return Number.isFinite(value);
1226
+ if (Array.isArray(value)) return value.every(isJsonValue);
1227
+ if (typeof value !== "object") return false;
1228
+ const proto = Object.getPrototypeOf(value);
1229
+ return (proto === Object.prototype || proto === null) && Object.values(value).every(isJsonValue);
1230
+ };
1231
+ var checked = (config) => {
1232
+ if (exceedsDepth(config)) throw new PrismError("Invalid config", ErrorCode.SCHEMA, { details: { issues: [{ path: "root", message: depthRefusal() }] } });
1233
+ const parsed = ConfigSchema.safeParse(config);
1234
+ if (!parsed.success) {
1235
+ const issues = explainIssues(parsed.error.issues).map((i) => ({ path: i.path.join(".") || "root", message: i.message }));
1236
+ throw new PrismError("Invalid config", ErrorCode.SCHEMA, { details: { issues } });
1237
+ }
1238
+ return desugar(parsed.data);
1239
+ };
1240
+ var run = (tree, source, limits, kept) => {
1241
+ const budget = createBudget(limits);
1242
+ const result = evaluateNode(tree, kept ? { source, vars: {}, budget, kept } : { source, vars: {}, budget });
1243
+ measure(result, budget);
1244
+ return result;
1245
+ };
1246
+ var keptTrees = /* @__PURE__ */ new WeakMap();
1247
+ var evaluate = (config, source, options) => {
1248
+ if (options?.check === "always") {
1249
+ if (!isJsonValue(source)) throw new PrismError("The source must be plain JSON.", ErrorCode.TYPE);
1250
+ return run(checked(config), source, options.limits, false);
1251
+ }
1252
+ const input = source;
1253
+ if (typeof config !== "object" || config === null) return run(checked(config), input, options?.limits, false);
1254
+ let kept = keptTrees.get(config);
1255
+ if (kept === void 0) {
1256
+ kept = { tree: checked(config), optimized: false };
1257
+ keptTrees.set(config, kept);
1258
+ } else if (!kept.optimized) {
1259
+ kept.tree = optimize(kept.tree, evaluateNode).node;
1260
+ kept.optimized = true;
1261
+ }
1262
+ return run(kept.tree, input, options?.limits, true);
1263
+ };
1264
+ var evaluateSafe = (config, source, options) => {
1265
+ try {
1266
+ return { ok: true, data: evaluate(config, source, options) };
1267
+ } catch (error) {
1268
+ return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };
1269
+ }
1270
+ };
174
1271
  var walk = (node, stats, depth) => {
175
1272
  stats.nodeCount++;
176
1273
  if (depth > stats.maxDepth) stats.maxDepth = depth;
@@ -249,9 +1346,6 @@ var compile = async (config, options) => {
249
1346
  // src/engine/execute.ts
250
1347
  var hydrated = /* @__PURE__ */ new WeakSet();
251
1348
  var execute = (ir, source, limits) => {
252
- if (ir.tables.paths.length > 0) {
253
- primeJsonPathCache(ir.tables.paths);
254
- }
255
1349
  const { core } = ir;
256
1350
  if (typeof core === "object" && core !== null && !hydrated.has(core)) {
257
1351
  rehydrate(core);
@@ -276,6 +1370,6 @@ var validate = (config) => {
276
1370
  return { ok: true, data: parsed.data };
277
1371
  };
278
1372
 
279
- export { compile, execute, validate };
1373
+ export { DEFAULT_LIMITS, compile, evaluate, evaluateSafe, execute, validate };
280
1374
  //# sourceMappingURL=index.js.map
281
1375
  //# sourceMappingURL=index.js.map