@amritk/helpers 0.10.0 → 0.10.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.
Files changed (37) hide show
  1. package/dist/escape-regex-pattern.d.ts +15 -5
  2. package/dist/escape-regex-pattern.js +48 -10
  3. package/dist/generate-index-barrel.js +3 -2
  4. package/dist/generate-type-definition.js +72 -53
  5. package/dist/multiple-of-check.d.ts +4 -0
  6. package/dist/multiple-of-check.js +30 -0
  7. package/dist/parse-documentation.js +6 -2
  8. package/dist/ref-to-name.js +17 -2
  9. package/dist/resolve-dynamic-refs.js +24 -0
  10. package/dist/safe-accessor.d.ts +3 -3
  11. package/dist/safe-accessor.js +10 -6
  12. package/dist/validate-record.js +11 -1
  13. package/dist/walk-ref-graph.js +4 -2
  14. package/package.json +4 -2
  15. package/src/build-dynamic-ref-map.ts +42 -0
  16. package/src/derive-root-type-name.ts +42 -0
  17. package/src/escape-regex-pattern.ts +59 -0
  18. package/src/extract-dynamic-anchor-defs.ts +33 -0
  19. package/src/extract-refs.ts +73 -0
  20. package/src/generate-index-barrel.ts +63 -0
  21. package/src/generate-type-definition.ts +599 -0
  22. package/src/has-ref.ts +10 -0
  23. package/src/is-object.ts +15 -0
  24. package/src/mjst-extension.ts +81 -0
  25. package/src/multiple-of-check.ts +32 -0
  26. package/src/parse-documentation.ts +177 -0
  27. package/src/ref-to-filename.ts +116 -0
  28. package/src/ref-to-name.ts +54 -0
  29. package/src/resolve-dynamic-refs.ts +74 -0
  30. package/src/resolve-ref.ts +82 -0
  31. package/src/safe-accessor.ts +53 -0
  32. package/src/schema-guards.ts +195 -0
  33. package/src/unknown-key-check.ts +68 -0
  34. package/src/upgrade-draft07-schema.ts +179 -0
  35. package/src/validate-array.ts +15 -0
  36. package/src/validate-record.ts +28 -0
  37. package/src/walk-ref-graph.ts +186 -0
@@ -1,16 +1,26 @@
1
1
  /**
2
2
  * Escapes a JSON Schema `pattern` so it can be embedded between the slashes of
3
- * a generated regex literal (`/…/`).
3
+ * a generated regex literal (`/…/`), and validates that the pattern is a legal
4
+ * regex at generation time.
4
5
  *
5
6
  * A `pattern` is an ECMA-262 regex *body*, and the generated text goes into a
6
7
  * regex literal — not a string literal — so backslashes are regex syntax and
7
8
  * must be left exactly as-is (doubling `\d` to `\\d` would change it from "a
8
- * digit" to "a literal backslash followed by d"). The only character that would
9
- * corrupt the surrounding literal is an *unescaped* `/`, which would close it
10
- * early. So we escape bare slashes to `\/` while leaving every existing escape
11
- * sequence (including an already-escaped `\/`) untouched.
9
+ * digit" to "a literal backslash followed by d"). Two things would otherwise
10
+ * corrupt the surrounding literal:
11
+ * - an *unescaped* `/`, which would close the literal early; and
12
+ * - a raw line terminator (LF, CR, U+2028, U+2029), which is not allowed
13
+ * inside a regex literal and would split the emitted `/…/` across lines (a
14
+ * syntax error). Each is rewritten to its backslash escape, which matches
15
+ * the identical character, so the regex's meaning is unchanged.
16
+ *
17
+ * Additionally, an *invalid* pattern (e.g. `([`) would be emitted verbatim as
18
+ * `/([/…` and produce output that does not parse. We compile the pattern with
19
+ * `new RegExp` here and throw a clear generator-time error instead, so a bad
20
+ * schema fails loudly during generation rather than emitting broken code.
12
21
  *
13
22
  * @example
14
23
  * escapeRegexPattern('\\d{4}/\\d{2}') // → '\\d{4}\\/\\d{2}' (i.e. \d{4}\/\d{2})
24
+ * @throws if `pattern` is not a valid regular expression.
15
25
  */
16
26
  export declare const escapeRegexPattern: (pattern: string) => string;
@@ -1,20 +1,58 @@
1
1
  /**
2
2
  * Escapes a JSON Schema `pattern` so it can be embedded between the slashes of
3
- * a generated regex literal (`/…/`).
3
+ * a generated regex literal (`/…/`), and validates that the pattern is a legal
4
+ * regex at generation time.
4
5
  *
5
6
  * A `pattern` is an ECMA-262 regex *body*, and the generated text goes into a
6
7
  * regex literal — not a string literal — so backslashes are regex syntax and
7
8
  * must be left exactly as-is (doubling `\d` to `\\d` would change it from "a
8
- * digit" to "a literal backslash followed by d"). The only character that would
9
- * corrupt the surrounding literal is an *unescaped* `/`, which would close it
10
- * early. So we escape bare slashes to `\/` while leaving every existing escape
11
- * sequence (including an already-escaped `\/`) untouched.
9
+ * digit" to "a literal backslash followed by d"). Two things would otherwise
10
+ * corrupt the surrounding literal:
11
+ * - an *unescaped* `/`, which would close the literal early; and
12
+ * - a raw line terminator (LF, CR, U+2028, U+2029), which is not allowed
13
+ * inside a regex literal and would split the emitted `/…/` across lines (a
14
+ * syntax error). Each is rewritten to its backslash escape, which matches
15
+ * the identical character, so the regex's meaning is unchanged.
16
+ *
17
+ * Additionally, an *invalid* pattern (e.g. `([`) would be emitted verbatim as
18
+ * `/([/…` and produce output that does not parse. We compile the pattern with
19
+ * `new RegExp` here and throw a clear generator-time error instead, so a bad
20
+ * schema fails loudly during generation rather than emitting broken code.
12
21
  *
13
22
  * @example
14
23
  * escapeRegexPattern('\\d{4}/\\d{2}') // → '\\d{4}\\/\\d{2}' (i.e. \d{4}\/\d{2})
24
+ * @throws if `pattern` is not a valid regular expression.
15
25
  */
16
- export const escapeRegexPattern = (pattern) =>
17
- // Match either an escape sequence (`\` + any char, kept verbatim) or a bare
18
- // `/` (escaped). Consuming escape pairs first means the slash in `\/` is never
19
- // seen as bare, so it is not double-escaped.
20
- pattern.replace(/\\[\s\S]|\//g, (match) => (match === '/' ? '\\/' : match));
26
+ export const escapeRegexPattern = (pattern) => {
27
+ // Validate at generation time — an invalid pattern must fail here, not emit
28
+ // a `/([/` literal that breaks the generated file.
29
+ try {
30
+ new RegExp(pattern);
31
+ }
32
+ catch (error) {
33
+ throw new Error(`Invalid regex pattern ${JSON.stringify(pattern)}: ${error instanceof Error ? error.message : String(error)}`);
34
+ }
35
+ // Line terminators, keyed by code point, and the backslash escape each maps to.
36
+ // These are the four characters disallowed *raw* inside a regex literal.
37
+ const lineTerminatorEscapes = {
38
+ 0x0a: '\\n', // LF
39
+ 0x0d: '\\r', // CR
40
+ 0x2028: '\\u2028', // LINE SEPARATOR
41
+ 0x2029: '\\u2029', // PARAGRAPH SEPARATOR
42
+ };
43
+ // Match either an escape sequence (`\` + any char, kept verbatim) or a single
44
+ // character that would corrupt the literal (a bare `/` or a line terminator).
45
+ // The line terminators are written as `\u….` escapes so this source file is
46
+ // itself free of the raw characters it guards against. Consuming escape pairs
47
+ // first means the slash in `\/` is never seen as bare, so it is not
48
+ // double-escaped.
49
+ return pattern.replace(/\\[\s\S]|[/\n\r\u2028\u2029]/g, (match) => {
50
+ if (match === '/')
51
+ return '\\/';
52
+ const terminatorEscape = lineTerminatorEscapes[match.charCodeAt(0)];
53
+ if (terminatorEscape !== undefined && match.length === 1)
54
+ return terminatorEscape;
55
+ // An escape pair like `\/` or `\d`: keep exactly as authored.
56
+ return match;
57
+ });
58
+ };
@@ -31,12 +31,13 @@ export const generateIndexBarrel = (files, options = {}) => {
31
31
  constNames.push(match[1]);
32
32
  if (typeNames.length === 0 && constNames.length === 0)
33
33
  continue;
34
+ // `.js` extension so the barrel resolves under Node ESM, not only Bun.
34
35
  if (typesOnly) {
35
- indexContent += `export type { ${typeNames.join(', ')} } from './${moduleName}';\n`;
36
+ indexContent += `export type { ${typeNames.join(', ')} } from './${moduleName}.js';\n`;
36
37
  }
37
38
  else {
38
39
  const typeExports = typeNames.map((name) => `type ${name}`);
39
- indexContent += `export { ${[...typeExports, ...constNames].join(', ')} } from './${moduleName}';\n`;
40
+ indexContent += `export { ${[...typeExports, ...constNames].join(', ')} } from './${moduleName}.js';\n`;
40
41
  }
41
42
  }
42
43
  return indexContent;
@@ -68,11 +68,21 @@ const isObjectLikeSchema = (schema) => {
68
68
  const getBooleanSubSchemaType = (schema) => {
69
69
  return schema ? 'unknown' : 'never';
70
70
  };
71
+ /**
72
+ * Renders a possibly multi-line description as JSDoc body lines, prefixing each
73
+ * line with `${indent}* `. Blank lines become a bare `${indent}*` so we never
74
+ * emit trailing whitespace. Without this, embedded newlines would leave
75
+ * continuation lines unprefixed and break the comment block.
76
+ */
77
+ const renderJsDocBody = (description, indent) => description
78
+ .split('\n')
79
+ .map((line) => (line.length > 0 ? `${indent}* ${line}\n` : `${indent}*\n`))
80
+ .join('');
71
81
  const buildJsDocBlock = (title, description, commentUrl) => {
72
82
  let block = `/**\n`;
73
83
  block += `* ${title}\n`;
74
84
  block += `*\n`;
75
- block += `* ${description}\n`;
85
+ block += renderJsDocBody(description, '');
76
86
  if (commentUrl?.startsWith('http')) {
77
87
  block += `* \n`;
78
88
  block += `* @see {@link ${commentUrl}}\n`;
@@ -80,6 +90,19 @@ const buildJsDocBlock = (title, description, commentUrl) => {
80
90
  block += `*/\n`;
81
91
  return block;
82
92
  };
93
+ /**
94
+ * Builds the inline JSDoc comment that precedes a generated property. A
95
+ * single-line description stays compact (` /** text *\/`); a multi-line
96
+ * description expands into an asterisk-prefixed block so every line is
97
+ * commented. The returned string always ends with a newline, ready for the
98
+ * property declaration to follow.
99
+ */
100
+ const buildInlinePropertyComment = (description) => {
101
+ if (!description.includes('\n')) {
102
+ return ` /** ${description} */\n`;
103
+ }
104
+ return ` /**\n${renderJsDocBody(description, ' ')} */\n`;
105
+ };
83
106
  /**
84
107
  * Converts a JSON Schema type to its TypeScript equivalent, applying any
85
108
  * `x-mjst` brand. Branding is type-level only, so we compute the underlying
@@ -93,6 +116,35 @@ const getTypeScriptType = (schema, options = {}) => {
93
116
  };
94
117
  /** Wraps a `Record<...>` in `Readonly<...>` when readonly output is requested. */
95
118
  const recordType = (keyType, valueType, options) => options.readonly ? `Readonly<Record<${keyType}, ${valueType}>>` : `Record<${keyType}, ${valueType}>`;
119
+ /**
120
+ * Builds the `Record<…>` type for a schema's `patternProperties`. Every pattern's
121
+ * value type is unioned (deduplicated) rather than only the first being used, so
122
+ * `{ '^a': string-schema, '^b': number-schema }` becomes `Record<string, string |
123
+ * number>` instead of silently dropping the second pattern. The template-literal
124
+ * `` `x-${string}` `` key is kept only when the sole pattern is the `^x-` vendor
125
+ * convention. Returns `undefined` when there are no usable patterns.
126
+ */
127
+ const patternPropertiesRecordType = (patternProperties, options) => {
128
+ const entries = Object.entries(patternProperties);
129
+ if (entries.length === 0)
130
+ return undefined;
131
+ const seen = new Set();
132
+ const valueTypes = [];
133
+ for (const [, value] of entries) {
134
+ const valueType = typeof value === 'boolean' ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options);
135
+ if (!seen.has(valueType)) {
136
+ seen.add(valueType);
137
+ valueTypes.push(valueType);
138
+ }
139
+ }
140
+ if (valueTypes.length === 0)
141
+ return undefined;
142
+ const valueType = valueTypes.join(' | ');
143
+ // The `^x-` vendor-extension convention maps to a template-literal key, but only
144
+ // when it is the single pattern (a union of key patterns can't be expressed).
145
+ const keyType = entries.length === 1 && entries[0]?.[0] === '^x-' ? '`x-${string}`' : 'string';
146
+ return recordType(keyType, valueType, options);
147
+ };
96
148
  /**
97
149
  * Converts a JSON Schema type to its TypeScript equivalent, ignoring any brand.
98
150
  * Recursively handles nested objects and arrays.
@@ -149,14 +201,6 @@ const getUnbrandedType = (schema, options = {}) => {
149
201
  }
150
202
  return enumUnion;
151
203
  }
152
- // Handle multi-value enum - union of literal types
153
- if (schema.enum && schema.enum.length > 1) {
154
- let multiEnumUnion = JSON.stringify(schema.enum[0]);
155
- for (let i = 1; i < schema.enum.length; i++) {
156
- multiEnumUnion += ' | ' + JSON.stringify(schema.enum[i]);
157
- }
158
- return multiEnumUnion;
159
- }
160
204
  // Handle union types (oneOf, anyOf) - check this before returning unknown
161
205
  if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
162
206
  // schema.oneOf[0] is safe: we guard with .length > 0 above
@@ -201,19 +245,9 @@ const getUnbrandedType = (schema, options = {}) => {
201
245
  return recordType('string', getTypeScriptType(schema.additionalProperties, options), options);
202
246
  }
203
247
  if (schema.patternProperties && typeof schema.patternProperties === 'object') {
204
- const firstEntry = Object.entries(schema.patternProperties)[0];
205
- if (firstEntry) {
206
- const [pattern, value] = firstEntry;
207
- if (value !== undefined) {
208
- const valueType = typeof value === 'boolean' ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options);
209
- // The ^x- pattern is a common JSON Schema convention for vendor extensions
210
- // that maps naturally to the TypeScript template literal `x-${string}`
211
- if (pattern === '^x-') {
212
- return recordType('`x-${string}`', valueType, options);
213
- }
214
- return recordType('string', valueType, options);
215
- }
216
- }
248
+ const record = patternPropertiesRecordType(schema.patternProperties, options);
249
+ if (record !== undefined)
250
+ return record;
217
251
  }
218
252
  if (schema.default !== undefined) {
219
253
  if (typeof schema.default === 'string') {
@@ -279,6 +313,9 @@ const getUnbrandedType = (schema, options = {}) => {
279
313
  case 'object':
280
314
  if (schema.properties) {
281
315
  const readonlyPrefix = options.readonly ? 'readonly ' : '';
316
+ // Build the required-key set once instead of an O(required) `includes`
317
+ // per property (O(properties × required) for a wide object).
318
+ const requiredSet = new Set(Array.isArray(schema.required) ? schema.required : []);
282
319
  const hasDescriptions = Object.values(schema.properties).some((p) => isSchemaObject(p) && (typeof p.description === 'string' || typeof p.$comment === 'string'));
283
320
  if (hasDescriptions) {
284
321
  let properties = '';
@@ -286,7 +323,7 @@ const getUnbrandedType = (schema, options = {}) => {
286
323
  for (const key in schema.properties) {
287
324
  // schema.properties[key] is safe: key comes from iterating schema.properties
288
325
  const propSchema = schema.properties[key];
289
- const isRequired = schema.required?.includes(key) ?? false;
326
+ const isRequired = requiredSet.has(key);
290
327
  const optional = isRequired ? '' : '?';
291
328
  const propType = getTypeScriptType(propSchema, options);
292
329
  const inlineDescription = isSchemaObject(propSchema) && typeof propSchema.description === 'string'
@@ -299,9 +336,8 @@ const getUnbrandedType = (schema, options = {}) => {
299
336
  first = false;
300
337
  if (inlineDescription) {
301
338
  properties +=
302
- ' /** ' +
303
- inlineDescription +
304
- ' */\n ' +
339
+ buildInlinePropertyComment(inlineDescription) +
340
+ ' ' +
305
341
  readonlyPrefix +
306
342
  safeKey(key) +
307
343
  optional +
@@ -320,7 +356,7 @@ const getUnbrandedType = (schema, options = {}) => {
320
356
  for (const key in schema.properties) {
321
357
  // schema.properties[key] is safe: key comes from iterating schema.properties
322
358
  const propSchema = schema.properties[key];
323
- const isRequired = schema.required?.includes(key) ?? false;
359
+ const isRequired = requiredSet.has(key);
324
360
  const optional = isRequired ? '' : '?';
325
361
  const propType = getTypeScriptType(propSchema, options);
326
362
  if (!first)
@@ -337,17 +373,9 @@ const getUnbrandedType = (schema, options = {}) => {
337
373
  }
338
374
  // Handle patternProperties as a Record type
339
375
  if (schema.patternProperties && typeof schema.patternProperties === 'object') {
340
- const firstEntry = Object.entries(schema.patternProperties)[0];
341
- if (firstEntry) {
342
- const [pattern, patternVal] = firstEntry;
343
- if (patternVal) {
344
- const valueType = getTypeScriptType(patternVal, options);
345
- if (pattern === '^x-') {
346
- return recordType('`x-${string}`', valueType, options);
347
- }
348
- return recordType('string', valueType, options);
349
- }
350
- }
376
+ const record = patternPropertiesRecordType(schema.patternProperties, options);
377
+ if (record !== undefined)
378
+ return record;
351
379
  }
352
380
  return 'object';
353
381
  // Default to unknown
@@ -395,23 +423,12 @@ export const generateTypeDefinition = (schema, typeName, options = {}) => {
395
423
  Object.keys(normalizedSchema.patternProperties).length > 0;
396
424
  // Handle objects with only patternProperties (no fixed properties)
397
425
  if (!hasProperties && hasPatternProperties && normalizedSchema.patternProperties) {
398
- const firstEntry = Object.entries(normalizedSchema.patternProperties)[0];
399
- const firstPattern = firstEntry?.[0];
400
- const firstPatternProperty = firstEntry?.[1];
401
- if (firstPatternProperty === undefined) {
402
- return `export type ${typeName} = Record<string, unknown>;`;
403
- }
404
- const patternPropType = typeof firstPatternProperty === 'boolean'
405
- ? getBooleanSubSchemaType(firstPatternProperty)
406
- : getTypeScriptType(firstPatternProperty, options);
407
- // The ^x- pattern is a common JSON Schema convention for vendor extensions
408
- // that maps naturally to the TypeScript template literal `x-${string}`
409
- const keyType = firstPattern === '^x-' ? '`x-${string}`' : 'string';
426
+ const record = patternPropertiesRecordType(normalizedSchema.patternProperties, options) ?? 'Record<string, unknown>';
410
427
  let result = '';
411
428
  if (jsDocTitle && jsDocDescription) {
412
429
  result += buildJsDocBlock(jsDocTitle, jsDocDescription);
413
430
  }
414
- result += `export type ${typeName} = ${recordType(keyType, patternPropType, options)};`;
431
+ result += `export type ${typeName} = ${record};`;
415
432
  return result;
416
433
  }
417
434
  // Handle objects with only additionalProperties (no fixed properties)
@@ -425,12 +442,13 @@ export const generateTypeDefinition = (schema, typeName, options = {}) => {
425
442
  return result;
426
443
  }
427
444
  const schemaProps = normalizedSchema.properties ?? {};
445
+ const requiredSet = new Set(Array.isArray(normalizedSchema.required) ? normalizedSchema.required : []);
428
446
  let properties = '';
429
447
  let isFirstProp = true;
430
448
  for (const key in schemaProps) {
431
449
  // schemaProps[key] is safe: key comes from iterating schemaProps
432
450
  const propSchema = schemaProps[key];
433
- const isRequired = normalizedSchema.required?.includes(key) ?? false;
451
+ const isRequired = requiredSet.has(key);
434
452
  const optional = isRequired ? '' : '?';
435
453
  const propType = getTypeScriptType(propSchema, options);
436
454
  const quotedKey = readonlyPrefix + safeKey(key);
@@ -444,7 +462,8 @@ export const generateTypeDefinition = (schema, typeName, options = {}) => {
444
462
  ? propSchema.$comment
445
463
  : undefined;
446
464
  if (inlineDescription) {
447
- properties += ' /** ' + inlineDescription + ' */\n ' + quotedKey + optional + ': ' + propType + ';';
465
+ properties +=
466
+ buildInlinePropertyComment(inlineDescription) + ' ' + quotedKey + optional + ': ' + propType + ';';
448
467
  }
449
468
  else {
450
469
  properties += ' ' + quotedKey + optional + ': ' + propType + ';';
@@ -0,0 +1,4 @@
1
+ /** Boolean expression that is TRUE when `valueExpr` is a valid multiple of `divisor`. */
2
+ export declare const multipleOfPassExpr: (valueExpr: string, divisor: number) => string;
3
+ /** Boolean expression that is TRUE when `valueExpr` is NOT a multiple of `divisor` (the error condition). */
4
+ export declare const multipleOfFailExpr: (valueExpr: string, divisor: number) => string;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Emits code for a JSON Schema `multipleOf` check that agrees with the runtime
3
+ * interpreter (`packages/runtime-validators/src/interpreter/interpret.ts`).
4
+ *
5
+ * The naive `x % m === 0` is float-wrong: IEEE-754 makes `0.3 % 0.1` evaluate to
6
+ * `0.0999…`, so `0.3` would spuriously fail `multipleOf: 0.1`. The interpreter
7
+ * instead divides and compares the quotient to its nearest integer within a
8
+ * tolerance that *scales with the quotient's magnitude* — a fixed epsilon falsely
9
+ * rejects large values (e.g. `1234567.89` against `multipleOf: 0.01`) whose
10
+ * representation error in the quotient already exceeds it. Keeping the emitted
11
+ * check identical to the interpreter's keeps generated validators/parsers and the
12
+ * interpreter from disagreeing on the same document.
13
+ *
14
+ * `valueExpr` is inlined three times, so it must be a side-effect-free expression
15
+ * (a property read or a cached variable — which is all the generators ever pass).
16
+ */
17
+ const quotientTolerance = (valueExpr, divisor) => {
18
+ const q = `${valueExpr} / ${divisor}`;
19
+ return { q, tol: `1e-8 * Math.max(1, Math.abs(${q}))` };
20
+ };
21
+ /** Boolean expression that is TRUE when `valueExpr` is a valid multiple of `divisor`. */
22
+ export const multipleOfPassExpr = (valueExpr, divisor) => {
23
+ const { q, tol } = quotientTolerance(valueExpr, divisor);
24
+ return `Math.abs(${q} - Math.round(${q})) <= ${tol}`;
25
+ };
26
+ /** Boolean expression that is TRUE when `valueExpr` is NOT a multiple of `divisor` (the error condition). */
27
+ export const multipleOfFailExpr = (valueExpr, divisor) => {
28
+ const { q, tol } = quotientTolerance(valueExpr, divisor);
29
+ return `Math.abs(${q} - Math.round(${q})) > ${tol}`;
30
+ };
@@ -29,9 +29,13 @@ export const parseDocumentation = (markdownDocumentation, commentUrl, fallbackCo
29
29
  const headingHashes = headingLevelMatch?.[1] ?? '####';
30
30
  const subHeadingHashes = headingHashes + '#';
31
31
  // Find the section in the markdown
32
- // Match the section heading and capture everything until the next same-level heading or end of file
32
+ // Match the section heading and capture everything until the next same-level heading or end of file.
33
+ // `sectionTitle` comes from the URL fragment, so escape any regex metacharacters
34
+ // before interpolating — otherwise a fragment containing `+`, `(`, etc. throws a
35
+ // SyntaxError that the outer catch then mislabels as a fetch failure.
33
36
  const escapedHashes = headingHashes.replace(/#/g, '\\#');
34
- const sectionRegex = new RegExp(`${escapedHashes}\\s+${sectionTitle}\\s*\\n([\\s\\S]*?)(?=\\n${escapedHashes}\\s|$)`, 'i');
37
+ const escapedTitle = sectionTitle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
38
+ const sectionRegex = new RegExp(`${escapedHashes}\\s+${escapedTitle}\\s*\\n([\\s\\S]*?)(?=\\n${escapedHashes}\\s|$)`, 'i');
35
39
  const sectionMatch = markdown.match(sectionRegex);
36
40
  if (!sectionMatch) {
37
41
  return null;
@@ -1,20 +1,35 @@
1
1
  import { refToFilename } from './ref-to-filename.js';
2
2
  /**
3
- * Converts a kebab-case filename to PascalCase, appending an optional suffix.
3
+ * Converts a filename-like string to a PascalCase TypeScript identifier,
4
+ * appending an optional suffix.
5
+ *
6
+ * Word boundaries are *any* run of characters that cannot appear in a JS
7
+ * identifier — not just `-` — so a dotted key like `io.k8s.api.core.v1.Pod`
8
+ * becomes `IoK8sApiCoreV1Pod` instead of the invalid `Io.k8s.api.core.v1.pod`.
9
+ * A leading digit is prefixed with `_`, and an otherwise-empty result falls back
10
+ * to `_`, so the output is always a usable identifier.
4
11
  *
5
12
  * @example
6
13
  * ```ts
7
14
  * kebabToPascal('server-variable') // 'ServerVariable'
8
15
  * kebabToPascal('channel') // 'Channel'
9
16
  * kebabToPascal('channel', 'Object') // 'ChannelObject'
17
+ * kebabToPascal('io.k8s.api.core.v1.pod') // 'IoK8sApiCoreV1Pod'
18
+ * kebabToPascal('123abc') // '_123abc'
10
19
  * ```
11
20
  */
12
21
  const kebabToPascal = (kebab, suffix) => {
13
- const words = kebab.split('-');
22
+ const words = kebab.split(/[^A-Za-z0-9]+/);
14
23
  let pascalCase = '';
15
24
  for (const word of words) {
25
+ if (word === '')
26
+ continue;
16
27
  pascalCase += word.charAt(0).toUpperCase() + word.slice(1);
17
28
  }
29
+ if (pascalCase === '')
30
+ pascalCase = '_';
31
+ else if (/^[0-9]/.test(pascalCase))
32
+ pascalCase = `_${pascalCase}`;
18
33
  return pascalCase + suffix;
19
34
  };
20
35
  /**
@@ -18,6 +18,12 @@ export const resolveDynamicRefs = (schema, dynamicRefMap) => {
18
18
  if (Object.keys(dynamicRefMap).length === 0) {
19
19
  return schema;
20
20
  }
21
+ // Cheap read-only pre-scan: most subschemas carry no `$dynamicRef`, so returning
22
+ // the original untouched avoids a full deep clone (and its allocation) on every
23
+ // node of every generator's walk when the document as a whole *does* use them.
24
+ if (!containsDynamicRef(schema)) {
25
+ return schema;
26
+ }
21
27
  const clone = JSON.parse(JSON.stringify(schema));
22
28
  const walk = (obj) => {
23
29
  if (typeof obj !== 'object' || obj === null) {
@@ -43,3 +49,21 @@ export const resolveDynamicRefs = (schema, dynamicRefMap) => {
43
49
  walk(clone);
44
50
  return clone;
45
51
  };
52
+ /** True if `value` contains a `$dynamicRef` string anywhere in its subtree. */
53
+ const containsDynamicRef = (value) => {
54
+ if (typeof value !== 'object' || value === null)
55
+ return false;
56
+ if (Array.isArray(value)) {
57
+ for (const item of value)
58
+ if (containsDynamicRef(item))
59
+ return true;
60
+ return false;
61
+ }
62
+ const record = value;
63
+ if (typeof record['$dynamicRef'] === 'string')
64
+ return true;
65
+ for (const key in record)
66
+ if (containsDynamicRef(record[key]))
67
+ return true;
68
+ return false;
69
+ };
@@ -9,8 +9,8 @@
9
9
  *
10
10
  * @example
11
11
  * safeAccessor("input", "name") // "input.name"
12
- * safeAccessor("input?", "x-linkedin") // "input?.['x-linkedin']"
13
- * safeAccessor("input", "x-linkedin") // "input['x-linkedin']"
12
+ * safeAccessor("input?", "x-linkedin") // 'input?.["x-linkedin"]'
13
+ * safeAccessor("input", "x-linkedin") // 'input["x-linkedin"]'
14
14
  */
15
15
  export declare const safeAccessor: (variable: string, key: string) => string;
16
16
  /**
@@ -19,6 +19,6 @@ export declare const safeAccessor: (variable: string, key: string) => string;
19
19
  *
20
20
  * @example
21
21
  * safeKey("name") // "name"
22
- * safeKey("x-linkedin") // "'x-linkedin'"
22
+ * safeKey("x-linkedin") // '"x-linkedin"'
23
23
  */
24
24
  export declare const safeKey: (key: string) => string;
@@ -15,18 +15,21 @@ const JS_IDENTIFIER = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
15
15
  *
16
16
  * @example
17
17
  * safeAccessor("input", "name") // "input.name"
18
- * safeAccessor("input?", "x-linkedin") // "input?.['x-linkedin']"
19
- * safeAccessor("input", "x-linkedin") // "input['x-linkedin']"
18
+ * safeAccessor("input?", "x-linkedin") // 'input?.["x-linkedin"]'
19
+ * safeAccessor("input", "x-linkedin") // 'input["x-linkedin"]'
20
20
  */
21
21
  export const safeAccessor = (variable, key) => {
22
22
  if (JS_IDENTIFIER.test(key)) {
23
23
  return `${variable}.${key}`;
24
24
  }
25
+ // Bracket keys are schema-controlled, so escape via JSON.stringify — a key like
26
+ // `it's` or `a']; evil(); //` would otherwise break or hijack the generated code.
27
+ const literal = JSON.stringify(key);
25
28
  // Handle optional chaining: "input?" -> "input?.['key']"
26
29
  if (variable.endsWith('?')) {
27
- return `${variable}.['${key}']`;
30
+ return `${variable}.[${literal}]`;
28
31
  }
29
- return `${variable}['${key}']`;
32
+ return `${variable}[${literal}]`;
30
33
  };
31
34
  /**
32
35
  * Generates a safe property key for use in object literals.
@@ -34,11 +37,12 @@ export const safeAccessor = (variable, key) => {
34
37
  *
35
38
  * @example
36
39
  * safeKey("name") // "name"
37
- * safeKey("x-linkedin") // "'x-linkedin'"
40
+ * safeKey("x-linkedin") // '"x-linkedin"'
38
41
  */
39
42
  export const safeKey = (key) => {
40
43
  if (JS_IDENTIFIER.test(key)) {
41
44
  return key;
42
45
  }
43
- return `'${key}'`;
46
+ // Schema-controlled keys must be escaped; a bare-quoted `it's` produces broken TS.
47
+ return JSON.stringify(key);
44
48
  };
@@ -10,7 +10,17 @@ export const validateRecord = (input, parser) => {
10
10
  const record = input;
11
11
  const result = {};
12
12
  for (const key in record) {
13
- result[key] = parser(record[key]);
13
+ const value = parser(record[key]);
14
+ // A plain assignment of `__proto__` invokes the prototype setter and
15
+ // corrupts `result`'s prototype (a prototype-pollution vector for untrusted
16
+ // input). Define it as an own data property instead so it round-trips as a
17
+ // normal key, matching every other property.
18
+ if (key === '__proto__') {
19
+ Object.defineProperty(result, key, { value, writable: true, enumerable: true, configurable: true });
20
+ }
21
+ else {
22
+ result[key] = value;
23
+ }
14
24
  }
15
25
  return result;
16
26
  };
@@ -90,8 +90,10 @@ export const walkRefGraph = (rootSchema, rootTypeName, options, visit) => {
90
90
  ...cachedExtractRefs(cache, upgraded),
91
91
  ...extractDynamicAnchorDefs(upgraded),
92
92
  ];
93
- while (queue.length > 0) {
94
- const ref = queue.shift();
93
+ // Advance a read cursor instead of `queue.shift()`, whose O(n) element move
94
+ // makes draining a large ref graph quadratic.
95
+ for (let head = 0; head < queue.length; head++) {
96
+ const ref = queue[head];
95
97
  if (!ref || processedRefs.has(ref))
96
98
  continue;
97
99
  processedRefs.add(ref);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/helpers",
3
- "version": "0.10.0",
3
+ "version": "0.10.2",
4
4
  "description": "Shared utilities for the mjst code generation ecosystem.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -20,7 +20,9 @@
20
20
  "url": "https://github.com/amritk/mjst/issues"
21
21
  },
22
22
  "files": [
23
- "dist"
23
+ "dist",
24
+ "src/**/*.ts",
25
+ "!src/**/*.test.ts"
24
26
  ],
25
27
  "publishConfig": {
26
28
  "access": "public"
@@ -0,0 +1,42 @@
1
+ import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
2
+
3
+ import { isSchemaObject } from './schema-guards'
4
+
5
+ /**
6
+ * Builds a map of $dynamicRef anchor values to their corresponding $ref paths.
7
+ *
8
+ * JSON Schema 2020-12 uses $dynamicAnchor and $dynamicRef for late-binding references.
9
+ * In the OpenAPI spec, $dynamicAnchor: "meta" on the schema definition allows properties
10
+ * like media-type.schema to reference it via $dynamicRef: "#meta".
11
+ *
12
+ * This function scans all $defs for entries with $dynamicAnchor and builds a lookup
13
+ * so we can convert $dynamicRef values to concrete $ref paths.
14
+ *
15
+ * @example
16
+ * // Given a schema with $defs.schema having $dynamicAnchor: "meta"
17
+ * buildDynamicRefMap(rootSchema)
18
+ * // Returns: { "#meta": "#/$defs/schema" }
19
+ */
20
+ export const buildDynamicRefMap = (rootSchema: JSONSchema): Record<string, string> => {
21
+ const map: Record<string, string> = {}
22
+
23
+ if (!isSchemaObject(rootSchema) || !('$defs' in rootSchema)) {
24
+ return map
25
+ }
26
+
27
+ const defs = rootSchema.$defs as Record<string, unknown>
28
+
29
+ for (const [key, value] of Object.entries(defs)) {
30
+ if (
31
+ typeof value === 'object' &&
32
+ value !== null &&
33
+ '$dynamicAnchor' in value &&
34
+ typeof (value as Record<string, unknown>)['$dynamicAnchor'] === 'string'
35
+ ) {
36
+ const anchor = (value as Record<string, unknown>)['$dynamicAnchor'] as string
37
+ map[`#${anchor}`] = `#/$defs/${key}`
38
+ }
39
+ }
40
+
41
+ return map
42
+ }