@niscorp/prism 0.3.0 → 0.3.2

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.
@@ -9,9 +9,7 @@ var ErrorCode = {
9
9
  DATE_INVALID: "E_DATE_INVALID",
10
10
  VAR_NOT_FOUND: "E_VAR_NOT_FOUND",
11
11
  NODE_SHAPE: "E_NODE_SHAPE",
12
- // A config's own `$assert` refused its input.
13
12
  ASSERT: "E_ASSERT",
14
- // An evaluation past its budget (engine/budget.ts).
15
13
  BUDGET: "E_BUDGET"
16
14
  };
17
15
  var PrismError = class extends Error {
@@ -24,6 +22,26 @@ var PrismError = class extends Error {
24
22
  this.context = context;
25
23
  }
26
24
  };
25
+ var origins = /* @__PURE__ */ new WeakMap();
26
+ var takeOrigin = (error) => {
27
+ const origin = origins.get(error);
28
+ origins.delete(error);
29
+ return origin;
30
+ };
31
+ var failAt = (message, code, context, origin) => {
32
+ const error = new PrismError(message, code, context);
33
+ origins.set(error, origin);
34
+ throw error;
35
+ };
36
+ var clip = (text, max) => text.length > max ? `${text.slice(0, max)}\u2026` : text;
37
+ var describeValue = (value) => {
38
+ if (value === null || value === void 0) return "null";
39
+ if (typeof value === "string") return `text ${clip(JSON.stringify(value), 60)}`;
40
+ if (typeof value === "number" || typeof value === "boolean") return `the ${typeof value} ${String(value)}`;
41
+ const json = clip(JSON.stringify(value) ?? String(value), 80);
42
+ if (Array.isArray(value)) return `a list of ${value.length} item${value.length === 1 ? "" : "s"}: ${json}`;
43
+ return `an object: ${json}`;
44
+ };
27
45
  var JsonPrimitiveSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]).describe("JSON primitive: string | number | boolean | null");
28
46
  var JsonValueSchema = z.lazy(
29
47
  () => z.union([JsonPrimitiveSchema, z.array(JsonValueSchema), z.record(z.string(), JsonValueSchema)])
@@ -173,6 +191,32 @@ var parseJsonPathCached = (path) => {
173
191
  cache.set(path, parsed);
174
192
  return parsed;
175
193
  };
194
+ var INDEX_TEXT = /^(0|[1-9][0-9]*)$/;
195
+ var MAX_KEYS = 10;
196
+ var whereStopped = (root, steps, nameUpTo, digitsIndex = false) => {
197
+ let at = root;
198
+ for (const [i, raw] of steps.entries()) {
199
+ const here = nameUpTo(i);
200
+ const shown = JSON.stringify(raw);
201
+ const step = digitsIndex && typeof raw === "string" && isJsonArray(at) && INDEX_TEXT.test(raw) ? Number(raw) : raw;
202
+ if (typeof step === "number") {
203
+ if (!isJsonArray(at)) return `stopped at ${shown}: the value at ${here} is ${describeValue(at)}, and only a list is read by index.`;
204
+ if (at[step] === void 0) return `stopped at ${shown}: the list at ${here} has ${at.length} item${at.length === 1 ? "" : "s"}.`;
205
+ at = at[step];
206
+ } else {
207
+ if (isJsonArray(at)) return `stopped at ${shown}: the value at ${here} is ${describeValue(at)}, and a list is read by index, a number; for every item use $map.`;
208
+ if (!isJsonObject(at)) return `stopped at ${shown}: the value at ${here} is ${describeValue(at)}, which has no keys.`;
209
+ if (at[step] === void 0) {
210
+ const keys = Object.keys(at);
211
+ const listed = keys.slice(0, MAX_KEYS).join(", ") + (keys.length > MAX_KEYS ? ", \u2026" : "");
212
+ return `stopped at ${shown}: the object at ${here} has no key ${shown} (${keys.length === 0 ? "it has no keys" : `its keys: ${listed}`}).`;
213
+ }
214
+ at = at[step];
215
+ }
216
+ }
217
+ return "";
218
+ };
219
+ var jsonPathUpTo = (segments, count) => segments.slice(0, count).reduce((text, s) => s.type === "key" ? `${text}.${s.key}` : `${text}[${s.index}]`, "$");
176
220
  var getByPath = (root, segments) => {
177
221
  let current = root;
178
222
  for (const segment of segments) {
@@ -707,19 +751,26 @@ var opMembersOf = (options) => {
707
751
  }
708
752
  return members;
709
753
  };
710
- var memberOf = (value, ops) => {
711
- if (value === null || typeof value !== "object") return JsonPrimitiveSchema;
712
- if (Array.isArray(value)) return NodeArraySchema;
754
+ var isPlainProto = (value) => {
713
755
  const proto = Object.getPrototypeOf(value);
714
- if (proto !== Object.prototype && proto !== null) return void 0;
715
- let op;
756
+ return proto === Object.prototype || proto === null;
757
+ };
758
+ var soleOpKey = (value) => {
759
+ if (value === null || typeof value !== "object" || Array.isArray(value) || !isPlainProto(value)) return void 0;
760
+ let sole;
716
761
  let count = 0;
717
762
  for (const key in value) {
718
763
  count += 1;
719
- if (key.startsWith("$")) op = key;
764
+ sole = key;
720
765
  }
721
- if (op === void 0) return TemplateSchema;
722
- return count === 1 ? ops.get(op) : void 0;
766
+ return count === 1 && sole !== void 0 && sole.startsWith("$") ? sole : void 0;
767
+ };
768
+ var memberOf = (value) => {
769
+ if (value === null || typeof value !== "object") return JsonPrimitiveSchema;
770
+ if (Array.isArray(value)) return NodeArraySchema;
771
+ if (!isPlainProto(value)) return void 0;
772
+ for (const key in value) if (key.startsWith("$")) return void 0;
773
+ return TemplateSchema;
723
774
  };
724
775
  var quick = /* @__PURE__ */ new WeakSet();
725
776
  var walking = /* @__PURE__ */ new WeakSet();
@@ -728,8 +779,15 @@ var NodeUnion = z.core.$constructor("PrismNodeUnion", (inst, def) => {
728
779
  const ops = opMembersOf(def.options);
729
780
  const walk = inst._zod.parse;
730
781
  inst._zod.parse = (payload, ctx) => {
782
+ const sole = soleOpKey(payload.value);
783
+ if (sole !== void 0) {
784
+ const op = ops.get(sole);
785
+ if (op !== void 0) return op._zod.run(payload, ctx);
786
+ payload.issues.push({ code: "custom", input: payload.value, path: [sole], message: templateKeyRefusal(sole), inst });
787
+ return payload;
788
+ }
731
789
  if (ctx.async !== false || walking.has(ctx)) return walk(payload, ctx);
732
- const member = memberOf(payload.value, ops);
790
+ const member = memberOf(payload.value);
733
791
  if (quick.has(ctx)) {
734
792
  if (member !== void 0) return member._zod.run(payload, ctx);
735
793
  payload.issues.push({ code: "custom", input: payload.value, inst });
@@ -749,103 +807,154 @@ var NodeUnion = z.core.$constructor("PrismNodeUnion", (inst, def) => {
749
807
  }
750
808
  };
751
809
  });
810
+ var OP_MEMBERS = [
811
+ RefNodeSchema,
812
+ ConstNodeSchema,
813
+ VarNodeSchema,
814
+ GetNodeSchema,
815
+ WithNodeSchema,
816
+ MapNodeSchema,
817
+ FilterNodeSchema,
818
+ ReduceNodeSchema,
819
+ SliceNodeSchema,
820
+ FlattenNodeSchema,
821
+ UniqueNodeSchema,
822
+ SortByNodeSchema,
823
+ AddNodeSchema,
824
+ SubNodeSchema,
825
+ MulNodeSchema,
826
+ DivNodeSchema,
827
+ ModNodeSchema,
828
+ RoundNodeSchema,
829
+ ToNumberNodeSchema,
830
+ FillNodeSchema,
831
+ JoinNodeSchema,
832
+ ToStringNodeSchema,
833
+ InterpolateNodeSchema,
834
+ TrimNodeSchema,
835
+ LowerNodeSchema,
836
+ UpperNodeSchema,
837
+ SplitNodeSchema,
838
+ ReplaceNodeSchema,
839
+ EqNodeSchema,
840
+ NeqNodeSchema,
841
+ GtNodeSchema,
842
+ GteNodeSchema,
843
+ LtNodeSchema,
844
+ LteNodeSchema,
845
+ EmptyNodeSchema,
846
+ StartsWithNodeSchema,
847
+ EndsWithNodeSchema,
848
+ ContainsNodeSchema,
849
+ NotNodeSchema,
850
+ AndNodeSchema,
851
+ OrNodeSchema,
852
+ MergeNodeSchema,
853
+ CoalesceNodeSchema,
854
+ CaseNodeSchema,
855
+ EntriesOfNodeSchema,
856
+ KeyByNodeSchema,
857
+ GroupByNodeSchema,
858
+ KeysNodeSchema,
859
+ ValuesNodeSchema,
860
+ FromEntriesNodeSchema,
861
+ PickNodeSchema,
862
+ OmitNodeSchema,
863
+ TypeNodeSchema,
864
+ LengthNodeSchema,
865
+ DateNodeSchema,
866
+ DateAddNodeSchema,
867
+ DateDiffNodeSchema,
868
+ LocaleDateNodeSchema,
869
+ LocaleMoneyNodeSchema,
870
+ LocaleNumberNodeSchema,
871
+ SumNodeSchema,
872
+ AvgNodeSchema,
873
+ CountNodeSchema,
874
+ MinNodeSchema,
875
+ MaxNodeSchema,
876
+ PluckNodeSchema,
877
+ TakeNodeSchema,
878
+ DropNodeSchema,
879
+ MatchNodeSchema,
880
+ FlatMapNodeSchema,
881
+ HasNodeSchema,
882
+ RenameKeysNodeSchema,
883
+ UpdateNodeSchema,
884
+ AssertNodeSchema,
885
+ WalkNodeSchema
886
+ ];
752
887
  var NodeSchema = z.lazy(
753
888
  () => new NodeUnion({ type: "union", options: [
754
- // Core
755
- RefNodeSchema,
756
- ConstNodeSchema,
757
- VarNodeSchema,
758
- GetNodeSchema,
759
- WithNodeSchema,
760
- // Array
761
- MapNodeSchema,
762
- FilterNodeSchema,
763
- ReduceNodeSchema,
764
- SliceNodeSchema,
765
- FlattenNodeSchema,
766
- UniqueNodeSchema,
767
- SortByNodeSchema,
768
- // Math
769
- AddNodeSchema,
770
- SubNodeSchema,
771
- MulNodeSchema,
772
- DivNodeSchema,
773
- ModNodeSchema,
774
- RoundNodeSchema,
775
- ToNumberNodeSchema,
776
- // String
777
- FillNodeSchema,
778
- JoinNodeSchema,
779
- ToStringNodeSchema,
780
- InterpolateNodeSchema,
781
- TrimNodeSchema,
782
- LowerNodeSchema,
783
- UpperNodeSchema,
784
- SplitNodeSchema,
785
- ReplaceNodeSchema,
786
- // Predicates
787
- EqNodeSchema,
788
- NeqNodeSchema,
789
- GtNodeSchema,
790
- GteNodeSchema,
791
- LtNodeSchema,
792
- LteNodeSchema,
793
- EmptyNodeSchema,
794
- StartsWithNodeSchema,
795
- EndsWithNodeSchema,
796
- ContainsNodeSchema,
797
- // Logic
798
- NotNodeSchema,
799
- AndNodeSchema,
800
- OrNodeSchema,
801
- // Structure
802
- MergeNodeSchema,
803
- CoalesceNodeSchema,
804
- CaseNodeSchema,
805
- EntriesOfNodeSchema,
806
- KeyByNodeSchema,
807
- GroupByNodeSchema,
808
- // Object
809
- KeysNodeSchema,
810
- ValuesNodeSchema,
811
- FromEntriesNodeSchema,
812
- PickNodeSchema,
813
- OmitNodeSchema,
814
- TypeNodeSchema,
815
- LengthNodeSchema,
816
- // Time
817
- DateNodeSchema,
818
- DateAddNodeSchema,
819
- DateDiffNodeSchema,
820
- // Locale-aware formatting
821
- LocaleDateNodeSchema,
822
- LocaleMoneyNodeSchema,
823
- LocaleNumberNodeSchema,
824
- // Sugar
825
- SumNodeSchema,
826
- AvgNodeSchema,
827
- CountNodeSchema,
828
- MinNodeSchema,
829
- MaxNodeSchema,
830
- PluckNodeSchema,
831
- TakeNodeSchema,
832
- DropNodeSchema,
833
- MatchNodeSchema,
834
- FlatMapNodeSchema,
835
- // Transform (rewriting a document)
836
- HasNodeSchema,
837
- RenameKeysNodeSchema,
838
- UpdateNodeSchema,
839
- AssertNodeSchema,
840
- WalkNodeSchema,
841
- // Primitives
889
+ ...OP_MEMBERS,
842
890
  JsonPrimitiveSchema,
843
- // Arrays of nodes
844
891
  NodeArraySchema,
845
- // Plain objects (no `$` keys, recursive values)
846
892
  TemplateSchema
847
893
  ] }).describe("A Prism node: an op, a plain JSON value, an array of nodes, or a plain object template.")
848
894
  );
895
+ var isMember = (value) => typeof value === "object" && value !== null && "_zod" in value;
896
+ var shapeOf = (schema) => {
897
+ const { def } = schema._zod;
898
+ const inner = (key) => {
899
+ const value = Reflect.get(def, key);
900
+ return isMember(value) ? shapeOf(value) : "<any JSON>";
901
+ };
902
+ const list = (key) => {
903
+ const value = Reflect.get(def, key);
904
+ return Array.isArray(value) ? value.filter(isMember) : [];
905
+ };
906
+ switch (def.type) {
907
+ case "lazy": {
908
+ const getter = Reflect.get(def, "getter");
909
+ return typeof getter === "function" && getter() === NodeSchema ? "<node>" : "<any JSON>";
910
+ }
911
+ case "string":
912
+ return "<text>";
913
+ case "number":
914
+ return "<number>";
915
+ case "boolean":
916
+ return "true|false";
917
+ case "null":
918
+ return "null";
919
+ case "enum": {
920
+ const entries = Reflect.get(def, "entries");
921
+ return typeof entries === "object" && entries !== null ? Object.values(entries).map((v) => JSON.stringify(v)).join("|") : "<text>";
922
+ }
923
+ case "optional":
924
+ case "default":
925
+ case "nullable":
926
+ case "readonly":
927
+ case "prefault":
928
+ return inner("innerType");
929
+ case "array":
930
+ return `[${inner("element")}, \u2026]`;
931
+ case "tuple":
932
+ return `[${list("items").map(shapeOf).join(", ")}]`;
933
+ case "union":
934
+ return list("options").map(shapeOf).join(" or ");
935
+ case "record":
936
+ return `{<name>: ${inner("valueType")}}`;
937
+ case "object": {
938
+ const shape = Reflect.get(def, "shape");
939
+ if (typeof shape !== "object" || shape === null) return "{\u2026}";
940
+ const fields = Object.entries(shape).filter((entry) => isMember(entry[1])).map(([key, field]) => {
941
+ const optional = field._zod.def.type === "optional" || field._zod.def.type === "default";
942
+ return `"${key}"${optional ? "?" : ""}: ${shapeOf(field)}`;
943
+ });
944
+ return `{${fields.join(", ")}}`;
945
+ }
946
+ default:
947
+ return `<${def.type}>`;
948
+ }
949
+ };
950
+ var forms;
951
+ var formOf = (op) => {
952
+ forms ??= opMembersOf(OP_MEMBERS);
953
+ const member = forms.get(op);
954
+ const shape = member === void 0 ? void 0 : Reflect.get(member._zod.def, "shape");
955
+ const field = typeof shape === "object" && shape !== null ? Reflect.get(shape, op) : void 0;
956
+ return isMember(field) ? `{"${op}": ${shapeOf(field)}}` : void 0;
957
+ };
849
958
  setNodeSchema(NodeSchema);
850
959
  setNodeSchema2(NodeSchema);
851
960
  setNodeSchema3(NodeSchema);
@@ -862,6 +971,6 @@ var ConfigSchema = NodeSchema.describe(
862
971
  "A Prism config: the top-level transformation definition. Can be any valid node."
863
972
  );
864
973
 
865
- export { ConfigSchema, ErrorCode, NodeSchema, OPTIONAL_FIELDS_KEY, OP_KEYS, PrismError, getByPath, isAddNode, isAndNode, isAssertNode, isAvgNode, isCaseNode, isCoalesceNode, isConstNode, isContainsNode, isCountNode, isDateAddNode, isDateDiffNode, isDateNode, isDivNode, isDropNode, isEmptyNode, isEndsWithNode, isEntriesOfNode, isEqNode, isFillNode, isFilterNode, isFlatMapNode, isFlattenNode, isFromEntriesNode, isGetNode, isGroupByNode, isGtNode, isGteNode, isHasNode, isInterpolateNode, isJoinNode, isJsonArray, isJsonObject, isKeyByNode, isKeysNode, isLengthNode, isLocaleDateNode, isLocaleMoneyNode, isLocaleNumberNode, isLowerNode, isLtNode, isLteNode, isMapNode, isMatchNode, isMaxNode, isMergeNode, isMinNode, isModNode, isMulNode, isNeqNode, isNotNode, isOmitNode, isOrNode, isPickNode, isPlainObject, isPluckNode, isReduceNode, isRefNode, isRenameKeysNode, isReplaceNode, isRoundNode, isSliceNode, isSortByNode, isSplitNode, isStartsWithNode, isSubNode, isSumNode, isTakeNode, isToNumberNode, isToStringNode, isTrimNode, isTypeNode, isUniqueNode, isUpdateNode, isUpperNode, isValuesNode, isVarNode, isWalkNode, isWithNode, parseJsonPath, parseJsonPathCached };
866
- //# sourceMappingURL=chunk-7VMFSXBM.js.map
867
- //# sourceMappingURL=chunk-7VMFSXBM.js.map
974
+ export { ConfigSchema, ErrorCode, INDEX_TEXT, NodeSchema, OPTIONAL_FIELDS_KEY, OP_KEYS, PrismError, clip, describeValue, failAt, formOf, getByPath, isAddNode, isAndNode, isAssertNode, isAvgNode, isCaseNode, isCoalesceNode, isConstNode, isContainsNode, isCountNode, isDateAddNode, isDateDiffNode, isDateNode, isDivNode, isDropNode, isEmptyNode, isEndsWithNode, isEntriesOfNode, isEqNode, isFillNode, isFilterNode, isFlatMapNode, isFlattenNode, isFromEntriesNode, isGetNode, isGroupByNode, isGtNode, isGteNode, isHasNode, isInterpolateNode, isJoinNode, isJsonArray, isJsonObject, isKeyByNode, isKeysNode, isLengthNode, isLocaleDateNode, isLocaleMoneyNode, isLocaleNumberNode, isLowerNode, isLtNode, isLteNode, isMapNode, isMatchNode, isMaxNode, isMergeNode, isMinNode, isModNode, isMulNode, isNeqNode, isNotNode, isOmitNode, isOrNode, isPickNode, isPlainObject, isPluckNode, isReduceNode, isRefNode, isRenameKeysNode, isReplaceNode, isRoundNode, isSliceNode, isSortByNode, isSplitNode, isStartsWithNode, isSubNode, isSumNode, isTakeNode, isToNumberNode, isToStringNode, isTrimNode, isTypeNode, isUniqueNode, isUpdateNode, isUpperNode, isValuesNode, isVarNode, isWalkNode, isWithNode, jsonPathUpTo, parseJsonPath, parseJsonPathCached, takeOrigin, whereStopped };
975
+ //# sourceMappingURL=chunk-OL4CCYWX.js.map
976
+ //# sourceMappingURL=chunk-OL4CCYWX.js.map