@amritk/helpers 0.14.0 → 0.15.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.
Files changed (65) hide show
  1. package/AI.md +13 -5
  2. package/README.md +4 -1
  3. package/dist/assert-id-scopes.d.ts +20 -0
  4. package/dist/assert-id-scopes.js +45 -0
  5. package/dist/build-anchor-map.d.ts +26 -0
  6. package/dist/build-anchor-map.js +35 -0
  7. package/dist/build-dynamic-ref-map.d.ts +8 -0
  8. package/dist/build-dynamic-ref-map.js +7 -5
  9. package/dist/build-resource-registry.d.ts +88 -0
  10. package/dist/build-resource-registry.js +90 -0
  11. package/dist/escape-regex-pattern.d.ts +27 -0
  12. package/dist/escape-regex-pattern.js +21 -1
  13. package/dist/extract-refs.js +6 -4
  14. package/dist/generate-index-barrel.js +13 -6
  15. package/dist/generate-type-definition.js +1 -4
  16. package/dist/graft-external-schemas.d.ts +83 -0
  17. package/dist/graft-external-schemas.js +70 -0
  18. package/dist/max-schema-depth.d.ts +22 -0
  19. package/dist/max-schema-depth.js +10 -0
  20. package/dist/mjst-extension.d.ts +4 -2
  21. package/dist/mjst-extension.js +11 -2
  22. package/dist/multiple-of-check.d.ts +31 -0
  23. package/dist/multiple-of-check.js +6 -10
  24. package/dist/normalize-ref-scopes.d.ts +29 -0
  25. package/dist/normalize-ref-scopes.js +53 -0
  26. package/dist/prune-external-schemas.d.ts +16 -0
  27. package/dist/prune-external-schemas.js +80 -0
  28. package/dist/ref-to-filename.d.ts +1 -0
  29. package/dist/ref-to-filename.js +19 -3
  30. package/dist/ref-to-name.js +7 -4
  31. package/dist/resolve-dynamic-refs.d.ts +10 -0
  32. package/dist/resolve-dynamic-refs.js +18 -16
  33. package/dist/resolve-ref.d.ts +4 -2
  34. package/dist/resolve-ref.js +32 -6
  35. package/dist/resolve-scoped-ref.d.ts +35 -0
  36. package/dist/resolve-scoped-ref.js +35 -0
  37. package/dist/safe-accessor.d.ts +38 -1
  38. package/dist/safe-accessor.js +15 -0
  39. package/dist/string-length-check.d.ts +8 -0
  40. package/dist/string-length-check.js +23 -0
  41. package/dist/upgrade-draft07-schema.js +9 -6
  42. package/dist/walk-ref-graph.d.ts +38 -3
  43. package/dist/walk-ref-graph.js +170 -23
  44. package/package.json +13 -3
  45. package/src/build-dynamic-ref-map.ts +0 -61
  46. package/src/derive-root-type-name.ts +0 -54
  47. package/src/escape-regex-pattern.ts +0 -87
  48. package/src/extract-dynamic-anchor-defs.ts +0 -25
  49. package/src/extract-refs.ts +0 -73
  50. package/src/fold-nullable.ts +0 -60
  51. package/src/generate-index-barrel.ts +0 -118
  52. package/src/generate-type-definition.ts +0 -784
  53. package/src/mjst-extension.ts +0 -81
  54. package/src/multiple-of-check.ts +0 -32
  55. package/src/parse-documentation.ts +0 -177
  56. package/src/quote-js-string.ts +0 -20
  57. package/src/ref-to-filename.ts +0 -116
  58. package/src/ref-to-name.ts +0 -54
  59. package/src/resolve-dynamic-refs.ts +0 -74
  60. package/src/resolve-ref.ts +0 -82
  61. package/src/safe-accessor.ts +0 -53
  62. package/src/schema-guards.ts +0 -234
  63. package/src/unknown-key-check.ts +0 -68
  64. package/src/upgrade-draft07-schema.ts +0 -179
  65. package/src/walk-ref-graph.ts +0 -257
@@ -0,0 +1,35 @@
1
+ import { resolveUri } from "./build-resource-registry.js";
2
+ const isPointerFragment = (fragment) => fragment === "" || fragment.startsWith("/");
3
+ const baseInScopeAt = (registry, pointer) => {
4
+ let base = registry.rootBase;
5
+ let matched = -1;
6
+ for (const [at, candidate] of registry.baseAt) {
7
+ if (at.length <= matched)
8
+ continue;
9
+ if (pointer === at || pointer.startsWith(at === "" ? "/" : `${at}/`)) {
10
+ base = candidate;
11
+ matched = at.length;
12
+ }
13
+ }
14
+ return base;
15
+ };
16
+ const resolveScopedRef = (registry, ref, base) => {
17
+ const absolute = resolveUri(ref, base);
18
+ if (absolute === void 0)
19
+ return void 0;
20
+ const hash = absolute.indexOf("#");
21
+ const uri = hash === -1 ? absolute : absolute.slice(0, hash);
22
+ const fragment = hash === -1 ? "" : absolute.slice(hash + 1);
23
+ const resource = registry.resources.get(uri);
24
+ if (resource === void 0)
25
+ return void 0;
26
+ if (!isPointerFragment(fragment)) {
27
+ const anchored = registry.anchors.get(`${uri}#${fragment}`);
28
+ return anchored === void 0 ? void 0 : { pointer: anchored, base: baseInScopeAt(registry, anchored) };
29
+ }
30
+ const pointer = `${resource}${fragment}`;
31
+ return { pointer, base: baseInScopeAt(registry, pointer) };
32
+ };
33
+ export {
34
+ resolveScopedRef
35
+ };
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * Generates a safe property accessor for a given key on an object variable.
3
3
  * Uses dot notation for simple identifiers and bracket notation for keys
4
- * that contain special characters like hyphens.
4
+ * that contain special characters like hyphens. Keys that collide with an
5
+ * `Object.prototype` member get an own-property guard (see
6
+ * {@link PROTOTYPE_MEMBERS}) so an inherited value never masquerades as input.
5
7
  *
6
8
  * @param variable - The variable name (e.g., "input", "input?")
7
9
  * @param key - The property name to access
@@ -11,8 +13,43 @@
11
13
  * safeAccessor("input", "name") // "input.name"
12
14
  * safeAccessor("input?", "x-linkedin") // 'input?.["x-linkedin"]'
13
15
  * safeAccessor("input", "x-linkedin") // 'input["x-linkedin"]'
16
+ * safeAccessor("input", "constructor")
17
+ * // '(input != null && Object.hasOwn(input, "constructor") ? input["constructor"] : undefined)'
14
18
  */
15
19
  export declare const safeAccessor: (variable: string, key: string) => string;
20
+ /**
21
+ * Generates the expression that is TRUE when `key` is present on the object held
22
+ * in `variable` — present as an *own* property, never inherited.
23
+ *
24
+ * For an `Object.prototype` name a bare `"key" in obj` was the obvious spelling
25
+ * and the wrong one: `in` walks the prototype chain, so `"toString" in obj` is
26
+ * true for every object and a `required: ["toString"]` could never be reported
27
+ * missing. Those names get `Object.hasOwn`, which asks the question `required` /
28
+ * `dependentRequired` / `dependentSchemas` actually mean.
29
+ *
30
+ * Every *other* name keeps `in`, because for them the two agree and the
31
+ * difference is not free. `Object.hasOwn` is a call the engine cannot fold into
32
+ * an inline cache the way it folds `in`, and a JSON document's object never
33
+ * inherits `id` or `name`, so paying for that question at every site buys
34
+ * nothing. This is the same split {@link safeAccessor} makes on the read side.
35
+ *
36
+ * The result binds tighter than `&&`, so it drops straight into a conjunction.
37
+ * It is *not* safe under a bare `!` — `!"k" in obj` parses as `(!"k") in obj` —
38
+ * so negate it with {@link missingCheck} rather than by hand.
39
+ *
40
+ * @example
41
+ * hasOwnCheck("input", "name") // '"name" in input'
42
+ * hasOwnCheck("input", "toString") // 'Object.hasOwn(input, "toString")'
43
+ */
44
+ export declare const hasOwnCheck: (variable: string, key: string) => string;
45
+ /**
46
+ * Generates the expression that is TRUE when `key` is absent — the negation of
47
+ * {@link hasOwnCheck}, with the parentheses `in` needs under a `!`.
48
+ *
49
+ * @example
50
+ * missingCheck("input", "name") // '!("name" in input)'
51
+ */
52
+ export declare const missingCheck: (variable: string, key: string) => string;
16
53
  /**
17
54
  * Generates a safe property key for use in object literals.
18
55
  * Wraps keys that are not valid identifiers in quotes.
@@ -1,5 +1,11 @@
1
1
  const JS_IDENTIFIER = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
2
+ const PROTOTYPE_MEMBERS = new Set(Object.getOwnPropertyNames(Object.prototype));
2
3
  const safeAccessor = (variable, key) => {
4
+ if (PROTOTYPE_MEMBERS.has(key)) {
5
+ const base = variable.endsWith("?") ? variable.slice(0, -1) : variable;
6
+ const literal2 = JSON.stringify(key);
7
+ return `(${base} != null && Object.hasOwn(${base}, ${literal2}) ? ${base}[${literal2}] : undefined)`;
8
+ }
3
9
  if (JS_IDENTIFIER.test(key)) {
4
10
  return `${variable}.${key}`;
5
11
  }
@@ -9,6 +15,13 @@ const safeAccessor = (variable, key) => {
9
15
  }
10
16
  return `${variable}[${literal}]`;
11
17
  };
18
+ const hasOwnCheck = (variable, key) => {
19
+ const literal = JSON.stringify(key);
20
+ if (PROTOTYPE_MEMBERS.has(key))
21
+ return `Object.hasOwn(${variable}, ${literal})`;
22
+ return `${literal} in ${variable}`;
23
+ };
24
+ const missingCheck = (variable, key) => `!(${hasOwnCheck(variable, key)})`;
12
25
  const safeKey = (key) => {
13
26
  if (JS_IDENTIFIER.test(key)) {
14
27
  return key;
@@ -16,6 +29,8 @@ const safeKey = (key) => {
16
29
  return JSON.stringify(key);
17
30
  };
18
31
  export {
32
+ hasOwnCheck,
33
+ missingCheck,
19
34
  safeAccessor,
20
35
  safeKey
21
36
  };
@@ -0,0 +1,8 @@
1
+ /** Boolean expression that is TRUE when `valueExpr` has at least `min` code points. */
2
+ export declare const minLengthPassExpr: (valueExpr: string, min: number) => string;
3
+ /** Boolean expression that is TRUE when `valueExpr` has at most `max` code points. */
4
+ export declare const maxLengthPassExpr: (valueExpr: string, max: number) => string;
5
+ /** Boolean expression that is TRUE when `valueExpr` has FEWER than `min` code points (the error condition). */
6
+ export declare const minLengthFailExpr: (valueExpr: string, min: number) => string;
7
+ /** Boolean expression that is TRUE when `valueExpr` has MORE than `max` code points (the error condition). */
8
+ export declare const maxLengthFailExpr: (valueExpr: string, max: number) => string;
@@ -0,0 +1,23 @@
1
+ const codePoints = (valueExpr) => `Array.from(${valueExpr} as string).length`;
2
+ const minLengthPassExpr = (valueExpr, min) => {
3
+ if (min <= 0)
4
+ return "true";
5
+ if (min === 1)
6
+ return `${valueExpr}.length >= 1`;
7
+ return `(${valueExpr}.length >= ${min} && (${valueExpr}.length >= ${min * 2} || ${codePoints(valueExpr)} >= ${min}))`;
8
+ };
9
+ const maxLengthPassExpr = (valueExpr, max) => `(${valueExpr}.length <= ${max} || ${codePoints(valueExpr)} <= ${max})`;
10
+ const minLengthFailExpr = (valueExpr, min) => {
11
+ if (min <= 0)
12
+ return "false";
13
+ if (min === 1)
14
+ return `${valueExpr}.length < 1`;
15
+ return `(${valueExpr}.length < ${min} || (${valueExpr}.length < ${min * 2} && ${codePoints(valueExpr)} < ${min}))`;
16
+ };
17
+ const maxLengthFailExpr = (valueExpr, max) => `(${valueExpr}.length > ${max} && ${codePoints(valueExpr)} > ${max})`;
18
+ export {
19
+ maxLengthFailExpr,
20
+ maxLengthPassExpr,
21
+ minLengthFailExpr,
22
+ minLengthPassExpr
23
+ };
@@ -1,10 +1,12 @@
1
+ import { assertSchemaDepth } from "./max-schema-depth.js";
1
2
  import { refToFilename, toKebabCase } from "./ref-to-filename.js";
2
3
  const isDraft07Schema = (schema) => typeof schema["$schema"] === "string" && schema["$schema"].includes("draft-07");
3
- const rewriteRefs = (obj, refMap, selfRef) => {
4
+ const rewriteRefs = (obj, refMap, selfRef, depth = 0) => {
5
+ assertSchemaDepth(depth, "upgradeDraft07Schema");
4
6
  if (typeof obj !== "object" || obj === null)
5
7
  return obj;
6
8
  if (Array.isArray(obj))
7
- return obj.map((item) => rewriteRefs(item, refMap, selfRef));
9
+ return obj.map((item) => rewriteRefs(item, refMap, selfRef, depth + 1));
8
10
  const record = obj;
9
11
  const result = {};
10
12
  for (const [key, value] of Object.entries(record)) {
@@ -17,7 +19,7 @@ const rewriteRefs = (obj, refMap, selfRef) => {
17
19
  result[key] = value;
18
20
  }
19
21
  } else {
20
- result[key] = rewriteRefs(value, refMap, selfRef);
22
+ result[key] = rewriteRefs(value, refMap, selfRef, depth + 1);
21
23
  }
22
24
  }
23
25
  return result;
@@ -74,11 +76,12 @@ const upgradeDraft07Schema = (schema) => {
74
76
  $defs: hoistedDefs
75
77
  };
76
78
  };
77
- const renameNestedDefs = (obj) => {
79
+ const renameNestedDefs = (obj, depth = 0) => {
80
+ assertSchemaDepth(depth, "upgradeDraft07Schema");
78
81
  if (typeof obj !== "object" || obj === null)
79
82
  return obj;
80
83
  if (Array.isArray(obj))
81
- return obj.map(renameNestedDefs);
84
+ return obj.map((item) => renameNestedDefs(item, depth + 1));
82
85
  const record = obj;
83
86
  const result = {};
84
87
  for (const [key, value] of Object.entries(record)) {
@@ -86,7 +89,7 @@ const renameNestedDefs = (obj) => {
86
89
  result[key] = value.replace("#/definitions/", "#/$defs/");
87
90
  } else {
88
91
  const outKey = key === "definitions" ? "$defs" : key;
89
- result[outKey] = renameNestedDefs(value);
92
+ result[outKey] = renameNestedDefs(value, depth + 1);
90
93
  }
91
94
  }
92
95
  return result;
@@ -32,6 +32,29 @@ export type WalkRefGraphOptions = {
32
32
  * Defaults to `''`.
33
33
  */
34
34
  readonly typeSuffix?: string;
35
+ /**
36
+ * Other schema documents you have **already loaded**, keyed by the absolute
37
+ * URI a `$ref` names them by. Supplying them makes those URIs resolvable, so
38
+ * the schema being generated can reference a document that is not itself.
39
+ *
40
+ * Nothing here fetches: the walker cannot be told a URL, only a document, so
41
+ * generation stays a pure function of its inputs. Loading is yours to do (or
42
+ * `@amritk/resolve-refs`'), and however you do it the result comes back
43
+ * through here. A `$ref` to a URI nobody registered is still refused.
44
+ *
45
+ * Each registered document is a schema resource like any other — its `$id`,
46
+ * `$anchor`s, `$dynamicAnchor`s and nested embedded resources all become
47
+ * resolvable, and a `$ref` from one registered document into another resolves
48
+ * too. A document with no `$id` resolves its relative `$ref`s against the URI
49
+ * you registered it under, and one whose `$id` disagrees answers to both. See
50
+ * {@link graftExternalSchemas}.
51
+ *
52
+ * Only the documents actually reached get files, so registering more than the
53
+ * schema uses costs nothing in the output. Treat the map and the documents in
54
+ * it as immutable once passed: walks are memoized per `(schema, schemas)` by
55
+ * identity, so hand over a *new* object when the set of documents changes.
56
+ */
57
+ readonly schemas?: Readonly<Record<string, unknown>>;
35
58
  };
36
59
  /**
37
60
  * Walks a JSON Schema and its entire `$ref` / `$dynamicRef` graph, invoking
@@ -43,8 +66,20 @@ export type WalkRefGraphOptions = {
43
66
  * ref, rewritten `$dynamicRef` to `$ref`, and derived the type/file names — so
44
67
  * callers only have to turn `node.schema` into file content. Definitions
45
68
  * reachable only via `$dynamicAnchor` are seeded too, so nothing the generated
46
- * code imports goes ungenerated. A ref that fails to resolve is reported via
47
- * `console.warn` and skipped, matching the generators' prior behavior.
69
+ * code imports goes ungenerated.
70
+ *
71
+ * The walker throws rather than degrading whenever it cannot produce output that
72
+ * would actually work: an unresolvable `$ref`, a `$dynamicRef` with no anchor to
73
+ * bind to, or two definitions that reduce to one filename or one type name. Each
74
+ * of those used to warn (or say nothing) and carry on, which meant `mjst` exited
75
+ * 0 having written TypeScript that either does not compile or — worse — compiles
76
+ * to the wrong type.
77
+ *
78
+ * A `$ref` whose target is another document resolves when that document is
79
+ * handed over through {@link WalkRefGraphOptions.schemas} — the walker folds the
80
+ * registered documents into the one it is walking, so cross-document refs become
81
+ * ordinary pointers and get files and type names by the same rules as everything
82
+ * else. Nothing is ever fetched; a URI nobody registered is still refused.
48
83
  *
49
84
  * Resolution work is memoized per root document (see {@link RootCache}), so
50
85
  * running several generators over the same loaded schema does the expensive
@@ -52,7 +87,7 @@ export type WalkRefGraphOptions = {
52
87
  *
53
88
  * @param rootSchema - The root JSON Schema to walk.
54
89
  * @param rootTypeName - The name for the root type (e.g. `'Document'`).
55
- * @param options - Naming options ({@link WalkRefGraphOptions}).
90
+ * @param options - Naming and registry options ({@link WalkRefGraphOptions}).
56
91
  * @param visit - Called once per output file with a fully prepared {@link RefNode}.
57
92
  */
58
93
  export declare const walkRefGraph: (rootSchema: JSONSchema, rootTypeName: string, options: WalkRefGraphOptions, visit: (node: RefNode) => void) => void;
@@ -1,11 +1,18 @@
1
+ import { assertIdScopes } from "./assert-id-scopes.js";
1
2
  import { buildDynamicRefMap } from "./build-dynamic-ref-map.js";
2
3
  import { extractRefs } from "./extract-refs.js";
4
+ import { graftExternalSchemas } from "./graft-external-schemas.js";
5
+ import { normalizeRefScopes } from "./normalize-ref-scopes.js";
6
+ import { pruneExternalSchemas } from "./prune-external-schemas.js";
3
7
  import { refToFilename } from "./ref-to-filename.js";
4
8
  import { refToName } from "./ref-to-name.js";
5
9
  import { resolveDynamicRefs } from "./resolve-dynamic-refs.js";
6
10
  import { resolveRef } from "./resolve-ref.js";
7
11
  import { upgradeDraft07Schema } from "./upgrade-draft07-schema.js";
8
12
  const rootCaches = /* @__PURE__ */ new WeakMap();
13
+ const registryCaches = /* @__PURE__ */ new WeakMap();
14
+ const ROOT_POINTER = "#";
15
+ const sameDefinition = (a, b) => a === b || JSON.stringify(a) === JSON.stringify(b);
9
16
  const SHAPE_KEYWORDS = [
10
17
  "properties",
11
18
  "type",
@@ -32,24 +39,139 @@ const getAliasRootRef = (schema) => {
32
39
  return null;
33
40
  return SHAPE_KEYWORDS.some((key) => key in record) ? null : record["$ref"];
34
41
  };
35
- const getRootCache = (rootSchema) => {
42
+ const DEFINITION_MAP_KEYS = ["$defs", "definitions"];
43
+ const expandBooleanDefinitions = (value) => {
44
+ if (typeof value !== "object" || value === null)
45
+ return value;
46
+ if (Array.isArray(value)) {
47
+ const mapped = value.map(expandBooleanDefinitions);
48
+ return mapped.some((item, index) => item !== value[index]) ? mapped : value;
49
+ }
50
+ const record = value;
51
+ let changed = false;
52
+ const result = {};
53
+ for (const [key, sub] of Object.entries(record)) {
54
+ const next = DEFINITION_MAP_KEYS.includes(key) ? expandDefinitionMap(sub) : expandBooleanDefinitions(sub);
55
+ if (next !== sub)
56
+ changed = true;
57
+ result[key] = next;
58
+ }
59
+ return changed ? result : value;
60
+ };
61
+ const expandDefinitionMap = (definitions) => {
62
+ if (typeof definitions !== "object" || definitions === null || Array.isArray(definitions))
63
+ return definitions;
64
+ const record = definitions;
65
+ let changed = false;
66
+ const result = {};
67
+ for (const [name, definition] of Object.entries(record)) {
68
+ const next = definition === true ? {} : definition === false ? { not: {} } : expandBooleanDefinitions(definition);
69
+ if (next !== definition)
70
+ changed = true;
71
+ result[name] = next;
72
+ }
73
+ return changed ? result : definitions;
74
+ };
75
+ const getRootCache = (rootSchema, schemas) => {
36
76
  if (typeof rootSchema !== "object" || rootSchema === null) {
37
77
  const upgraded2 = rootSchema;
38
- return { upgraded: upgraded2, dynamicRefMap: {}, resolveRefCache: /* @__PURE__ */ new Map(), extractRefsCache: /* @__PURE__ */ new WeakMap() };
78
+ return {
79
+ upgraded: upgraded2,
80
+ dynamicRefMap: {},
81
+ resolveRefCache: /* @__PURE__ */ new Map(),
82
+ extractRefsCache: /* @__PURE__ */ new WeakMap(),
83
+ rootAnchored: /* @__PURE__ */ new Map()
84
+ };
39
85
  }
40
- const existing = rootCaches.get(rootSchema);
41
- if (existing)
42
- return existing;
43
- const upgraded = upgradeDraft07Schema(rootSchema);
86
+ const registry = schemas !== void 0 && Object.keys(schemas).length > 0 ? schemas : void 0;
87
+ const cached = registry === void 0 ? rootCaches.get(rootSchema) : registryCaches.get(rootSchema)?.get(registry);
88
+ if (cached)
89
+ return cached;
90
+ const grafted = registry === void 0 ? void 0 : graftExternalSchemas(rootSchema, registry);
91
+ const combined = grafted?.document ?? rootSchema;
92
+ const expanded = expandBooleanDefinitions(upgradeDraft07Schema(combined));
93
+ assertIdScopes(expanded);
94
+ const normalized = normalizeRefScopes(expanded);
95
+ const upgraded = grafted === void 0 ? normalized : pruneExternalSchemas(normalized, grafted.names);
44
96
  const cache = {
45
97
  upgraded,
46
98
  dynamicRefMap: buildDynamicRefMap(upgraded),
47
99
  resolveRefCache: /* @__PURE__ */ new Map(),
48
- extractRefsCache: /* @__PURE__ */ new WeakMap()
100
+ extractRefsCache: /* @__PURE__ */ new WeakMap(),
101
+ rootAnchored: /* @__PURE__ */ new Map()
49
102
  };
50
- rootCaches.set(rootSchema, cache);
103
+ if (registry === void 0)
104
+ rootCaches.set(rootSchema, cache);
105
+ else {
106
+ const byRegistry = registryCaches.get(rootSchema) ?? /* @__PURE__ */ new WeakMap();
107
+ byRegistry.set(registry, cache);
108
+ registryCaches.set(rootSchema, byRegistry);
109
+ }
51
110
  return cache;
52
111
  };
112
+ const referencesRoot = (value) => {
113
+ if (typeof value !== "object" || value === null)
114
+ return false;
115
+ if (Array.isArray(value))
116
+ return value.some(referencesRoot);
117
+ const record = value;
118
+ if (record["$ref"] === ROOT_POINTER || record["$ref"] === "#/")
119
+ return true;
120
+ for (const key in record)
121
+ if (referencesRoot(record[key]))
122
+ return true;
123
+ return false;
124
+ };
125
+ const rewriteRootRefs = (value, rootSelfRef) => {
126
+ if (typeof value !== "object" || value === null)
127
+ return value;
128
+ if (Array.isArray(value))
129
+ return value.map((item) => rewriteRootRefs(item, rootSelfRef));
130
+ const out = {};
131
+ for (const [key, sub] of Object.entries(value)) {
132
+ out[key] = key === "$ref" && (sub === ROOT_POINTER || sub === "#/") ? rootSelfRef : rewriteRootRefs(sub, rootSelfRef);
133
+ }
134
+ return out;
135
+ };
136
+ const rootAnchoredCache = (base, rootFilename, rootSelfRef) => {
137
+ const cached = base.rootAnchored.get(rootFilename);
138
+ if (cached)
139
+ return cached;
140
+ const rewritten = referencesRoot(base.upgraded) ? rewriteRootRefs(base.upgraded, rootSelfRef) : base.upgraded;
141
+ const { $defs, ...rootBody } = rewritten;
142
+ const defs = typeof $defs === "object" && $defs !== null ? $defs : {};
143
+ if (Object.hasOwn(defs, rootFilename)) {
144
+ throw new Error(`The root schema declares a $dynamicAnchor, so its own definition is aliased as "${rootSelfRef}" \u2014 but "${rootFilename}" is already a definition in $defs. Rename one so each gets its own file.`);
145
+ }
146
+ const derived = {
147
+ upgraded: { ...rewritten, $defs: { ...defs, [rootFilename]: rootBody } },
148
+ dynamicRefMap: Object.fromEntries(Object.entries(base.dynamicRefMap).map(([anchor, pointer]) => [
149
+ anchor,
150
+ pointer === ROOT_POINTER ? rootSelfRef : pointer
151
+ ])),
152
+ resolveRefCache: /* @__PURE__ */ new Map(),
153
+ extractRefsCache: /* @__PURE__ */ new WeakMap(),
154
+ rootAnchored: /* @__PURE__ */ new Map()
155
+ };
156
+ base.rootAnchored.set(rootFilename, derived);
157
+ return derived;
158
+ };
159
+ const dynamicPointerRefs = (value, into = /* @__PURE__ */ new Set()) => {
160
+ if (typeof value !== "object" || value === null)
161
+ return into;
162
+ if (Array.isArray(value)) {
163
+ for (const item of value)
164
+ dynamicPointerRefs(item, into);
165
+ return into;
166
+ }
167
+ const record = value;
168
+ const ref = record["$dynamicRef"];
169
+ if (typeof ref === "string" && ref.startsWith("#/"))
170
+ into.add(ref);
171
+ for (const key in record)
172
+ dynamicPointerRefs(record[key], into);
173
+ return into;
174
+ };
53
175
  const cachedResolveRef = (cache, ref) => {
54
176
  if (cache.resolveRefCache.has(ref))
55
177
  return cache.resolveRefCache.get(ref);
@@ -69,24 +191,40 @@ const cachedExtractRefs = (cache, schema) => {
69
191
  };
70
192
  const walkRefGraph = (rootSchema, rootTypeName, options, visit) => {
71
193
  const typeSuffix = options.typeSuffix ?? "";
72
- const cache = getRootCache(rootSchema);
194
+ const baseCache = getRootCache(rootSchema, options.schemas);
195
+ const rootFilename = rootTypeName.toLowerCase();
196
+ const rootSelfRef = `#/$defs/${rootFilename}`;
197
+ const rootIsAnchored = Object.values(baseCache.dynamicRefMap).includes(ROOT_POINTER);
198
+ const rootIsSelfReferenced = referencesRoot(baseCache.upgraded);
199
+ const needsRootAlias = rootIsAnchored || rootIsSelfReferenced;
200
+ if (needsRootAlias && refToName(rootSelfRef, typeSuffix) !== rootTypeName) {
201
+ throw new Error(`The root schema is referenced by ${rootIsAnchored ? "a $dynamicAnchor" : 'a $ref to "#"'}, which is generated as the root's own file \u2014 but the root type name "${rootTypeName}" does not survive the round trip through ref naming (refs to it would be named "${refToName(rootSelfRef, typeSuffix)}"). Use a single-word root type name with no type suffix, or move the recursion onto a $defs entry.`);
202
+ }
203
+ const cache = needsRootAlias ? rootAnchoredCache(baseCache, rootFilename, rootSelfRef) : baseCache;
73
204
  const { upgraded, dynamicRefMap } = cache;
74
205
  const processedRefs = /* @__PURE__ */ new Set();
75
- const processedFilenames = /* @__PURE__ */ new Set();
76
206
  const filenameOwners = /* @__PURE__ */ new Map();
77
- const rootFilename = rootTypeName.toLowerCase();
78
- processedFilenames.add(rootFilename);
79
- filenameOwners.set(rootFilename, `the root type ${rootTypeName}`);
207
+ const typeNameOwners = /* @__PURE__ */ new Map();
80
208
  let rootNodeSchema = upgraded;
81
209
  let rootNodeRef;
210
+ let rootTarget = upgraded;
82
211
  const aliasRef = getAliasRootRef(upgraded);
83
212
  if (aliasRef && refToFilename(aliasRef) === rootFilename) {
84
213
  const resolved = cachedResolveRef(cache, aliasRef);
85
214
  if (resolved) {
86
215
  rootNodeSchema = resolved;
87
216
  rootNodeRef = aliasRef;
217
+ rootTarget = resolved;
218
+ processedRefs.add(aliasRef);
88
219
  }
89
220
  }
221
+ if (needsRootAlias) {
222
+ processedRefs.add(rootSelfRef);
223
+ rootNodeRef ??= rootSelfRef;
224
+ }
225
+ const rootOwner = { label: `the root type ${rootTypeName}`, resolved: rootTarget };
226
+ filenameOwners.set(rootFilename, rootOwner);
227
+ typeNameOwners.set(rootTypeName, rootOwner);
90
228
  visit({
91
229
  ref: rootNodeRef,
92
230
  typeName: rootTypeName,
@@ -95,7 +233,11 @@ const walkRefGraph = (rootSchema, rootTypeName, options, visit) => {
95
233
  rootSchema: upgraded,
96
234
  isRoot: true
97
235
  });
98
- const queue = [...cachedExtractRefs(cache, upgraded), ...Object.values(dynamicRefMap)];
236
+ const queue = [
237
+ ...cachedExtractRefs(cache, upgraded),
238
+ ...Object.values(dynamicRefMap),
239
+ ...[...dynamicPointerRefs(upgraded)].filter((ref) => cachedResolveRef(cache, ref) !== void 0)
240
+ ];
99
241
  for (let head = 0; head < queue.length; head++) {
100
242
  const ref = queue[head];
101
243
  if (!ref || processedRefs.has(ref))
@@ -103,21 +245,26 @@ const walkRefGraph = (rootSchema, rootTypeName, options, visit) => {
103
245
  processedRefs.add(ref);
104
246
  const resolved = cachedResolveRef(cache, ref);
105
247
  if (!resolved) {
106
- console.warn(`Warning: Could not resolve ref: ${ref}`);
107
- continue;
248
+ throw new Error(`Could not resolve $ref "${ref}". Nothing in the document defines it, so the generated output would reference a type and a function that are never emitted. Fix the ref, or drop it from the schema.`);
108
249
  }
109
250
  const filename = refToFilename(ref);
110
- if (processedFilenames.has(filename)) {
111
- const owner = filenameOwners.get(filename);
112
- if (owner !== void 0 && owner !== ref) {
113
- console.warn(`Warning: ${ref} and ${owner} both map to "${filename}.ts" \u2014 only ${owner} was generated, so every reference to the other resolves to the wrong type. Rename one so each gets its own file.`);
251
+ const typeName = refToName(ref, typeSuffix);
252
+ const fileOwner = filenameOwners.get(filename);
253
+ if (fileOwner) {
254
+ if (!sameDefinition(fileOwner.resolved, resolved)) {
255
+ throw new Error(`"${ref}" and ${fileOwner.label} both generate the file "${filename}.ts", so only one of them can be emitted and every reference to the other would resolve to the wrong type. Rename one definition.`);
114
256
  }
115
257
  } else {
116
- processedFilenames.add(filename);
117
- filenameOwners.set(filename, ref);
258
+ const typeOwner = typeNameOwners.get(typeName);
259
+ if (typeOwner) {
260
+ throw new Error(`"${ref}" and ${typeOwner.label} both generate the type name "${typeName}" from different files, so the generated output would import that name twice and fail to parse. Rename one definition.`);
261
+ }
262
+ const owner = { label: `"${ref}"`, resolved };
263
+ filenameOwners.set(filename, owner);
264
+ typeNameOwners.set(typeName, owner);
118
265
  visit({
119
266
  ref,
120
- typeName: refToName(ref, typeSuffix),
267
+ typeName,
121
268
  filename,
122
269
  schema: resolveDynamicRefs(resolved, dynamicRefMap),
123
270
  rootSchema: upgraded,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/helpers",
3
- "version": "0.14.0",
3
+ "version": "0.15.1",
4
4
  "description": "Shared utilities for the mjst code generation ecosystem.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -25,8 +25,10 @@
25
25
  },
26
26
  "files": [
27
27
  "dist",
28
- "src/**/*.ts",
29
- "!src/**/*.test.ts",
28
+ "src/has-ref.ts",
29
+ "src/is-object.ts",
30
+ "src/validate-array.ts",
31
+ "src/validate-record.ts",
30
32
  "AI.md"
31
33
  ],
32
34
  "publishConfig": {
@@ -34,6 +36,7 @@
34
36
  },
35
37
  "scripts": {
36
38
  "build": "tsgo -p tsconfig.build.json && tsc-alias -p tsconfig.build.json -f && node ../../scripts/strip-comments.mjs",
39
+ "prepublishOnly": "node ../../scripts/check-publishable.mjs",
37
40
  "types:check": "tsgo -p . --noEmit",
38
41
  "test": "NODE_ENV=production vitest run --root ../.. helpers"
39
42
  },
@@ -47,5 +50,12 @@
47
50
  "import": "./dist/*.js",
48
51
  "default": "./dist/*.js"
49
52
  }
53
+ },
54
+ "typesVersions": {
55
+ "*": {
56
+ "*": [
57
+ "./dist/*.d.ts"
58
+ ]
59
+ }
50
60
  }
51
61
  }
@@ -1,61 +0,0 @@
1
- import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
2
-
3
- import { isSchemaObject } from './schema-guards'
4
-
5
- /** Escapes a JSON Pointer segment (RFC 6901): `~` → `~0`, `/` → `~1`. */
6
- const escapeSegment = (segment: string): string =>
7
- segment.indexOf('~') !== -1 || segment.indexOf('/') !== -1
8
- ? segment.replace(/~/g, '~0').replace(/\//g, '~1')
9
- : segment
10
-
11
- // Keywords whose values are data, not subschemas — a `$dynamicAnchor` key inside
12
- // an enum member or example value is instance data and must not register.
13
- const NON_SCHEMA_KEYWORDS = new Set(['enum', 'const', 'default', 'examples'])
14
-
15
- /**
16
- * Builds a map of $dynamicRef anchor values to their corresponding $ref paths.
17
- *
18
- * JSON Schema 2020-12 uses $dynamicAnchor and $dynamicRef for late-binding references.
19
- * In the OpenAPI spec, $dynamicAnchor: "meta" on the schema definition allows properties
20
- * like media-type.schema to reference it via $dynamicRef: "#meta".
21
- *
22
- * The whole document is scanned — a `$dynamicAnchor` may sit anywhere, not just
23
- * on a direct `$defs` entry — and each anchor maps to the JSON Pointer of the
24
- * subschema that declares it. When the same anchor name appears more than once,
25
- * the first occurrence in document order wins, matching how the resolvers bind
26
- * a name to a single document-global target.
27
- *
28
- * @example
29
- * // Given a schema with $defs.schema having $dynamicAnchor: "meta"
30
- * buildDynamicRefMap(rootSchema)
31
- * // Returns: { "#meta": "#/$defs/schema" }
32
- */
33
- export const buildDynamicRefMap = (rootSchema: JSONSchema): Record<string, string> => {
34
- const map: Record<string, string> = {}
35
- if (!isSchemaObject(rootSchema)) return map
36
-
37
- const walk = (node: unknown, pointer: string): void => {
38
- if (node === null || typeof node !== 'object') return
39
- if (Array.isArray(node)) {
40
- for (let i = 0; i < node.length; i++) walk(node[i], `${pointer}/${i}`)
41
- return
42
- }
43
-
44
- const record = node as Record<string, unknown>
45
- const anchor = record['$dynamicAnchor']
46
- // The document root is skipped: mapping it would rewrite `$dynamicRef` to
47
- // `$ref: "#"`, a self-reference the file-per-definition generators cannot
48
- // name an output file for. Every nested subschema gets a real pointer.
49
- if (pointer !== '' && typeof anchor === 'string' && !(`#${anchor}` in map)) {
50
- map[`#${anchor}`] = `#${pointer}`
51
- }
52
-
53
- for (const key of Object.keys(record)) {
54
- if (NON_SCHEMA_KEYWORDS.has(key)) continue
55
- walk(record[key], `${pointer}/${escapeSegment(key)}`)
56
- }
57
- }
58
-
59
- walk(rootSchema, '')
60
- return map
61
- }