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