@amritk/helpers 0.15.2 → 0.15.4

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.
@@ -1,19 +1,20 @@
1
- import { buildResourceRegistry, DATA_KEYWORDS, escapePointerSegment } from "./build-resource-registry.js";
1
+ import { buildResourceRegistry, entersSchemaMap, escapePointerSegment, isDataPosition } from "./build-resource-registry.js";
2
2
  import { assertSchemaDepth } from "./max-schema-depth.js";
3
+ import { readKey } from "./read-key.js";
3
4
  import { resolveRef } from "./resolve-ref.js";
4
5
  import { resolveScopedRef } from "./resolve-scoped-ref.js";
5
- const declaresLocalTargets = (record) => typeof record["$defs"] === "object" || typeof record["definitions"] === "object" || typeof record["$anchor"] === "string";
6
+ const declaresLocalTargets = (record) => typeof readKey(record, "$defs") === "object" || typeof readKey(record, "definitions") === "object" || typeof readKey(record, "$anchor") === "string";
6
7
  const assertIdScopes = (rootSchema) => {
7
8
  const registry = buildResourceRegistry(rootSchema);
8
9
  if (registry === null)
9
10
  return;
10
- const walk = (node, pointer, enclosing, resource, depth) => {
11
+ const walk = (node, pointer, enclosing, resource, depth, inSchemaMap) => {
11
12
  assertSchemaDepth(depth, "assertIdScopes");
12
13
  if (node === null || typeof node !== "object")
13
14
  return;
14
15
  if (Array.isArray(node)) {
15
16
  for (let index = 0; index < node.length; index++) {
16
- walk(node[index], `${pointer}/${index}`, enclosing, resource, depth + 1);
17
+ walk(node[index], `${pointer}/${index}`, enclosing, resource, depth + 1, inSchemaMap);
17
18
  }
18
19
  return;
19
20
  }
@@ -22,7 +23,7 @@ const assertIdScopes = (rootSchema) => {
22
23
  const base = declared ?? enclosing;
23
24
  const scope = declared !== void 0 && pointer !== "" ? record : resource;
24
25
  for (const key of ["$ref", "$dynamicRef"]) {
25
- const ref = record[key];
26
+ const ref = readKey(record, key);
26
27
  if (typeof ref !== "string" || !ref.startsWith("#") || ref === "#")
27
28
  continue;
28
29
  if (scope === null || !declaresLocalTargets(scope))
@@ -33,12 +34,12 @@ const assertIdScopes = (rootSchema) => {
33
34
  throw new Error(`The subschema with $id "${scope["$id"]}" declares its own definitions and contains the ref "${ref}", which names nothing inside it. $id base-URI scoping makes that ref unresolvable, but resolving it from the document root would silently select a different definition. Point the ref at a definition the embedded resource declares, hoist the resource into the root $defs, or drop the inner $id.`);
34
35
  }
35
36
  for (const key of Object.keys(record)) {
36
- if (DATA_KEYWORDS.has(key))
37
+ if (isDataPosition(key, inSchemaMap))
37
38
  continue;
38
- walk(record[key], `${pointer}/${escapePointerSegment(key)}`, base, scope, depth + 1);
39
+ walk(record[key], `${pointer}/${escapePointerSegment(key)}`, base, scope, depth + 1, entersSchemaMap(key, inSchemaMap));
39
40
  }
40
41
  };
41
- walk(rootSchema, "", registry.rootBase, null, 0);
42
+ walk(rootSchema, "", registry.rootBase, null, 0, false);
42
43
  };
43
44
  export {
44
45
  assertIdScopes
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Assigns `value` under `key` on a rebuilt object without letting a `__proto__`
3
+ * key reach the prototype setter.
4
+ *
5
+ * Every walker in this package rebuilds schema objects key by key, and a
6
+ * schema may legitimately describe a property named `__proto__`. A plain
7
+ * `target[key] = value` on that key sets the rebuilt object's *prototype*
8
+ * instead of adding a property: the key disappears from the output — a
9
+ * declared property silently gone, along with every constraint on it — and the
10
+ * object starts inheriting the subschema's own keys, so a later `node.$ref` or
11
+ * `node.type` reads a value the node never had.
12
+ *
13
+ * Defining it as an own data property keeps the key verbatim and leaves the
14
+ * prototype alone. `@amritk/resolve-refs` carries the same helper for the same
15
+ * reason; the two are deliberately identical.
16
+ */
17
+ export declare const assignKey: (target: Record<string, unknown>, key: string, value: unknown) => void;
@@ -0,0 +1,10 @@
1
+ const assignKey = (target, key, value) => {
2
+ if (key === "__proto__") {
3
+ Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
4
+ } else {
5
+ target[key] = value;
6
+ }
7
+ };
8
+ export {
9
+ assignKey
10
+ };
@@ -1,33 +1,33 @@
1
+ import { entersSchemaMap, escapePointerSegment, isDataPosition } from "./build-resource-registry.js";
1
2
  import { assertSchemaDepth } from "./max-schema-depth.js";
3
+ import { readKey } from "./read-key.js";
2
4
  import { isSchemaObject } from "./schema-guards.js";
3
- const escapeSegment = (segment) => segment.indexOf("~") !== -1 || segment.indexOf("/") !== -1 ? segment.replace(/~/g, "~0").replace(/\//g, "~1") : segment;
4
- const NON_SCHEMA_KEYWORDS = /* @__PURE__ */ new Set(["enum", "const", "default", "examples"]);
5
5
  const buildAnchorMap = (rootSchema) => {
6
6
  const map = /* @__PURE__ */ Object.create(null);
7
7
  if (!isSchemaObject(rootSchema))
8
8
  return map;
9
- const walk = (node, pointer, depth) => {
9
+ const walk = (node, pointer, depth, inSchemaMap) => {
10
10
  assertSchemaDepth(depth, "buildAnchorMap");
11
11
  if (node === null || typeof node !== "object")
12
12
  return;
13
13
  if (Array.isArray(node)) {
14
14
  for (let i = 0; i < node.length; i++)
15
- walk(node[i], `${pointer}/${i}`, depth + 1);
15
+ walk(node[i], `${pointer}/${i}`, depth + 1, inSchemaMap);
16
16
  return;
17
17
  }
18
18
  const record = node;
19
19
  for (const keyword of ["$anchor", "$dynamicAnchor"]) {
20
- const anchor = record[keyword];
20
+ const anchor = readKey(record, keyword);
21
21
  if (typeof anchor === "string" && !Object.hasOwn(map, anchor))
22
22
  map[anchor] = `#${pointer}`;
23
23
  }
24
24
  for (const key of Object.keys(record)) {
25
- if (NON_SCHEMA_KEYWORDS.has(key))
25
+ if (isDataPosition(key, inSchemaMap))
26
26
  continue;
27
- walk(record[key], `${pointer}/${escapeSegment(key)}`, depth + 1);
27
+ walk(record[key], `${pointer}/${escapePointerSegment(key)}`, depth + 1, entersSchemaMap(key, inSchemaMap));
28
28
  }
29
29
  };
30
- walk(rootSchema, "", 0);
30
+ walk(rootSchema, "", 0, false);
31
31
  return map;
32
32
  };
33
33
  export {
@@ -1,32 +1,32 @@
1
+ import { entersSchemaMap, escapePointerSegment, isDataPosition } from "./build-resource-registry.js";
1
2
  import { assertSchemaDepth } from "./max-schema-depth.js";
3
+ import { readKey } from "./read-key.js";
2
4
  import { isSchemaObject } from "./schema-guards.js";
3
- const escapeSegment = (segment) => segment.indexOf("~") !== -1 || segment.indexOf("/") !== -1 ? segment.replace(/~/g, "~0").replace(/\//g, "~1") : segment;
4
- const NON_SCHEMA_KEYWORDS = /* @__PURE__ */ new Set(["enum", "const", "default", "examples"]);
5
5
  const buildDynamicRefMap = (rootSchema) => {
6
6
  const map = {};
7
7
  if (!isSchemaObject(rootSchema))
8
8
  return map;
9
- const walk = (node, pointer, depth) => {
9
+ const walk = (node, pointer, depth, inSchemaMap) => {
10
10
  assertSchemaDepth(depth, "buildDynamicRefMap");
11
11
  if (node === null || typeof node !== "object")
12
12
  return;
13
13
  if (Array.isArray(node)) {
14
14
  for (let i = 0; i < node.length; i++)
15
- walk(node[i], `${pointer}/${i}`, depth + 1);
15
+ walk(node[i], `${pointer}/${i}`, depth + 1, inSchemaMap);
16
16
  return;
17
17
  }
18
18
  const record = node;
19
- const anchor = record["$dynamicAnchor"];
19
+ const anchor = readKey(record, "$dynamicAnchor");
20
20
  if (typeof anchor === "string" && !(`#${anchor}` in map)) {
21
21
  map[`#${anchor}`] = `#${pointer}`;
22
22
  }
23
23
  for (const key of Object.keys(record)) {
24
- if (NON_SCHEMA_KEYWORDS.has(key))
24
+ if (isDataPosition(key, inSchemaMap))
25
25
  continue;
26
- walk(record[key], `${pointer}/${escapeSegment(key)}`, depth + 1);
26
+ walk(record[key], `${pointer}/${escapePointerSegment(key)}`, depth + 1, entersSchemaMap(key, inSchemaMap));
27
27
  }
28
28
  };
29
- walk(rootSchema, "", 0);
29
+ walk(rootSchema, "", 0, false);
30
30
  return map;
31
31
  };
32
32
  export {
@@ -54,6 +54,17 @@ export declare const SYNTHETIC_BASE = "https://helpers.mjst.invalid/schema";
54
54
  * these.
55
55
  */
56
56
  export declare const DATA_KEYWORDS: Set<string>;
57
+ /**
58
+ * Keywords whose value is a map of author-chosen names to schemas.
59
+ *
60
+ * The distinction {@link DATA_KEYWORDS} needs to be useful: at a schema node
61
+ * those four are keywords, but inside one of these maps the keys are *names*,
62
+ * so a property genuinely called `default` or `examples` carries no keyword
63
+ * meaning. A walker that skips by key name alone skips that property's whole
64
+ * subtree, which is how a real tuple went unnormalized and a `nullable`
65
+ * property went unfolded.
66
+ */
67
+ export declare const SCHEMA_MAPS: Set<string>;
57
68
  /** `new URL(ref, base).href`, or `undefined` when the pair does not parse. */
58
69
  export declare const resolveUri: (ref: string, base: string) => string | undefined;
59
70
  /**
@@ -65,6 +76,49 @@ export declare const resolveUri: (ref: string, base: string) => string | undefin
65
76
  * literally named `a%2Fb` would otherwise be looked up as `a/b`.
66
77
  */
67
78
  export declare const escapePointerSegment: (segment: string) => string;
79
+ /**
80
+ * Whether `key` holds instance data rather than a schema, at a node whose own
81
+ * position is `inSchemaMap`.
82
+ *
83
+ * A schema walk has two kinds of object. At a **schema node** the keys are
84
+ * keywords, so {@link DATA_KEYWORDS} mark subtrees holding values the schema
85
+ * describes, which must not be read as schemas. Inside a {@link SCHEMA_MAPS}
86
+ * entry the keys are author-chosen **names**, where those same words carry no
87
+ * keyword meaning — a definition or property genuinely called `default` is
88
+ * ordinary.
89
+ *
90
+ * Every walker here used to test the key name alone, which conflated the two:
91
+ * a `$defs.default` had its whole subtree skipped, so an `$anchor` inside it
92
+ * never registered and the `$ref` naming it failed to resolve. Threading one
93
+ * boolean through the recursion is what tells them apart, and asking these two
94
+ * functions is what keeps the walkers agreeing about it.
95
+ *
96
+ * Two predicates rather than a generator over `{key, value, inSchemaMap}`
97
+ * objects: these are the inner loop of ten whole-document walkers, several of
98
+ * which document that they allocate nothing per node.
99
+ *
100
+ * Arrays are the caller's to handle, and the rule there is that **an element
101
+ * inherits its array's position**, the same one `resolve-refs`' `childRole`
102
+ * applies.
103
+ *
104
+ * @example
105
+ * ```typescript
106
+ * const walk = (node: unknown, inSchemaMap: boolean): void => {
107
+ * if (Array.isArray(node)) {
108
+ * for (const item of node) walk(item, inSchemaMap)
109
+ * return
110
+ * }
111
+ * if (!isObject(node)) return
112
+ * for (const key of Object.keys(node)) {
113
+ * if (isDataPosition(key, inSchemaMap)) continue
114
+ * walk(node[key], entersSchemaMap(key, inSchemaMap))
115
+ * }
116
+ * }
117
+ * ```
118
+ */
119
+ export declare const isDataPosition: (key: string, inSchemaMap: boolean) => boolean;
120
+ /** Whether the child at `key` is a map of author-chosen names. See {@link isDataPosition}. */
121
+ export declare const entersSchemaMap: (key: string, inSchemaMap: boolean) => boolean;
68
122
  /**
69
123
  * The base URI a subschema establishes through its `$id`, or the enclosing base
70
124
  * when it declares none. A draft-07-style `$id: "#name"` resolves to a bare
@@ -1,6 +1,25 @@
1
1
  import { assertSchemaDepth } from "./max-schema-depth.js";
2
+ import { readKey } from "./read-key.js";
2
3
  const SYNTHETIC_BASE = "https://helpers.mjst.invalid/schema";
3
- const DATA_KEYWORDS = /* @__PURE__ */ new Set(["enum", "const", "default", "examples"]);
4
+ const DATA_KEYWORDS = /* @__PURE__ */ new Set([
5
+ "enum",
6
+ "const",
7
+ "default",
8
+ "examples",
9
+ // OpenAPI 3.0's singular spelling. `foldNullable` runs specifically on 3.0
10
+ // documents, and the adapters take TypeBox/OpenAPI-derived input, so an
11
+ // `example` value was being walked as though it were a schema.
12
+ "example"
13
+ ]);
14
+ const SCHEMA_MAPS = /* @__PURE__ */ new Set([
15
+ "properties",
16
+ "patternProperties",
17
+ "$defs",
18
+ "definitions",
19
+ "dependentSchemas",
20
+ // Draft-07's `dependencies`: its keys are trigger property names too.
21
+ "dependencies"
22
+ ]);
4
23
  const resolveUri = (ref, base) => {
5
24
  try {
6
25
  return new URL(ref, base).href;
@@ -9,8 +28,10 @@ const resolveUri = (ref, base) => {
9
28
  }
10
29
  };
11
30
  const escapePointerSegment = (segment) => segment.indexOf("~") === -1 && segment.indexOf("/") === -1 && segment.indexOf("%") === -1 ? segment : segment.replace(/~/g, "~0").replace(/\//g, "~1").replace(/%/g, "%25");
31
+ const isDataPosition = (key, inSchemaMap) => !inSchemaMap && DATA_KEYWORDS.has(key);
32
+ const entersSchemaMap = (key, inSchemaMap) => !inSchemaMap && SCHEMA_MAPS.has(key);
12
33
  const baseAfterId = (node, enclosing) => {
13
- const id = node["$id"];
34
+ const id = readKey(node, "$id");
14
35
  if (typeof id !== "string" || id === "")
15
36
  return enclosing;
16
37
  const resolved = resolveUri(id, enclosing);
@@ -32,13 +53,13 @@ const buildResourceRegistry = (root) => {
32
53
  const dynamicAnchors = /* @__PURE__ */ new Map();
33
54
  const baseAt = /* @__PURE__ */ new Map();
34
55
  let sawId = false;
35
- const walk = (node, pointer, enclosing, depth) => {
56
+ const walk = (node, pointer, enclosing, depth, inSchemaMap) => {
36
57
  assertSchemaDepth(depth, "buildResourceRegistry");
37
58
  if (node === null || typeof node !== "object")
38
59
  return;
39
60
  if (Array.isArray(node)) {
40
61
  for (let index = 0; index < node.length; index++)
41
- walk(node[index], `${pointer}/${index}`, enclosing, depth + 1);
62
+ walk(node[index], `${pointer}/${index}`, enclosing, depth + 1, inSchemaMap);
42
63
  return;
43
64
  }
44
65
  const record = node;
@@ -49,10 +70,10 @@ const buildResourceRegistry = (root) => {
49
70
  if (!resources.has(base))
50
71
  resources.set(base, pointer);
51
72
  }
52
- const anchor = record["$anchor"];
73
+ const anchor = readKey(record, "$anchor");
53
74
  if (typeof anchor === "string" && !anchors.has(`${base}#${anchor}`))
54
75
  anchors.set(`${base}#${anchor}`, pointer);
55
- const dynamicAnchor = record["$dynamicAnchor"];
76
+ const dynamicAnchor = readKey(record, "$dynamicAnchor");
56
77
  if (typeof dynamicAnchor === "string") {
57
78
  const key = `${base}#${dynamicAnchor}`;
58
79
  if (!dynamicAnchors.has(key))
@@ -61,12 +82,12 @@ const buildResourceRegistry = (root) => {
61
82
  anchors.set(key, pointer);
62
83
  }
63
84
  for (const key of Object.keys(record)) {
64
- if (DATA_KEYWORDS.has(key))
85
+ if (isDataPosition(key, inSchemaMap))
65
86
  continue;
66
- walk(record[key], `${pointer}/${escapePointerSegment(key)}`, base, depth + 1);
87
+ walk(record[key], `${pointer}/${escapePointerSegment(key)}`, base, depth + 1, entersSchemaMap(key, inSchemaMap));
67
88
  }
68
89
  };
69
- walk(root, "", SYNTHETIC_BASE, 0);
90
+ walk(root, "", SYNTHETIC_BASE, 0, false);
70
91
  if (!sawId) {
71
92
  registries.set(root, null);
72
93
  return null;
@@ -82,9 +103,12 @@ const buildResourceRegistry = (root) => {
82
103
  };
83
104
  export {
84
105
  DATA_KEYWORDS,
106
+ SCHEMA_MAPS,
85
107
  SYNTHETIC_BASE,
86
108
  baseAfterId,
87
109
  buildResourceRegistry,
110
+ entersSchemaMap,
88
111
  escapePointerSegment,
112
+ isDataPosition,
89
113
  resolveUri
90
114
  };
@@ -1,4 +1,6 @@
1
+ import { entersSchemaMap, isDataPosition } from "./build-resource-registry.js";
1
2
  import { assertSchemaDepth } from "./max-schema-depth.js";
3
+ import { readKey } from "./read-key.js";
2
4
  const isResolvableRef = (ref) => {
3
5
  if (ref === "#")
4
6
  return false;
@@ -10,23 +12,25 @@ const isResolvableRef = (ref) => {
10
12
  };
11
13
  const extractRefs = (schema) => {
12
14
  const refs = /* @__PURE__ */ new Set();
13
- const traverse = (obj, depth) => {
15
+ const traverse = (obj, depth, inSchemaMap = false) => {
14
16
  assertSchemaDepth(depth, "extractRefs");
15
17
  if (typeof obj !== "object" || obj === null) {
16
18
  return;
17
19
  }
18
20
  if (Array.isArray(obj)) {
19
21
  for (const item of obj) {
20
- traverse(item, depth + 1);
22
+ traverse(item, depth + 1, inSchemaMap);
21
23
  }
22
24
  return;
23
25
  }
24
26
  const record = obj;
25
- if ("$ref" in record && typeof record["$ref"] === "string" && isResolvableRef(record["$ref"])) {
27
+ if (!inSchemaMap && typeof readKey(record, "$ref") === "string" && isResolvableRef(record["$ref"])) {
26
28
  refs.add(record["$ref"]);
27
29
  }
28
- for (const key in record) {
29
- traverse(record[key], depth + 1);
30
+ for (const key of Object.keys(record)) {
31
+ if (isDataPosition(key, inSchemaMap))
32
+ continue;
33
+ traverse(record[key], depth + 1, entersSchemaMap(key, inSchemaMap));
30
34
  }
31
35
  };
32
36
  traverse(schema, 0);
@@ -1,12 +1,14 @@
1
+ import { assignKey } from "./assign-key.js";
2
+ import { entersSchemaMap, isDataPosition } from "./build-resource-registry.js";
1
3
  const foldNullable = (schema) => {
2
4
  const folded = fold(schema);
3
5
  return folded;
4
6
  };
5
- const fold = (node) => {
7
+ const fold = (node, inSchemaMap = false) => {
6
8
  if (Array.isArray(node)) {
7
9
  let changed2 = false;
8
10
  const next2 = node.map((item) => {
9
- const folded = fold(item);
11
+ const folded = fold(item, inSchemaMap);
10
12
  if (folded !== item)
11
13
  changed2 = true;
12
14
  return folded;
@@ -18,15 +20,18 @@ const fold = (node) => {
18
20
  const record = node;
19
21
  let changed = false;
20
22
  const next = {};
21
- for (const key in record) {
22
- const value = record[key];
23
- const folded = fold(value);
24
- if (folded !== value)
23
+ for (const [key, value] of Object.entries(record))
24
+ assignKey(next, key, value);
25
+ for (const key of Object.keys(record)) {
26
+ if (isDataPosition(key, inSchemaMap))
27
+ continue;
28
+ const folded = fold(record[key], entersSchemaMap(key, inSchemaMap));
29
+ if (folded !== record[key])
25
30
  changed = true;
26
- next[key] = folded;
31
+ assignKey(next, key, folded);
27
32
  }
28
- const type = record["type"];
29
- if (record["nullable"] === true) {
33
+ const type = Object.hasOwn(record, "type") ? record["type"] : void 0;
34
+ if (!inSchemaMap && Object.hasOwn(record, "nullable") && record["nullable"] === true) {
30
35
  if (typeof type === "string" && type !== "null") {
31
36
  next["type"] = [type, "null"];
32
37
  changed = true;
@@ -50,7 +50,7 @@ const getConditionalObjectSchema = (schema) => {
50
50
  }
51
51
  }
52
52
  if (hasIfProperties) {
53
- for (const key in ifProperties) {
53
+ for (const key of Object.keys(ifProperties)) {
54
54
  required.add(key);
55
55
  }
56
56
  }
@@ -60,7 +60,7 @@ const getConditionalObjectSchema = (schema) => {
60
60
  }
61
61
  }
62
62
  if (hasThenProperties) {
63
- for (const key in thenProperties) {
63
+ for (const key of Object.keys(thenProperties)) {
64
64
  required.add(key);
65
65
  }
66
66
  }
@@ -158,16 +158,16 @@ const patternPropertiesRecordType = (patternProperties, options) => {
158
158
  };
159
159
  const getTuplePositions = (schema) => {
160
160
  const record = schema;
161
- const prefixItems = record["prefixItems"];
162
- if (Array.isArray(prefixItems) && prefixItems.length > 0)
163
- return prefixItems;
161
+ const prefixItems = Object.hasOwn(record, "prefixItems") ? record["prefixItems"] : void 0;
162
+ if (Array.isArray(prefixItems))
163
+ return prefixItems.length > 0 ? prefixItems : void 0;
164
164
  if (Array.isArray(schema.items) && schema.items.length > 0)
165
165
  return schema.items;
166
166
  return void 0;
167
167
  };
168
168
  const tupleTypeToTs = (schema, positions, options) => {
169
169
  const record = schema;
170
- const rest = Array.isArray(schema.items) ? record["additionalItems"] : record["items"];
170
+ const rest = Array.isArray(schema.items) ? Object.hasOwn(record, "additionalItems") ? record["additionalItems"] : void 0 : Object.hasOwn(record, "items") ? record["items"] : void 0;
171
171
  const minItems = typeof schema.minItems === "number" ? schema.minItems : 0;
172
172
  const parts = [];
173
173
  for (let i = 0; i < positions.length; i++) {
@@ -237,7 +237,7 @@ const objectTypeToTs = (schema, options) => {
237
237
  const declaredTypes = [];
238
238
  let hasOptionalProperty = false;
239
239
  const entries = [];
240
- for (const key in schema.properties) {
240
+ for (const key of Object.keys(schema.properties)) {
241
241
  const propSchema = schema.properties[key];
242
242
  const isRequired = requiredSet.has(key);
243
243
  const optional = isRequired ? "" : "?";
@@ -440,7 +440,7 @@ const generateTypeDefinition = (schema, typeName, options = {}) => {
440
440
  isFirstProp = false;
441
441
  properties += line;
442
442
  };
443
- for (const key in schemaProps) {
443
+ for (const key of Object.keys(schemaProps)) {
444
444
  const propSchema = schemaProps[key];
445
445
  const isRequired = requiredSet.has(key);
446
446
  const optional = isRequired ? "" : "?";
package/dist/has-ref.js CHANGED
@@ -1,5 +1,5 @@
1
1
  const hasRef = (value) => {
2
- return typeof value === "object" && value !== null && !Array.isArray(value) && "$ref" in value && typeof value.$ref === "string";
2
+ return typeof value === "object" && value !== null && !Array.isArray(value) && Object.hasOwn(value, "$ref") && typeof value.$ref === "string";
3
3
  };
4
4
  export {
5
5
  hasRef
@@ -1,4 +1,5 @@
1
- import { buildResourceRegistry, DATA_KEYWORDS, escapePointerSegment, resolveUri } from "./build-resource-registry.js";
1
+ import { assignKey } from "./assign-key.js";
2
+ import { buildResourceRegistry, entersSchemaMap, escapePointerSegment, isDataPosition, resolveUri } from "./build-resource-registry.js";
2
3
  import { assertSchemaDepth } from "./max-schema-depth.js";
3
4
  import { resolveRef } from "./resolve-ref.js";
4
5
  import { resolveScopedRef } from "./resolve-scoped-ref.js";
@@ -26,23 +27,28 @@ const normalizeRefScopes = (root) => {
26
27
  }
27
28
  return normalizedRef(ref, base);
28
29
  };
29
- const rewrite = (node, pointer, enclosing, depth) => {
30
+ const rewrite = (node, pointer, enclosing, depth, inSchemaMap = false) => {
30
31
  assertSchemaDepth(depth, "normalizeRefScopes");
31
32
  if (node === null || typeof node !== "object")
32
33
  return node;
33
34
  if (Array.isArray(node)) {
34
- const mapped = node.map((item, index) => rewrite(item, `${pointer}/${index}`, enclosing, depth + 1));
35
+ const mapped = node.map((item, index) => rewrite(item, `${pointer}/${index}`, enclosing, depth + 1, inSchemaMap));
35
36
  return mapped.some((item, index) => item !== node[index]) ? mapped : node;
36
37
  }
37
38
  const record = node;
38
39
  const base = registry.baseAt.get(pointer) ?? enclosing;
39
40
  let changed = false;
40
41
  const result = {};
41
- for (const [key, value] of Object.entries(record)) {
42
- const next = key === "$ref" && typeof value === "string" ? normalizedRef(value, base) ?? value : key === "$dynamicRef" && typeof value === "string" ? normalizedDynamicRef(value, base) ?? value : DATA_KEYWORDS.has(key) ? value : rewrite(value, `${pointer}/${escapePointerSegment(key)}`, base, depth + 1);
42
+ for (const [key, value] of Object.entries(record))
43
+ assignKey(result, key, value);
44
+ for (const key of Object.keys(record)) {
45
+ if (isDataPosition(key, inSchemaMap))
46
+ continue;
47
+ const value = record[key];
48
+ const next = !inSchemaMap && key === "$ref" && typeof value === "string" ? normalizedRef(value, base) ?? value : !inSchemaMap && key === "$dynamicRef" && typeof value === "string" ? normalizedDynamicRef(value, base) ?? value : rewrite(value, `${pointer}/${escapePointerSegment(key)}`, base, depth + 1, entersSchemaMap(key, inSchemaMap));
43
49
  if (next !== value)
44
50
  changed = true;
45
- result[key] = next;
51
+ assignKey(result, key, next);
46
52
  }
47
53
  return changed ? result : record;
48
54
  };
@@ -1,7 +1,8 @@
1
1
  import { buildDynamicRefMap } from "./build-dynamic-ref-map.js";
2
2
  import { assertSchemaDepth } from "./max-schema-depth.js";
3
+ import { readKey } from "./read-key.js";
3
4
  const DEFS_PREFIX = "#/$defs/";
4
- const unescapeSegment = (segment) => segment.indexOf("~") === -1 ? segment : segment.replace(/~1/g, "/").replace(/~0/g, "~");
5
+ const unescapeSegment = (segment) => segment.indexOf("~") === -1 && segment.indexOf("%25") === -1 ? segment : segment.replace(/~1/g, "/").replace(/~0/g, "~").replace(/%25/g, "%");
5
6
  const externalTarget = (ref, external) => {
6
7
  if (!ref.startsWith(DEFS_PREFIX))
7
8
  return void 0;
@@ -21,21 +22,21 @@ const referencedFrom = (node, external, dynamicMap, into) => {
21
22
  return;
22
23
  }
23
24
  const record = value;
24
- const ref = record["$ref"];
25
+ const ref = Object.hasOwn(record, "$ref") ? record["$ref"] : void 0;
25
26
  if (typeof ref === "string") {
26
27
  const name = externalTarget(ref, external);
27
28
  if (name !== void 0)
28
29
  into.add(name);
29
30
  }
30
- const dynamicRef = record["$dynamicRef"];
31
+ const dynamicRef = Object.hasOwn(record, "$dynamicRef") ? record["$dynamicRef"] : void 0;
31
32
  if (typeof dynamicRef === "string") {
32
- const target = dynamicRef.startsWith("#/") ? dynamicRef : dynamicMap[dynamicRef];
33
+ const target = dynamicRef.startsWith("#/") ? dynamicRef : readKey(dynamicMap, dynamicRef);
33
34
  const name = target === void 0 ? void 0 : externalTarget(target, external);
34
35
  if (name !== void 0)
35
36
  into.add(name);
36
37
  }
37
- for (const key in record)
38
- walk(record[key], depth + 1);
38
+ for (const value2 of Object.values(record))
39
+ walk(value2, depth + 1);
39
40
  };
40
41
  walk(node, 0);
41
42
  };
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Reads `key` off a map of author-chosen names, treating an inherited name as
3
+ * absent.
4
+ *
5
+ * The maps this guards — `$defs`, a `$dynamicAnchor` index, a config-key table
6
+ * — are keyed by names taken from a schema or a config file, so `__proto__`,
7
+ * `constructor` and `toString` are all names an author may legitimately use.
8
+ * A bare index answers those from `Object.prototype`, which is never what the
9
+ * caller meant: `$defs.__proto__` hands back `Object.prototype` as though it
10
+ * were a declared definition, and `map.toString` hands back a `Function` where
11
+ * a schema was expected.
12
+ */
13
+ export declare const readKey: <T>(source: Readonly<Record<string, T>>, key: string) => T | undefined;
@@ -0,0 +1,4 @@
1
+ const readKey = (source, key) => Object.hasOwn(source, key) ? source[key] : void 0;
2
+ export {
3
+ readKey
4
+ };
@@ -1,4 +1,6 @@
1
+ import { DATA_KEYWORDS, entersSchemaMap, isDataPosition } from "./build-resource-registry.js";
1
2
  import { assertSchemaDepth } from "./max-schema-depth.js";
3
+ import { readKey } from "./read-key.js";
2
4
  const resolveDynamicRefs = (schema, dynamicRefMap) => {
3
5
  if (typeof schema !== "object" || schema === null) {
4
6
  return schema;
@@ -7,28 +9,30 @@ const resolveDynamicRefs = (schema, dynamicRefMap) => {
7
9
  return schema;
8
10
  }
9
11
  const clone = JSON.parse(JSON.stringify(schema));
10
- const walk = (obj, depth) => {
12
+ const walk = (obj, depth, inSchemaMap = false) => {
11
13
  assertSchemaDepth(depth, "resolveDynamicRefs");
12
14
  if (typeof obj !== "object" || obj === null) {
13
15
  return;
14
16
  }
15
17
  if (Array.isArray(obj)) {
16
18
  for (const item of obj)
17
- walk(item, depth + 1);
19
+ walk(item, depth + 1, inSchemaMap);
18
20
  return;
19
21
  }
20
22
  const record = obj;
21
- const dynamicRef = record["$dynamicRef"];
23
+ const dynamicRef = inSchemaMap ? void 0 : readKey(record, "$dynamicRef");
22
24
  if (typeof dynamicRef === "string") {
23
- const resolved = dynamicRefMap[dynamicRef] ?? (dynamicRef.startsWith("#/") ? dynamicRef : void 0);
25
+ const resolved = readKey(dynamicRefMap, dynamicRef) ?? (dynamicRef.startsWith("#/") ? dynamicRef : void 0);
24
26
  if (resolved === void 0) {
25
27
  throw new Error(`Unresolvable $dynamicRef "${dynamicRef}": no $dynamicAnchor named "${dynamicRef.replace(/^#/, "")}" is declared anywhere in the document. Declare the anchor, or point a plain $ref at the definition instead.`);
26
28
  }
27
29
  record["$ref"] = resolved;
28
30
  delete record["$dynamicRef"];
29
31
  }
30
- for (const key in record) {
31
- walk(record[key], depth + 1);
32
+ for (const key of Object.keys(record)) {
33
+ if (isDataPosition(key, inSchemaMap))
34
+ continue;
35
+ walk(record[key], depth + 1, entersSchemaMap(key, inSchemaMap));
32
36
  }
33
37
  };
34
38
  walk(clone, 0);
@@ -45,11 +49,14 @@ const containsDynamicRef = (value, depth) => {
45
49
  return false;
46
50
  }
47
51
  const record = value;
48
- if (typeof record["$dynamicRef"] === "string")
52
+ if (typeof readKey(record, "$dynamicRef") === "string")
49
53
  return true;
50
- for (const key in record)
54
+ for (const key of Object.keys(record)) {
55
+ if (DATA_KEYWORDS.has(key))
56
+ continue;
51
57
  if (containsDynamicRef(record[key], depth + 1))
52
58
  return true;
59
+ }
53
60
  return false;
54
61
  };
55
62
  export {
@@ -1,4 +1,5 @@
1
1
  import { buildAnchorMap } from "./build-anchor-map.js";
2
+ import { readKey } from "./read-key.js";
2
3
  const anchorMaps = /* @__PURE__ */ new WeakMap();
3
4
  const getAnchorMap = (rootSchema) => {
4
5
  const existing = anchorMaps.get(rootSchema);
@@ -54,7 +55,7 @@ const resolveRef = (ref, rootSchema) => {
54
55
  if (typeof defs !== "object" || defs === null)
55
56
  return void 0;
56
57
  const defsRecord = defs;
57
- const base = defsRecord[baseUri];
58
+ const base = readKey(defsRecord, baseUri);
58
59
  if (typeof base !== "object" || base === null)
59
60
  return void 0;
60
61
  if (!fragment)
@@ -2,67 +2,67 @@ const isSchemaObject = (schema) => {
2
2
  return typeof schema === "object" && schema !== null && typeof schema !== "boolean";
3
3
  };
4
4
  const hasType = (schema) => {
5
- return isSchemaObject(schema) && "type" in schema && typeof schema.type === "string";
5
+ return isSchemaObject(schema) && Object.hasOwn(schema, "type") && typeof schema.type === "string";
6
6
  };
7
7
  const isObjectSchema = (schema) => {
8
- return isSchemaObject(schema) && ("type" in schema && schema.type === "object" || "properties" in schema);
8
+ return isSchemaObject(schema) && (Object.hasOwn(schema, "type") && schema.type === "object" || Object.hasOwn(schema, "properties"));
9
9
  };
10
10
  const hasProperties = (schema) => {
11
- return isSchemaObject(schema) && "properties" in schema && typeof schema.properties === "object" && schema.properties !== null;
11
+ return isSchemaObject(schema) && Object.hasOwn(schema, "properties") && typeof schema.properties === "object" && schema.properties !== null;
12
12
  };
13
13
  const hasEnum = (schema) => {
14
- return isSchemaObject(schema) && "enum" in schema && Array.isArray(schema.enum);
14
+ return isSchemaObject(schema) && Object.hasOwn(schema, "enum") && Array.isArray(schema.enum);
15
15
  };
16
16
  const hasConst = (schema) => {
17
- return isSchemaObject(schema) && "const" in schema;
17
+ return isSchemaObject(schema) && Object.hasOwn(schema, "const");
18
18
  };
19
19
  const hasPattern = (schema) => {
20
- return isSchemaObject(schema) && "pattern" in schema && typeof schema.pattern === "string";
20
+ return isSchemaObject(schema) && Object.hasOwn(schema, "pattern") && typeof schema.pattern === "string";
21
21
  };
22
22
  const hasFormat = (schema) => {
23
- return isSchemaObject(schema) && "format" in schema && typeof schema.format === "string";
23
+ return isSchemaObject(schema) && Object.hasOwn(schema, "format") && typeof schema.format === "string";
24
24
  };
25
25
  const hasDefault = (schema) => {
26
- return isSchemaObject(schema) && "default" in schema;
26
+ return isSchemaObject(schema) && Object.hasOwn(schema, "default");
27
27
  };
28
28
  const hasExamples = (schema) => {
29
- return isSchemaObject(schema) && "examples" in schema && Array.isArray(schema.examples);
29
+ return isSchemaObject(schema) && Object.hasOwn(schema, "examples") && Array.isArray(schema.examples);
30
30
  };
31
31
  const hasOneOf = (schema) => {
32
- return isSchemaObject(schema) && "oneOf" in schema && Array.isArray(schema.oneOf);
32
+ return isSchemaObject(schema) && Object.hasOwn(schema, "oneOf") && Array.isArray(schema.oneOf);
33
33
  };
34
34
  const hasAnyOf = (schema) => {
35
- return isSchemaObject(schema) && "anyOf" in schema && Array.isArray(schema.anyOf);
35
+ return isSchemaObject(schema) && Object.hasOwn(schema, "anyOf") && Array.isArray(schema.anyOf);
36
36
  };
37
37
  const hasAllOf = (schema) => {
38
- return isSchemaObject(schema) && "allOf" in schema && Array.isArray(schema.allOf);
38
+ return isSchemaObject(schema) && Object.hasOwn(schema, "allOf") && Array.isArray(schema.allOf);
39
39
  };
40
40
  const hasRequired = (schema) => {
41
- return isSchemaObject(schema) && "required" in schema && Array.isArray(schema.required);
41
+ return isSchemaObject(schema) && Object.hasOwn(schema, "required") && Array.isArray(schema.required);
42
42
  };
43
43
  const hasItems = (schema) => {
44
- return isSchemaObject(schema) && "items" in schema && typeof schema.items === "object" && schema.items !== null && typeof schema.items !== "boolean";
44
+ return isSchemaObject(schema) && Object.hasOwn(schema, "items") && typeof schema.items === "object" && schema.items !== null && typeof schema.items !== "boolean";
45
45
  };
46
46
  const hasAdditionalProperties = (schema) => {
47
- return isSchemaObject(schema) && "additionalProperties" in schema;
47
+ return isSchemaObject(schema) && Object.hasOwn(schema, "additionalProperties");
48
48
  };
49
49
  const hasMinLength = (schema) => {
50
- return isSchemaObject(schema) && "minLength" in schema && typeof schema.minLength === "number";
50
+ return isSchemaObject(schema) && Object.hasOwn(schema, "minLength") && typeof schema.minLength === "number";
51
51
  };
52
52
  const hasMaxLength = (schema) => {
53
- return isSchemaObject(schema) && "maxLength" in schema && typeof schema.maxLength === "number";
53
+ return isSchemaObject(schema) && Object.hasOwn(schema, "maxLength") && typeof schema.maxLength === "number";
54
54
  };
55
55
  const hasMinimum = (schema) => {
56
- return isSchemaObject(schema) && "minimum" in schema && typeof schema.minimum === "number";
56
+ return isSchemaObject(schema) && Object.hasOwn(schema, "minimum") && typeof schema.minimum === "number";
57
57
  };
58
58
  const hasMaximum = (schema) => {
59
- return isSchemaObject(schema) && "maximum" in schema && typeof schema.maximum === "number";
59
+ return isSchemaObject(schema) && Object.hasOwn(schema, "maximum") && typeof schema.maximum === "number";
60
60
  };
61
61
  const hasExclusiveMinimum = (schema) => {
62
- return isSchemaObject(schema) && "exclusiveMinimum" in schema && typeof schema.exclusiveMinimum === "number";
62
+ return isSchemaObject(schema) && Object.hasOwn(schema, "exclusiveMinimum") && typeof schema.exclusiveMinimum === "number";
63
63
  };
64
64
  const hasExclusiveMaximum = (schema) => {
65
- return isSchemaObject(schema) && "exclusiveMaximum" in schema && typeof schema.exclusiveMaximum === "number";
65
+ return isSchemaObject(schema) && Object.hasOwn(schema, "exclusiveMaximum") && typeof schema.exclusiveMaximum === "number";
66
66
  };
67
67
  const hasStrictExclusiveMinimum = (schema) => {
68
68
  if (!isSchemaObject(schema))
@@ -77,43 +77,43 @@ const hasStrictExclusiveMaximum = (schema) => {
77
77
  return flag === true;
78
78
  };
79
79
  const hasMultipleOf = (schema) => {
80
- return isSchemaObject(schema) && "multipleOf" in schema && typeof schema.multipleOf === "number";
80
+ return isSchemaObject(schema) && Object.hasOwn(schema, "multipleOf") && typeof schema.multipleOf === "number";
81
81
  };
82
82
  const hasMinItems = (schema) => {
83
- return isSchemaObject(schema) && "minItems" in schema && typeof schema.minItems === "number";
83
+ return isSchemaObject(schema) && Object.hasOwn(schema, "minItems") && typeof schema.minItems === "number";
84
84
  };
85
85
  const hasMaxItems = (schema) => {
86
- return isSchemaObject(schema) && "maxItems" in schema && typeof schema.maxItems === "number";
86
+ return isSchemaObject(schema) && Object.hasOwn(schema, "maxItems") && typeof schema.maxItems === "number";
87
87
  };
88
88
  const hasUniqueItems = (schema) => {
89
- return isSchemaObject(schema) && "uniqueItems" in schema && typeof schema.uniqueItems === "boolean";
89
+ return isSchemaObject(schema) && Object.hasOwn(schema, "uniqueItems") && typeof schema.uniqueItems === "boolean";
90
90
  };
91
91
  const hasMinProperties = (schema) => {
92
- return isSchemaObject(schema) && "minProperties" in schema && typeof schema.minProperties === "number";
92
+ return isSchemaObject(schema) && Object.hasOwn(schema, "minProperties") && typeof schema.minProperties === "number";
93
93
  };
94
94
  const hasMaxProperties = (schema) => {
95
- return isSchemaObject(schema) && "maxProperties" in schema && typeof schema.maxProperties === "number";
95
+ return isSchemaObject(schema) && Object.hasOwn(schema, "maxProperties") && typeof schema.maxProperties === "number";
96
96
  };
97
97
  const hasDependentRequired = (schema) => {
98
- return isSchemaObject(schema) && "dependentRequired" in schema && typeof schema.dependentRequired === "object" && schema.dependentRequired !== null;
98
+ return isSchemaObject(schema) && Object.hasOwn(schema, "dependentRequired") && typeof schema.dependentRequired === "object" && schema.dependentRequired !== null;
99
99
  };
100
100
  const hasPropertyNames = (schema) => {
101
- return isSchemaObject(schema) && "propertyNames" in schema;
101
+ return isSchemaObject(schema) && Object.hasOwn(schema, "propertyNames");
102
102
  };
103
103
  const hasDependentSchemas = (schema) => {
104
- return isSchemaObject(schema) && "dependentSchemas" in schema && typeof schema.dependentSchemas === "object" && schema.dependentSchemas !== null;
104
+ return isSchemaObject(schema) && Object.hasOwn(schema, "dependentSchemas") && typeof schema.dependentSchemas === "object" && schema.dependentSchemas !== null;
105
105
  };
106
106
  const hasPatternProperties = (schema) => {
107
- return isSchemaObject(schema) && "patternProperties" in schema && typeof schema.patternProperties === "object" && schema.patternProperties !== null;
107
+ return isSchemaObject(schema) && Object.hasOwn(schema, "patternProperties") && typeof schema.patternProperties === "object" && schema.patternProperties !== null;
108
108
  };
109
109
  const hasContains = (schema) => {
110
- return isSchemaObject(schema) && "contains" in schema;
110
+ return isSchemaObject(schema) && Object.hasOwn(schema, "contains");
111
111
  };
112
112
  const hasNot = (schema) => {
113
- return isSchemaObject(schema) && "not" in schema;
113
+ return isSchemaObject(schema) && Object.hasOwn(schema, "not");
114
114
  };
115
115
  const hasIf = (schema) => {
116
- return isSchemaObject(schema) && "if" in schema;
116
+ return isSchemaObject(schema) && Object.hasOwn(schema, "if");
117
117
  };
118
118
  import { hasRef } from "./has-ref.js";
119
119
  export {
@@ -1,26 +1,29 @@
1
- import { DATA_KEYWORDS } from "./build-resource-registry.js";
1
+ import { assignKey } from "./assign-key.js";
2
+ import { entersSchemaMap, isDataPosition } from "./build-resource-registry.js";
2
3
  import { assertSchemaDepth } from "./max-schema-depth.js";
3
4
  import { refToFilename, toKebabCase } from "./ref-to-filename.js";
4
5
  const isDraft07Schema = (schema) => typeof schema["$schema"] === "string" && schema["$schema"].includes("draft-07");
5
- const rewriteRefs = (obj, refMap, selfRef, depth = 0) => {
6
+ const rewriteRefs = (obj, refMap, selfRef, depth = 0, inSchemaMap = false) => {
6
7
  assertSchemaDepth(depth, "upgradeDraft07Schema");
7
8
  if (typeof obj !== "object" || obj === null)
8
9
  return obj;
9
10
  if (Array.isArray(obj))
10
- return obj.map((item) => rewriteRefs(item, refMap, selfRef, depth + 1));
11
+ return obj.map((item) => rewriteRefs(item, refMap, selfRef, depth + 1, inSchemaMap));
11
12
  const record = obj;
12
13
  const result = {};
13
14
  for (const [key, value] of Object.entries(record)) {
14
- if (key === "$ref" && typeof value === "string") {
15
+ if (isDataPosition(key, inSchemaMap)) {
16
+ assignKey(result, key, value);
17
+ } else if (!inSchemaMap && key === "$ref" && typeof value === "string") {
15
18
  if (refMap.has(value)) {
16
- result[key] = refMap.get(value);
19
+ assignKey(result, key, refMap.get(value));
17
20
  } else if (value === "#" && selfRef) {
18
- result[key] = selfRef;
21
+ assignKey(result, key, selfRef);
19
22
  } else {
20
- result[key] = value;
23
+ assignKey(result, key, value);
21
24
  }
22
25
  } else {
23
- result[key] = rewriteRefs(value, refMap, selfRef, depth + 1);
26
+ assignKey(result, key, rewriteRefs(value, refMap, selfRef, depth + 1, entersSchemaMap(key, inSchemaMap)));
24
27
  }
25
28
  }
26
29
  return result;
@@ -29,13 +32,13 @@ const hoistNestedDefs = (defs) => {
29
32
  const hoisted = {};
30
33
  for (const [parentName, parentSchema] of Object.entries(defs)) {
31
34
  if (typeof parentSchema !== "object" || parentSchema === null) {
32
- hoisted[parentName] = parentSchema;
35
+ assignKey(hoisted, parentName, parentSchema);
33
36
  continue;
34
37
  }
35
38
  const parentObj = parentSchema;
36
39
  const nestedDefs = parentObj["$defs"];
37
40
  if (!nestedDefs || typeof nestedDefs !== "object") {
38
- hoisted[parentName] = parentSchema;
41
+ assignKey(hoisted, parentName, parentSchema);
39
42
  continue;
40
43
  }
41
44
  const parentPrefix = parentName.startsWith("http://") || parentName.startsWith("https://") ? refToFilename(parentName) : parentName;
@@ -46,10 +49,10 @@ const hoistNestedDefs = (defs) => {
46
49
  }
47
50
  const selfRef = `#/$defs/${parentPrefix}`;
48
51
  const rewrittenParent = rewriteRefs(parentObj, localToHoisted, selfRef);
49
- hoisted[parentName] = rewrittenParent;
52
+ assignKey(hoisted, parentName, rewrittenParent);
50
53
  for (const [localName, localSchema] of Object.entries(nestedDefs)) {
51
54
  const hoistedName = `${parentPrefix}-${toKebabCase(localName)}`;
52
- hoisted[hoistedName] = rewriteRefs(localSchema, localToHoisted, selfRef);
55
+ assignKey(hoisted, hoistedName, rewriteRefs(localSchema, localToHoisted, selfRef));
53
56
  }
54
57
  }
55
58
  return hoisted;
@@ -61,14 +64,14 @@ const upgradeDraft07Schema = (schema) => {
61
64
  const rawDefs = definitions ?? {};
62
65
  const renamedDefs = {};
63
66
  for (const [key, value] of Object.entries(rawDefs)) {
64
- renamedDefs[key] = renameNestedDefs(value);
67
+ assignKey(renamedDefs, key, renameNestedDefs(value));
65
68
  }
66
69
  const hoistedDefs = hoistNestedDefs(renamedDefs);
67
70
  for (const key of Object.keys(hoistedDefs)) {
68
71
  if (key.startsWith("http://") || key.startsWith("https://")) {
69
72
  const shortName = refToFilename(key);
70
- if (shortName && !(shortName in hoistedDefs)) {
71
- hoistedDefs[shortName] = hoistedDefs[key];
73
+ if (shortName && !Object.hasOwn(hoistedDefs, shortName)) {
74
+ assignKey(hoistedDefs, shortName, hoistedDefs[key]);
72
75
  }
73
76
  }
74
77
  }
@@ -77,40 +80,48 @@ const upgradeDraft07Schema = (schema) => {
77
80
  $defs: hoistedDefs
78
81
  };
79
82
  };
80
- const rewriteDefinitionsRefs = (obj, depth = 0) => {
83
+ const rewriteDefinitionsRefs = (obj, depth = 0, inSchemaMap = false) => {
81
84
  assertSchemaDepth(depth, "upgradeDraft07Schema");
82
85
  if (typeof obj !== "object" || obj === null)
83
86
  return obj;
84
87
  if (Array.isArray(obj))
85
- return obj.map((item) => rewriteDefinitionsRefs(item, depth + 1));
88
+ return obj.map((item) => rewriteDefinitionsRefs(item, depth + 1, inSchemaMap));
86
89
  const record = obj;
87
90
  const result = {};
88
- for (const [key, value] of Object.entries(record)) {
89
- const rewritten = key === "$ref" && typeof value === "string" && value.startsWith("#/definitions/") ? value.replace("#/definitions/", "#/$defs/") : DATA_KEYWORDS.has(key) || startsNewResource(value) ? value : rewriteDefinitionsRefs(value, depth + 1);
90
- if (key === "__proto__") {
91
- Object.defineProperty(result, key, { value: rewritten, writable: true, enumerable: true, configurable: true });
92
- } else {
93
- result[key] = rewritten;
94
- }
91
+ for (const [key, value] of Object.entries(record))
92
+ assignKey(result, key, value);
93
+ for (const key of Object.keys(record)) {
94
+ if (isDataPosition(key, inSchemaMap))
95
+ continue;
96
+ const value = record[key];
97
+ const rewritten = !inSchemaMap && key === "$ref" && typeof value === "string" && value.startsWith("#/definitions/") ? value.replace("#/definitions/", "#/$defs/") : startsNewResource(value) ? value : rewriteDefinitionsRefs(value, depth + 1, entersSchemaMap(key, inSchemaMap));
98
+ assignKey(result, key, rewritten);
95
99
  }
96
100
  return result;
97
101
  };
98
102
  const startsNewResource = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && typeof value["$id"] === "string";
99
- const renameNestedDefs = (obj, depth = 0) => {
103
+ const renameNestedDefs = (obj, depth = 0, inSchemaMap = false) => {
100
104
  assertSchemaDepth(depth, "upgradeDraft07Schema");
101
105
  if (typeof obj !== "object" || obj === null)
102
106
  return obj;
103
107
  if (Array.isArray(obj))
104
- return obj.map((item) => renameNestedDefs(item, depth + 1));
108
+ return obj.map((item) => renameNestedDefs(item, depth + 1, inSchemaMap));
105
109
  const record = obj;
106
110
  const result = {};
107
- for (const [key, value] of Object.entries(record)) {
108
- if (key === "$ref" && typeof value === "string" && value.startsWith("#/definitions/")) {
109
- result[key] = value.replace("#/definitions/", "#/$defs/");
110
- } else {
111
- const outKey = key === "definitions" ? "$defs" : key;
112
- result[outKey] = renameNestedDefs(value, depth + 1);
111
+ for (const [key, value] of Object.entries(record))
112
+ assignKey(result, key, value);
113
+ for (const key of Object.keys(record)) {
114
+ if (isDataPosition(key, inSchemaMap))
115
+ continue;
116
+ const value = record[key];
117
+ if (!inSchemaMap && key === "$ref" && typeof value === "string" && value.startsWith("#/definitions/")) {
118
+ assignKey(result, key, value.replace("#/definitions/", "#/$defs/"));
119
+ continue;
113
120
  }
121
+ const outKey = !inSchemaMap && key === "definitions" ? "$defs" : key;
122
+ if (outKey !== key)
123
+ delete result[key];
124
+ assignKey(result, outKey, renameNestedDefs(value, depth + 1, entersSchemaMap(key, inSchemaMap)));
114
125
  }
115
126
  return result;
116
127
  };
@@ -1,5 +1,10 @@
1
1
  /**
2
2
  * Parses the values of a record with a parser function.
3
- * Uses for...in instead of Object.entries() to avoid allocating an intermediate array.
3
+ *
4
+ * Own keys only. This runs on untrusted input at runtime, and a `for…in` walks
5
+ * the prototype chain — so with a polluted `Object.prototype` the parsed record
6
+ * came back carrying properties the input never had. `Object.keys` allocates an
7
+ * array where `for…in` did not; that is the cheaper half of the trade, and it
8
+ * is the form the interpreter's own benchmark measures fastest anyway.
4
9
  */
5
10
  export declare const validateRecord: (input: unknown, parser: (input: unknown) => unknown) => Record<string, unknown>;
@@ -5,7 +5,7 @@ const validateRecord = (input, parser) => {
5
5
  }
6
6
  const record = input;
7
7
  const result = {};
8
- for (const key in record) {
8
+ for (const key of Object.keys(record)) {
9
9
  const value = parser(record[key]);
10
10
  if (key === "__proto__") {
11
11
  Object.defineProperty(result, key, { value, writable: true, enumerable: true, configurable: true });
@@ -1,9 +1,12 @@
1
1
  import { assertIdScopes } from "./assert-id-scopes.js";
2
+ import { assignKey } from "./assign-key.js";
2
3
  import { buildDynamicRefMap } from "./build-dynamic-ref-map.js";
4
+ import { entersSchemaMap, isDataPosition } from "./build-resource-registry.js";
3
5
  import { extractRefs } from "./extract-refs.js";
4
6
  import { graftExternalSchemas } from "./graft-external-schemas.js";
5
7
  import { normalizeRefScopes } from "./normalize-ref-scopes.js";
6
8
  import { pruneExternalSchemas } from "./prune-external-schemas.js";
9
+ import { readKey } from "./read-key.js";
7
10
  import { refToFilename } from "./ref-to-filename.js";
8
11
  import { refToName } from "./ref-to-name.js";
9
12
  import { resolveDynamicRefs } from "./resolve-dynamic-refs.js";
@@ -35,26 +38,31 @@ const getAliasRootRef = (schema) => {
35
38
  if (typeof schema !== "object" || schema === null)
36
39
  return null;
37
40
  const record = schema;
38
- if (typeof record["$ref"] !== "string")
41
+ const ref = readKey(record, "$ref");
42
+ if (typeof ref !== "string")
39
43
  return null;
40
- return SHAPE_KEYWORDS.some((key) => key in record) ? null : record["$ref"];
44
+ return SHAPE_KEYWORDS.some((key) => Object.hasOwn(record, key)) ? null : ref;
41
45
  };
42
46
  const DEFINITION_MAP_KEYS = ["$defs", "definitions"];
43
- const expandBooleanDefinitions = (value) => {
47
+ const expandBooleanDefinitions = (value, inSchemaMap = false) => {
44
48
  if (typeof value !== "object" || value === null)
45
49
  return value;
46
50
  if (Array.isArray(value)) {
47
- const mapped = value.map(expandBooleanDefinitions);
51
+ const mapped = value.map((item) => expandBooleanDefinitions(item, inSchemaMap));
48
52
  return mapped.some((item, index) => item !== value[index]) ? mapped : value;
49
53
  }
50
54
  const record = value;
51
55
  let changed = false;
52
56
  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)
57
+ for (const [key, sub] of Object.entries(record))
58
+ assignKey(result, key, sub);
59
+ for (const key of Object.keys(record)) {
60
+ if (isDataPosition(key, inSchemaMap))
61
+ continue;
62
+ const next = !inSchemaMap && DEFINITION_MAP_KEYS.includes(key) ? expandDefinitionMap(record[key]) : expandBooleanDefinitions(record[key], entersSchemaMap(key, inSchemaMap));
63
+ if (next !== record[key])
56
64
  changed = true;
57
- result[key] = next;
65
+ assignKey(result, key, next);
58
66
  }
59
67
  return changed ? result : value;
60
68
  };
@@ -68,7 +76,7 @@ const expandDefinitionMap = (definitions) => {
68
76
  const next = definition === true ? {} : definition === false ? { not: {} } : expandBooleanDefinitions(definition);
69
77
  if (next !== definition)
70
78
  changed = true;
71
- result[name] = next;
79
+ assignKey(result, name, next);
72
80
  }
73
81
  return changed ? result : definitions;
74
82
  };
@@ -109,27 +117,48 @@ const getRootCache = (rootSchema, schemas) => {
109
117
  }
110
118
  return cache;
111
119
  };
112
- const referencesRoot = (value) => {
120
+ const referencesRoot = (value, inSchemaMap = false) => {
113
121
  if (typeof value !== "object" || value === null)
114
122
  return false;
115
123
  if (Array.isArray(value))
116
- return value.some(referencesRoot);
124
+ return value.some((item) => referencesRoot(item, inSchemaMap));
117
125
  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]))
126
+ if (!inSchemaMap) {
127
+ const ref = readKey(record, "$ref");
128
+ if (ref === ROOT_POINTER || ref === "#/")
129
+ return true;
130
+ }
131
+ for (const key of Object.keys(record)) {
132
+ if (isDataPosition(key, inSchemaMap))
133
+ continue;
134
+ if (referencesRoot(record[key], entersSchemaMap(key, inSchemaMap)))
122
135
  return true;
136
+ }
123
137
  return false;
124
138
  };
125
- const rewriteRootRefs = (value, rootSelfRef) => {
139
+ const copyValue = (value) => {
140
+ if (typeof value !== "object" || value === null)
141
+ return value;
142
+ if (Array.isArray(value))
143
+ return value.map(copyValue);
144
+ const out = {};
145
+ for (const [key, sub] of Object.entries(value))
146
+ assignKey(out, key, copyValue(sub));
147
+ return out;
148
+ };
149
+ const rewriteRootRefs = (value, rootSelfRef, inSchemaMap = false) => {
126
150
  if (typeof value !== "object" || value === null)
127
151
  return value;
128
152
  if (Array.isArray(value))
129
- return value.map((item) => rewriteRootRefs(item, rootSelfRef));
153
+ return value.map((item) => rewriteRootRefs(item, rootSelfRef, inSchemaMap));
130
154
  const out = {};
131
- for (const [key, sub] of Object.entries(value)) {
132
- out[key] = key === "$ref" && (sub === ROOT_POINTER || sub === "#/") ? rootSelfRef : rewriteRootRefs(sub, rootSelfRef);
155
+ const record = value;
156
+ for (const key of Object.keys(record)) {
157
+ if (isDataPosition(key, inSchemaMap)) {
158
+ assignKey(out, key, copyValue(record[key]));
159
+ continue;
160
+ }
161
+ assignKey(out, key, !inSchemaMap && key === "$ref" && (record[key] === ROOT_POINTER || record[key] === "#/") ? rootSelfRef : rewriteRootRefs(record[key], rootSelfRef, entersSchemaMap(key, inSchemaMap)));
133
162
  }
134
163
  return out;
135
164
  };
@@ -165,10 +194,10 @@ const dynamicPointerRefs = (value, into = /* @__PURE__ */ new Set()) => {
165
194
  return into;
166
195
  }
167
196
  const record = value;
168
- const ref = record["$dynamicRef"];
197
+ const ref = readKey(record, "$dynamicRef");
169
198
  if (typeof ref === "string" && ref.startsWith("#/"))
170
199
  into.add(ref);
171
- for (const key in record)
200
+ for (const key of Object.keys(record))
172
201
  dynamicPointerRefs(record[key], into);
173
202
  return into;
174
203
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/helpers",
3
- "version": "0.15.2",
3
+ "version": "0.15.4",
4
4
  "description": "Shared utilities for the mjst code generation ecosystem.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
package/src/has-ref.ts CHANGED
@@ -4,7 +4,7 @@ export const hasRef = (value: unknown): value is { $ref: string } & Record<strin
4
4
  typeof value === 'object' &&
5
5
  value !== null &&
6
6
  !Array.isArray(value) &&
7
- '$ref' in value &&
7
+ Object.hasOwn(value, '$ref') &&
8
8
  typeof (value as { $ref: unknown }).$ref === 'string'
9
9
  )
10
10
  }
@@ -2,7 +2,12 @@ import { isObject } from './is-object'
2
2
 
3
3
  /**
4
4
  * Parses the values of a record with a parser function.
5
- * Uses for...in instead of Object.entries() to avoid allocating an intermediate array.
5
+ *
6
+ * Own keys only. This runs on untrusted input at runtime, and a `for…in` walks
7
+ * the prototype chain — so with a polluted `Object.prototype` the parsed record
8
+ * came back carrying properties the input never had. `Object.keys` allocates an
9
+ * array where `for…in` did not; that is the cheaper half of the trade, and it
10
+ * is the form the interpreter's own benchmark measures fastest anyway.
6
11
  */
7
12
  export const validateRecord = (input: unknown, parser: (input: unknown) => unknown) => {
8
13
  if (!isObject(input)) {
@@ -11,7 +16,7 @@ export const validateRecord = (input: unknown, parser: (input: unknown) => unkno
11
16
 
12
17
  const record = input as Record<string, unknown>
13
18
  const result: Record<string, unknown> = {}
14
- for (const key in record) {
19
+ for (const key of Object.keys(record)) {
15
20
  const value = parser(record[key])
16
21
  // A plain assignment of `__proto__` invokes the prototype setter and
17
22
  // corrupts `result`'s prototype (a prototype-pollution vector for untrusted