@amritk/helpers 0.24.0 → 0.26.0

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.
package/AI.md CHANGED
@@ -40,8 +40,8 @@ if (node && isObjectSchema(node) && hasProperties(node)) {
40
40
  4. **Two similar guards:** `isSchemaObject` narrows to a non-boolean schema;
41
41
  `isObjectSchema` narrows to a `type: object` schema. Don't confuse them.
42
42
  5. **Some modules are copied verbatim into generated output** (`is-object`,
43
- `safe-accessor`, `validate-array`, `validate-record`) — intentionally
44
- dependency-free and minimal, not general-purpose validators.
43
+ `has-ref`, `validate-array`, `validate-record`, `coercion-runtime`) —
44
+ intentionally dependency-free and minimal, not general-purpose validators.
45
45
 
46
46
  Notable subpaths: `/resolve-ref`, `/extract-refs`, `/schema-guards`,
47
47
  `/ref-to-name`, `/ref-to-filename`, `/upgrade-draft07-schema`,
package/README.md CHANGED
@@ -59,6 +59,7 @@ bun add @amritk/helpers
59
59
  | `@amritk/helpers/prune-external-schemas` | `pruneExternalSchemas` | Drop the grafted documents nothing references. |
60
60
  | `@amritk/helpers/extract-dynamic-anchor-defs` | `extractDynamicAnchorDefs` | Collect a `#/...` ref for every subschema carrying a `$dynamicAnchor`. |
61
61
  | `@amritk/helpers/fold-nullable` | `foldNullable` | Rewrite OpenAPI 3.0 `nullable: true` into a `null` member of `type`. |
62
+ | `@amritk/helpers/referenced-conditional` | `referencedConditional` | The `if`/`then` definition an `allOf` member's local `$ref` points at, so the type emitter and the import collectors agree on what gets inlined. |
62
63
  | `@amritk/helpers/derive-root-type-name` | `deriveRootTypeName` | Turn a schema `title` into a PascalCase root type name. |
63
64
  | `@amritk/helpers/read-key` | `readKey`, `declaresKey` | Read an author-chosen name (`$defs` entry, config key) off a map, treating inherited names such as `__proto__` as absent. |
64
65
  | `@amritk/helpers/assign-key` | `assignKey` | Assign a key on a rebuilt object without letting `__proto__` reach the prototype setter. |
@@ -69,8 +70,12 @@ bun add @amritk/helpers
69
70
  | Subpath | Exports | Purpose |
70
71
  |:---|:---|:---|
71
72
  | `@amritk/helpers/generate-type-definition` | `generateTypeDefinition` | Render a TypeScript type from a schema node. |
72
- | `@amritk/helpers/mjst-extension` | `MJST_EXTENSION_KEY`, `getMjstInstanceOf`, `getMjstPrimitive`, `getMjstBrand` | Read the `x-mjst` vendor hints (`instanceOf`, `primitive`, `brand`) a schema carries. |
73
+ | `@amritk/helpers/mjst-extension` | `MJST_EXTENSION_KEY`, `MjstExtension`, `hasMjstHint`, `getMjstInstanceOf`, `getMjstPrimitive`, `getMjstBrand`, `getMjstDiscriminator` | Read the `x-mjst` vendor hints (`instanceOf`, `primitive`, `brand`) a schema carries, and the message `discriminator` an AsyncAPI channel names. |
73
74
  | `@amritk/helpers/generate-index-barrel` | `generateIndexBarrel` | Render the `index.ts` barrel that re-exports every generated file. A name starting with `_` is for sibling files only and is left out. |
75
+ | `@amritk/helpers/identifier-mentions` | `identifierMentions` | Ask whether emitted source names an identifier, ignoring comments, strings, and regex literals — decides which `$ref` imports a generated file keeps. |
76
+ | `@amritk/helpers/get-default-value` | `getDefaultValue` | The fallback value (as source text) a parser or repairing validator substitutes for missing data: `default` > `const` > first `enum` > first usable `examples` entry > first union branch > `pattern` > type. `default` and `examples` are used only when they match the declared type. |
77
+ | `@amritk/helpers/generate-default-from-pattern` | `generateDefaultFromPattern` | Build a fallback string that is guaranteed to match a `pattern` (and length bounds), or `null`. |
78
+ | `@amritk/helpers/unknown-keys-strategy` | `UnknownKeysStrategy`, `UNKNOWN_KEYS_STRATEGIES`, `DEFAULT_UNKNOWN_KEYS`, `isUnknownKeysStrategy` | How a generated fast path proves a closed object has no extra key: `'count-keys'` (default) or `'count-enumerable'`. |
74
79
  | `@amritk/helpers/escape-regex-pattern` | `escapeRegexPattern`, `regexFlagsFor`, `regexLiteral` | Embed a JSON Schema `pattern` in a generated regex literal, validating it at generation time. |
75
80
  | `@amritk/helpers/quote-js-string` | `quoteJsString` | Quote a string as a JS literal, escaping only when needed. |
76
81
  | `@amritk/helpers/multiple-of-check` | `multipleOfPassExpr`, `multipleOfFailExpr` | Emit a `multipleOf` check that agrees with the runtime interpreter. |
@@ -113,7 +118,7 @@ Most helpers have a colocated test file (`*.test.ts`) — read those for canonic
113
118
 
114
119
  ## Related packages
115
120
 
116
- - [`@amritk/validation`](../parsers) — primary consumer
121
+ - [`@amritk/validation`](../validation) — primary consumer
117
122
  - [`@amritk/mjst`](../cli) — the CLI surface
118
123
 
119
124
  ---
@@ -26,3 +26,38 @@ export declare const regexFlagsFor: (pattern: string) => string;
26
26
  * @throws if `pattern` is not a valid regular expression.
27
27
  */
28
28
  export declare const regexLiteral: (pattern: string) => string;
29
+ /**
30
+ * The string a `pattern` matches verbatim, and where it is anchored, when the
31
+ * pattern is nothing but literal characters — `^x-`, `^\$ref$`, `^\/`. `null` for
32
+ * anything that needs a regex engine.
33
+ *
34
+ * Kept deliberately narrow: an escape counts only when it is one of the
35
+ * punctuation characters every mode reads as itself (`\d`, `\n` or `A`
36
+ * bail), and any surrogate bails, so the code-point matching the `u` flag does
37
+ * can never differ from the code-unit comparison that replaces it. Without the
38
+ * `m` flag, which no generated regex carries, `^` and `$` anchor to the ends of
39
+ * the whole string and nothing else, so `startsWith`, `endsWith` and `===` are
40
+ * exactly the same test.
41
+ */
42
+ export declare const literalPattern: (pattern: string) => {
43
+ readonly text: string;
44
+ readonly start: boolean;
45
+ readonly end: boolean;
46
+ } | null;
47
+ /**
48
+ * A boolean expression testing the string `subject` against `pattern`: a plain
49
+ * string comparison when the pattern is only literal characters, a regex
50
+ * literal's `.test` otherwise.
51
+ *
52
+ * Generated code tests the same few patterns on every key of every object —
53
+ * `^x-` for OpenAPI extensions, `^\/` for paths — and a regex costs several
54
+ * times what `startsWith` does for the same answer, more again inside the loop,
55
+ * where the literal is re-created on each pass. `subject` must be an expression
56
+ * that is already known to be a string, which every key and every `typeof`
57
+ * -guarded value is.
58
+ *
59
+ * @example
60
+ * regexTest('^x-', 'key') // → 'key.startsWith("x-")'
61
+ * regexTest('^\\d+$', 'key') // → '/^\\d+$/u.test(key)'
62
+ */
63
+ export declare const regexTest: (pattern: string, subject: string) => string;
@@ -62,8 +62,60 @@ const escapeRegexPattern = (pattern) => {
62
62
  };
63
63
  const regexFlagsFor = (pattern) => compileMode(pattern) ?? "";
64
64
  const regexLiteral = (pattern) => `/${escapeRegexPattern(pattern)}/${regexFlagsFor(pattern)}`;
65
+ const ESCAPABLE_PUNCTUATION = /* @__PURE__ */ new Set(["^", "$", "\\", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", "|", "/", "-"]);
66
+ const METACHARACTERS = /* @__PURE__ */ new Set(["^", "$", "\\", ".", "*", "+", "?", "(", ")", "[", "]", "{", "}", "|"]);
67
+ const literalPattern = (pattern) => {
68
+ const start = pattern.startsWith("^");
69
+ let body = start ? pattern.slice(1) : pattern;
70
+ let end = false;
71
+ if (body.endsWith("$")) {
72
+ let slashes = 0;
73
+ for (let i = body.length - 2; i >= 0 && body[i] === "\\"; i--)
74
+ slashes++;
75
+ if (slashes % 2 === 0) {
76
+ end = true;
77
+ body = body.slice(0, -1);
78
+ }
79
+ }
80
+ let text = "";
81
+ for (let i = 0; i < body.length; i++) {
82
+ const char = body[i];
83
+ const code = char.charCodeAt(0);
84
+ if (code >= 55296 && code <= 57343)
85
+ return null;
86
+ if (char === "\\") {
87
+ const next = body[i + 1];
88
+ if (next === void 0 || !ESCAPABLE_PUNCTUATION.has(next))
89
+ return null;
90
+ text += next;
91
+ i++;
92
+ continue;
93
+ }
94
+ if (METACHARACTERS.has(char))
95
+ return null;
96
+ text += char;
97
+ }
98
+ if (text === "" && !(start && end))
99
+ return null;
100
+ return { text, start, end };
101
+ };
102
+ const regexTest = (pattern, subject) => {
103
+ const literal = literalPattern(pattern);
104
+ if (literal === null)
105
+ return `${regexLiteral(pattern)}.test(${subject})`;
106
+ const text = JSON.stringify(literal.text);
107
+ if (literal.start && literal.end)
108
+ return `(${subject} === ${text})`;
109
+ if (literal.start)
110
+ return `${subject}.startsWith(${text})`;
111
+ if (literal.end)
112
+ return `${subject}.endsWith(${text})`;
113
+ return `${subject}.includes(${text})`;
114
+ };
65
115
  export {
66
116
  escapeRegexPattern,
117
+ literalPattern,
67
118
  regexFlagsFor,
68
- regexLiteral
119
+ regexLiteral,
120
+ regexTest
69
121
  };
@@ -1,16 +1,23 @@
1
1
  /**
2
2
  * Generates a safe property accessor for a given key on an object variable.
3
- * Uses dot notation for simple identifiers and bracket notation for keys
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.
3
+ * Keys that collide with an `Object.prototype` member get an own-property guard
4
+ * (see {@link PROTOTYPE_MEMBERS}) so an inherited value never masquerades as
5
+ * input.
6
+ *
7
+ * Every other key is read with bracket notation, plain identifiers included.
8
+ * The generated code reads properties off a `Record<string, unknown>`, and a dot
9
+ * read of an index signature is `TS4111` under `noPropertyAccessFromIndexSignature`
10
+ * — a flag strict projects turn on, and which would otherwise fail every file
11
+ * dropped into one. Engines compile `o["a"]` and `o.a` to the same named load,
12
+ * and TypeScript narrows a string-literal index the way it narrows a dot, so the
13
+ * bracket form costs nothing at runtime or in the type checks it feeds.
7
14
  *
8
15
  * @param variable - The variable name (e.g., "input", "input?")
9
16
  * @param key - The property name to access
10
17
  * @returns A valid JS property access expression
11
18
  *
12
19
  * @example
13
- * safeAccessor("input", "name") // "input.name"
20
+ * safeAccessor("input", "name") // 'input["name"]'
14
21
  * safeAccessor("input?", "x-linkedin") // 'input?.["x-linkedin"]'
15
22
  * safeAccessor("input", "x-linkedin") // 'input["x-linkedin"]'
16
23
  * safeAccessor("input", "constructor")
@@ -6,9 +6,6 @@ const safeAccessor = (variable, key) => {
6
6
  const literal2 = JSON.stringify(key);
7
7
  return `((${base} != null && Object.hasOwn(${base}, ${literal2}) ? ${base}[${literal2}] : undefined) as any)`;
8
8
  }
9
- if (JS_IDENTIFIER.test(key)) {
10
- return `${variable}.${key}`;
11
- }
12
9
  const literal = JSON.stringify(key);
13
10
  if (variable.endsWith("?")) {
14
11
  return `${variable}.[${literal}]`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/helpers",
3
- "version": "0.24.0",
3
+ "version": "0.26.0",
4
4
  "description": "Shared utilities for the mjst code generation ecosystem.",
5
5
  "type": "module",
6
6
  "sideEffects": false,