@amritk/helpers 0.23.3 → 0.24.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/README.md CHANGED
@@ -70,7 +70,7 @@ bun add @amritk/helpers
70
70
  |:---|:---|:---|
71
71
  | `@amritk/helpers/generate-type-definition` | `generateTypeDefinition` | Render a TypeScript type from a schema node. |
72
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/generate-index-barrel` | `generateIndexBarrel` | Render the `index.ts` barrel that re-exports every generated file. |
73
+ | `@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. |
74
74
  | `@amritk/helpers/escape-regex-pattern` | `escapeRegexPattern`, `regexFlagsFor`, `regexLiteral` | Embed a JSON Schema `pattern` in a generated regex literal, validating it at generation time. |
75
75
  | `@amritk/helpers/quote-js-string` | `quoteJsString` | Quote a string as a JS literal, escaping only when needed. |
76
76
  | `@amritk/helpers/multiple-of-check` | `multipleOfPassExpr`, `multipleOfFailExpr` | Emit a `multipleOf` check that agrees with the runtime interpreter. |
@@ -84,6 +84,7 @@ bun add @amritk/helpers
84
84
 
85
85
  | Subpath | Exports | Purpose |
86
86
  |:---|:---|:---|
87
+ | `@amritk/helpers/coercion-runtime` | `coerceScalar`, `coerceUnion`, `valuesEqual`, `allUnique`, `everyItem`, `escapePointer` | The validator's coercion and matching runtime, byte-identical to the copy in a validator build's `validation-result.ts`, for a coercing parser that has to agree with `coerceX`. |
87
88
  | `@amritk/helpers/is-object` | `isObject` | Narrow `unknown` → `Record<string, unknown>`. |
88
89
  | `@amritk/helpers/has-ref` | `hasRef` | Narrow a value to an object carrying a string `$ref`. |
89
90
  | `@amritk/helpers/validate-array` | `validateArray` | Validate array shape and items. |
@@ -0,0 +1,103 @@
1
+ /**
2
+ * The runtime the coercing and matching halves of generated code call: scalar
3
+ * coercion, structural equality, uniqueness, pointer escaping.
4
+ *
5
+ * The validator engine ships these inside its emitted `validation-result.ts`,
6
+ * which a parser build does not have. A coercing parser that agrees with
7
+ * `coerceX` has to coerce, and judge, exactly as `coerceX` does, so it imports
8
+ * the very same functions from here. They are kept byte-identical to the
9
+ * emitted copies — `coercion-runtime.test.ts` in `@amritk/validation` fails
10
+ * the moment the two differ — because two implementations of "is this a
11
+ * number" are two answers waiting to disagree.
12
+ */
13
+ /**
14
+ * One scalar, coerced toward `type`, or returned untouched when that is not
15
+ * possible.
16
+ *
17
+ * Returning the original on failure is what keeps the error honest: nothing is
18
+ * substituted, so the validator that runs next rejects the value the caller
19
+ * actually wrote, with the keyword and params that rejected it. That is the
20
+ * difference between this and a parser's repair, which repairs toward a default
21
+ * and leaves nothing to report.
22
+ *
23
+ * The table is Ajv's `coerceTypes` minus the cells where Ajv guesses. Every
24
+ * value this coerces, Ajv coerces to the same value — `coerced-vs-ajv` pins that
25
+ * as a property, so moving off Ajv never changes a value, it only turns some of
26
+ * Ajv's silent repairs into errors. What is deliberately *not* coerced:
27
+ *
28
+ * - **Anything to or from `null`.** Ajv reads `null` as `""`, `0` and
29
+ * `false`, and reads `""`, `0` and `false` back as `null`. `null` is a
30
+ * JSON value in its own right and usually means "not set"; turning it into an
31
+ * empty string, or an empty string into it, loses the distinction the document
32
+ * drew.
33
+ * - **Strings that are not cleanly numeric** ({@link isNumericString}) — no
34
+ * whitespace padding, no `0x`/`0o`/`0b`, no `Infinity`, no trailing `.`.
35
+ */
36
+ export declare const coerceScalar: (value: unknown, type: string) => unknown;
37
+ /**
38
+ * One scalar at a position that offers several types — a `type` array, or a
39
+ * union of scalar branches — coerced only when every type that can take it
40
+ * agrees on the result.
41
+ *
42
+ * A value whose type is already one of the offered types is left alone: it is
43
+ * what the schema asked for, and the question of coercion does not arise. That
44
+ * one rule is where this parts company with Ajv, which walks its own coercion
45
+ * list in order and so turns `"1"` into `1` under `["number", "string"]` while
46
+ * leaving it a string under `["string", "number"]`. The answer should not depend
47
+ * on the order someone wrote the union in.
48
+ *
49
+ * Otherwise every offered type is tried, and the coercion is taken only if the
50
+ * types that succeed all agree on it. `true` against `number | string` could be
51
+ * `1` or `"true"` with equal justification, so it stays `true` and the
52
+ * validator says what is wrong with it. `"1"` against `number | integer` is `1`
53
+ * either way, so it is `1`.
54
+ */
55
+ export declare const coerceUnion: (value: unknown, types: readonly string[]) => unknown;
56
+ /**
57
+ * Structural deep equality used by generated `const` checks. Objects compare by
58
+ * their key sets rather than serialization, so `{ a: 1, b: 2 }` and
59
+ * `{ b: 2, a: 1 }` are equal — unlike `JSON.stringify`, which is key-order
60
+ * sensitive and would reject a reordered-but-equal value.
61
+ */
62
+ export declare const valuesEqual: (a: unknown, b: unknown, depth?: number) => boolean;
63
+ /**
64
+ * True when every element of `arr` is distinct under structural equality
65
+ * ({@link valuesEqual}). Backs generated `uniqueItems` checks whose items may be
66
+ * objects or arrays, where a `JSON.stringify` dedupe key would be key-order
67
+ * sensitive and let a reordered-but-equal duplicate (`{ a: 1, b: 2 }` vs
68
+ * `{ b: 2, a: 1 }`) slip through.
69
+ *
70
+ * A native `Set` dedupes the all-primitive case in one linear pass. Object and
71
+ * array elements are bucketed by {@link structuralHash} first, so the exact
72
+ * comparison runs only against elements that could actually be equal: an array of
73
+ * distinct objects costs ~O(n) instead of the O(n²) an exhaustive pairwise sweep
74
+ * charged — 4 000 rows took over half a second of pure comparison before, which
75
+ * is a lot to hand an unauthenticated caller.
76
+ */
77
+ export declare const allUnique: (arr: readonly unknown[]) => boolean;
78
+ /**
79
+ * True when `test` holds for every element of `arr`, holes included. Backs the
80
+ * item check inside a generated boolean guard.
81
+ *
82
+ * Not `Array.prototype.every`, because that *skips holes* in a sparse array
83
+ * (`[, 'x']`), whereas the validator's index-based loop reads a hole as
84
+ * `undefined` and rejects it — and the guard must never accept what the validator
85
+ * rejects. The guard used to get that by materialising `Array.from(arr)` first,
86
+ * which copied every array it looked at; an index loop reads a hole the same way
87
+ * and copies nothing.
88
+ */
89
+ export declare const everyItem: (arr: readonly unknown[], test: (item: unknown) => boolean) => boolean;
90
+ /**
91
+ * Escapes one JSON Pointer segment (RFC 6901): `~` → `~0`, `/` → `~1`, in that
92
+ * order. Generated error paths are built from *runtime* keys wherever the schema
93
+ * did not name them — a `patternProperties` match, an `additionalProperties`
94
+ * sweep, a `propertyNames` loop — and a key containing a `/` would otherwise read
95
+ * back as two segments, so an error on `{"a/b": …}` pointed at `/a/b`, which is
96
+ * the child `b` of a property `a`. Keys the schema *does* name are escaped at
97
+ * generation time instead, and `@amritk/runtime-validators` escapes the same way,
98
+ * so all three agree.
99
+ *
100
+ * The `indexOf` pre-test keeps the common key — no `/`, no `~` — off the replace
101
+ * path entirely, which is what the interpreter does for the same reason.
102
+ */
103
+ export declare const escapePointer: (key: string) => string;
@@ -0,0 +1,194 @@
1
+ const isNumericString = (text) => {
2
+ let i = 0;
3
+ let c = text.charCodeAt(0);
4
+ if (c === 43 || c === 45)
5
+ c = text.charCodeAt(++i);
6
+ let digits = 0;
7
+ while (c >= 48 && c <= 57) {
8
+ digits++;
9
+ c = text.charCodeAt(++i);
10
+ }
11
+ if (c === 46) {
12
+ c = text.charCodeAt(++i);
13
+ let fraction = 0;
14
+ while (c >= 48 && c <= 57) {
15
+ fraction++;
16
+ c = text.charCodeAt(++i);
17
+ }
18
+ if (fraction === 0)
19
+ return false;
20
+ } else if (digits === 0)
21
+ return false;
22
+ if (c === 101 || c === 69) {
23
+ c = text.charCodeAt(++i);
24
+ if (c === 43 || c === 45)
25
+ c = text.charCodeAt(++i);
26
+ let exponent = 0;
27
+ while (c >= 48 && c <= 57) {
28
+ exponent++;
29
+ c = text.charCodeAt(++i);
30
+ }
31
+ if (exponent === 0)
32
+ return false;
33
+ }
34
+ return i === text.length;
35
+ };
36
+ const coerceScalar = (value, type) => {
37
+ switch (type) {
38
+ case "string":
39
+ return typeof value === "number" || typeof value === "boolean" ? String(value) : value;
40
+ case "number":
41
+ case "integer": {
42
+ if (typeof value === "boolean")
43
+ return value ? 1 : 0;
44
+ if (typeof value !== "string" || !isNumericString(value))
45
+ return value;
46
+ const asNumber = Number(value);
47
+ if (!Number.isFinite(asNumber))
48
+ return value;
49
+ return type === "integer" && asNumber % 1 !== 0 ? value : asNumber;
50
+ }
51
+ case "boolean":
52
+ if (value === "true" || value === 1)
53
+ return true;
54
+ if (value === "false" || value === 0)
55
+ return false;
56
+ return value;
57
+ default:
58
+ return value;
59
+ }
60
+ };
61
+ const coerceUnion = (value, types) => {
62
+ const actual = value === null ? "null" : typeof value;
63
+ for (const type of types) {
64
+ if (actual === type || actual === "number" && type === "integer")
65
+ return value;
66
+ }
67
+ let coerced = value;
68
+ for (const type of types) {
69
+ const candidate = coerceScalar(value, type);
70
+ if (candidate === value)
71
+ continue;
72
+ if (coerced === value)
73
+ coerced = candidate;
74
+ else if (candidate !== coerced)
75
+ return value;
76
+ }
77
+ return coerced;
78
+ };
79
+ const MAX_EQUAL_DEPTH = 512;
80
+ const valuesEqual = (a, b, depth = 0) => {
81
+ if (a === b || Number.isNaN(a) && Number.isNaN(b))
82
+ return true;
83
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
84
+ return false;
85
+ if (depth >= MAX_EQUAL_DEPTH)
86
+ return false;
87
+ const aArray = Array.isArray(a);
88
+ const bArray = Array.isArray(b);
89
+ if (aArray !== bArray)
90
+ return false;
91
+ if (aArray) {
92
+ const aa = a;
93
+ const bb = b;
94
+ if (aa.length !== bb.length)
95
+ return false;
96
+ for (let i = 0; i < aa.length; i++)
97
+ if (!valuesEqual(aa[i], bb[i], depth + 1))
98
+ return false;
99
+ return true;
100
+ }
101
+ const ao = a;
102
+ const bo = b;
103
+ const keys = Object.keys(ao);
104
+ if (keys.length !== Object.keys(bo).length)
105
+ return false;
106
+ for (const key of keys) {
107
+ if (!Object.hasOwn(bo, key) || !valuesEqual(ao[key], bo[key], depth + 1))
108
+ return false;
109
+ }
110
+ return true;
111
+ };
112
+ const structuralHash = (value, depth = 0) => {
113
+ if (value === null)
114
+ return 1715004;
115
+ const t = typeof value;
116
+ if (t === "number") {
117
+ const n = value;
118
+ return Number.isNaN(n) ? 32760 : n === 0 ? 0 : Math.trunc(n * 2654435761) | 0;
119
+ }
120
+ if (t === "string") {
121
+ const s = value;
122
+ let h2 = 2166136261;
123
+ for (let i = 0; i < s.length; i++)
124
+ h2 = Math.imul(h2 ^ s.charCodeAt(i), 16777619);
125
+ return h2 | 0;
126
+ }
127
+ if (t === "boolean")
128
+ return value ? 1 : 2;
129
+ if (t !== "object")
130
+ return 24301;
131
+ if (depth >= MAX_EQUAL_DEPTH)
132
+ return 57065;
133
+ if (Array.isArray(value)) {
134
+ let h2 = 74565 ^ value.length;
135
+ for (let i = 0; i < value.length; i++)
136
+ h2 = Math.imul(h2, 31) + structuralHash(value[i], depth + 1) | 0;
137
+ return h2 | 0;
138
+ }
139
+ const obj = value;
140
+ const keys = Object.keys(obj);
141
+ let h = 703710 ^ keys.length;
142
+ for (const k of keys) {
143
+ let kh = 2166136261;
144
+ for (let i = 0; i < k.length; i++)
145
+ kh = Math.imul(kh ^ k.charCodeAt(i), 16777619);
146
+ h = h ^ Math.imul(kh, 2654435761) + structuralHash(obj[k], depth + 1) | 0;
147
+ }
148
+ return h | 0;
149
+ };
150
+ const allUnique = (arr) => {
151
+ const len = arr.length;
152
+ if (len < 2)
153
+ return true;
154
+ let allPrimitive = true;
155
+ for (let i = 0; i < len; i++) {
156
+ const v = arr[i];
157
+ if (v !== null && typeof v === "object") {
158
+ allPrimitive = false;
159
+ break;
160
+ }
161
+ }
162
+ if (allPrimitive)
163
+ return new Set(arr).size === len;
164
+ const buckets = /* @__PURE__ */ new Map();
165
+ for (let i = 0; i < len; i++) {
166
+ const item = arr[i];
167
+ const hash = structuralHash(item);
168
+ const bucket = buckets.get(hash);
169
+ if (bucket === void 0) {
170
+ buckets.set(hash, [item]);
171
+ continue;
172
+ }
173
+ for (const seen of bucket)
174
+ if (valuesEqual(seen, item))
175
+ return false;
176
+ bucket.push(item);
177
+ }
178
+ return true;
179
+ };
180
+ const everyItem = (arr, test) => {
181
+ for (let i = 0; i < arr.length; i++)
182
+ if (!test(arr[i]))
183
+ return false;
184
+ return true;
185
+ };
186
+ const escapePointer = (key) => key.indexOf("/") !== -1 || key.indexOf("~") !== -1 ? key.replace(/~/g, "~0").replace(/\//g, "~1") : key;
187
+ export {
188
+ allUnique,
189
+ coerceScalar,
190
+ coerceUnion,
191
+ escapePointer,
192
+ everyItem,
193
+ valuesEqual
194
+ };
@@ -29,7 +29,7 @@ const collectExportNames = (content, typeNames, constNames) => {
29
29
  typeNames.push(typeName);
30
30
  } else {
31
31
  const constName = exportNameAt(content, at, "export const ");
32
- if (constName !== null)
32
+ if (constName !== null && !constName.startsWith("_"))
33
33
  constNames.push(constName);
34
34
  }
35
35
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/helpers",
3
- "version": "0.23.3",
3
+ "version": "0.24.0",
4
4
  "description": "Shared utilities for the mjst code generation ecosystem.",
5
5
  "type": "module",
6
6
  "sideEffects": false,