@stonyx/orm 0.3.2-alpha.66 → 0.3.2-alpha.68

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/dist/utils.js CHANGED
@@ -15,3 +15,50 @@ export function pluralize(word) {
15
15
  }
16
16
  return basePluralize(word);
17
17
  }
18
+ /**
19
+ * The highest NUMERIC id held by a set of records, or `0` when there is none.
20
+ *
21
+ * ONE COPY, and the duplication it replaces is the reason it lives here. Three
22
+ * near-identical reduces existed at once: `assignRecordId` (server-assigned id
23
+ * selection), `StandaloneDB.create` (src/standalone-db.ts) and the #203 test
24
+ * helper. `docs/improvements.md`'s standing WET Code category prescribes
25
+ * exactly this remedy -- extract into the module that already acts as the
26
+ * shared utility -- and `assignRecordId` already imported `isOrmRecord` from
27
+ * here.
28
+ *
29
+ * NON-NUMBERS ARE SKIPPED RATHER THAN COERCED TO `0`, AND THAT IS STYLISTIC.
30
+ * `StandaloneDB`'s shape mapped them to `0`, which can never beat a seed of
31
+ * `0`. Measured over eleven input classes (`[]`, `1`, `NaN`, `'5'`, `'abc'`,
32
+ * `-3`, `0`, `null`, `undefined`, `Infinity`, and mixed arrays) the two shapes
33
+ * produce IDENTICAL output on every one. In particular `typeof NaN` is
34
+ * `'number'`, so NEITHER shape coerces `NaN` -- both reject it on `NaN > max`,
35
+ * which is `false`. An earlier revision of this code asserted that the skip was
36
+ * what made the `NaN` case work; it is not, the comparison is, and that claim
37
+ * has been removed rather than left standing.
38
+ *
39
+ * WHAT IS LOAD-BEARING is that this is not `Math.max(...ids)`. `Math.max`
40
+ * returns `NaN` if any operand is `NaN`, and a record CAN be held under the key
41
+ * `NaN` -- so the obvious fix assigns `NaN`, lands on that slot and overwrites
42
+ * it, which is abofs/stonyx-orm#203 in a new disguise. Pinned by
43
+ * test/unit/assign-record-id-test.ts AC2; before that file existed the whole
44
+ * suite scored 951/0 under exactly that fix.
45
+ */
46
+ export function maxNumericId(records) {
47
+ return records.reduce((max, record) => {
48
+ const { id } = record;
49
+ return typeof id === 'number' && id > max ? id : max;
50
+ }, 0);
51
+ }
52
+ /**
53
+ * The message prefix `assignRecordId` throws with when no free id can be
54
+ * derived for a model, and the ONE string `createHandler` matches on to answer
55
+ * `409` instead of letting the rejection reach express's default handler.
56
+ *
57
+ * It lives here rather than in either file because both need it and neither
58
+ * should own a copy: a literal in two places is how the two id coercions in
59
+ * orm-request.ts drifted apart (see `coerceId`). The repo has no error codes
60
+ * and no custom error classes -- 24 bare `throw new Error` sites across `src/`
61
+ * -- so a shared prefix is the narrowest way to make ONE failure distinguishable
62
+ * without inventing an error taxonomy this codebase does not use.
63
+ */
64
+ export const NO_FREE_ID_ERROR = 'Cannot assign record ID: no free id available';
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "stonyx-async",
5
5
  "stonyx-module"
6
6
  ],
7
- "version": "0.3.2-alpha.66",
7
+ "version": "0.3.2-alpha.68",
8
8
  "description": "",
9
9
  "main": "dist/index.js",
10
10
  "type": "module",
@@ -0,0 +1,222 @@
1
+ /**
2
+ * The shared access-verdict primitive (abofs/stonyx-orm#234).
3
+ *
4
+ * ---------------------------------------------------------------------------
5
+ * WHY THIS FILE EXISTS: ONE INTERPRETER, NOT TWO
6
+ * ---------------------------------------------------------------------------
7
+ * A consumer `access()` may return six differently-shaped things -- `false`, a
8
+ * bare permission string, a permission array, `true`, a per-record function, or
9
+ * something the contract does not define at all -- and the reading of each one
10
+ * is a security decision. `auth()` has held that reading inline since #190.
11
+ * Every surface that needs to ask "may this caller see model X's record?" needs
12
+ * the SAME reading, or the second copy becomes an unreviewed second
13
+ * authorization vocabulary that answers differently about the same value.
14
+ *
15
+ * So `interpretAccess` is extracted here and `auth()` now calls it. It is the
16
+ * only place a return shape is classified, and abofs/stonyx-orm#232 and #233
17
+ * rebase onto it rather than re-deriving it.
18
+ *
19
+ * ---------------------------------------------------------------------------
20
+ * WHAT A LINKAGE FILTER IS, AND WHY THE CALLER BUILDS IT
21
+ * ---------------------------------------------------------------------------
22
+ * `Record.toJSON()` APPLIES a verdict; it never RESOLVES one. That is not a
23
+ * style choice, it is forced, and it was measured before it was decided:
24
+ *
25
+ * INPUT: origin/dev @ c5f7907, unpatched -> 967 pass / 0 fail
26
+ * INPUT: same + fail-closed resolution INSIDE toJSON() -> 964 pass / 3 fail
27
+ *
28
+ * and all three reds were over-denial of PERMITTED records, not the leak. Two
29
+ * independent reasons:
30
+ *
31
+ * 1. `toJSON()` has no request. The shipped, documented sample reads
32
+ * `request.path` for its `/archived` sub-path rule -- the one read of
33
+ * argument one the README sanctions -- and fail-closes when it is absent.
34
+ * Measured against the live registry:
35
+ *
36
+ * getAccess('owner')(undefined, { model:'owner', operation:'read' }) -> false
37
+ * getAccess('animal')(undefined,{ model:'animal', operation:'read' }) -> [Function]
38
+ *
39
+ * Same predicate object, two models, two different degradation modes,
40
+ * chosen by the consumer. Without a request there is no trustworthy
41
+ * answer to get.
42
+ *
43
+ * 2. `toJSON` is also the `JSON.stringify` hook, so `JSON.stringify({data:
44
+ * record})` calls `record.toJSON('data')` -- a STRING in the options slot.
45
+ * An implicit caller has no syntactic place to pass anything
46
+ * (abofs/stonyx-orm#230). The no-argument document must therefore stay
47
+ * byte-identical to what shipped, which also rules out fail-closed by
48
+ * default: `Orm.instance.accessFunctions` is `{}` in any process that
49
+ * never ran `setup-rest-server` (CLI, SQL-only, unit tests), so a
50
+ * fail-closed default would empty every relationship on every document in
51
+ * processes that have no REST surface to protect.
52
+ *
53
+ * The caller -- which still holds the request -- resolves the predicate,
54
+ * interprets it here, caches the answer, and hands `toJSON()` an already-decided
55
+ * `(type, record) => boolean`.
56
+ */
57
+ import Orm from '@stonyx/orm';
58
+ import log from 'stonyx/log';
59
+ import type { AccessMethod, AccessOperation } from './types/orm-types.js';
60
+
61
+ /**
62
+ * The classified reading of one `access()` return value.
63
+ *
64
+ * `granted: false` is a total denial. `granted: true` with no `filter` is an
65
+ * unconditional grant. `granted: true` WITH a filter means "grant, subject to
66
+ * this per-record predicate" -- the function return shape, which is the
67
+ * per-record hook `AccessContext` deliberately does not provide.
68
+ */
69
+ export interface AccessVerdict {
70
+ granted: boolean;
71
+ filter?: (record: unknown) => boolean;
72
+ }
73
+
74
+ /**
75
+ * A resolved, request-scoped linkage decision: may `record` of model `type` be
76
+ * NAMED, by id, inside another model's document?
77
+ *
78
+ * Arity is `(type, record)` and not `(type, id)` because the per-record filter
79
+ * the consumer returns is handed the RECORD -- this repo's own fixture reads
80
+ * `record.owner?.id`, not just `record.id`. The `(type, id)` pair is the CACHE
81
+ * key, not the input.
82
+ */
83
+ export type LinkageFilter = (type: string, record: unknown) => boolean;
84
+
85
+ const DENIED: AccessVerdict = Object.freeze({ granted: false });
86
+ const GRANTED: AccessVerdict = Object.freeze({ granted: true });
87
+
88
+ /**
89
+ * Classify one `access()` return value. Extracted verbatim from `auth()`, which
90
+ * now calls this; the branch ORDER is load-bearing and is preserved exactly.
91
+ *
92
+ * `operation` is the verb being authorised. `undefined` -- reachable, because
93
+ * express delivers HEAD to the GET handler and `methodAccessMap` has no entry
94
+ * for it -- falls through `permitted.includes(undefined)` to a denial, which is
95
+ * the same answer `auth()` gave before the extraction.
96
+ */
97
+ export function interpretAccess(access: AccessMethod, operation: AccessOperation | undefined): AccessVerdict {
98
+ if (!access) return DENIED;
99
+
100
+ // The function return shape IS the per-record hook. Grant the request and
101
+ // carry the predicate; the caller applies it per record.
102
+ if (typeof access === 'function') return { granted: true, filter: access as (record: unknown) => boolean };
103
+
104
+ if (access === true) return GRANTED;
105
+
106
+ // `AccessMethod` declares `string` legal and it fell through every branch
107
+ // above. A bare string is ONE permission, not a grant of all four -- reading
108
+ // it as a full grant is what once let `return 'read'` authorise DELETE.
109
+ const permitted = typeof access === 'string' ? [access] : access;
110
+
111
+ // Anything that is not a permission array by this point -- an object, a
112
+ // number, a Symbol -- is a consumer mistake, and the only safe reading of a
113
+ // shape the contract does not define is a denial. Fail CLOSED.
114
+ if (!Array.isArray(permitted)) return DENIED;
115
+ if (!permitted.includes(operation as string)) return DENIED;
116
+
117
+ return GRANTED;
118
+ }
119
+
120
+ /**
121
+ * Resolve model `type`'s verdict for a read, against the live `request`.
122
+ *
123
+ * Fails closed on both ambiguous inputs:
124
+ *
125
+ * - `getAccess(type)` -> `undefined`. That is NOT "this model is
126
+ * unrestricted". `setup-rest-server` catches an access-class load failure,
127
+ * warns, and publishes whatever PARTIAL map it had, so `undefined` covers
128
+ * both "no access class claims this model" and "the class that claims it
129
+ * failed to load" -- and the caller cannot tell them apart. Deny.
130
+ * - the predicate THROWS. Same reading `auth()` and `isDenied` already use:
131
+ * a throw is a denial, logged, never a 500 and never a grant.
132
+ *
133
+ * NOTE ON CROSS-MODEL ASKS. The predicate is asked about `type` while the
134
+ * request in hand was dispatched to a DIFFERENT model's route. Since #222 this
135
+ * repo's fixture reads `context.model` and answers correctly; a consumer's
136
+ * arity-1 predicate does not, and there is no supported way to tell which kind
137
+ * was resolved (the boot-time arity warning is abofs/stonyx-orm#213). A
138
+ * consequence to expect rather than debug: the fixture's surviving `request.path`
139
+ * read means asking the OWNER predicate on a request dispatched to
140
+ * `GET /animals/archived` returns a bare `false`. That is a whole-request deny
141
+ * bleeding across models -- harmless, because it is the fail-closed direction,
142
+ * and it is treated as "deny this linkage", not as an error.
143
+ */
144
+ function resolveVerdict(request: unknown, type: string): AccessVerdict {
145
+ const predicate = Orm.instance?.getAccess?.(type);
146
+ if (typeof predicate !== 'function') return DENIED;
147
+
148
+ let access: AccessMethod;
149
+
150
+ try {
151
+ access = predicate(request, { model: type, operation: 'read' });
152
+ } catch (error) {
153
+ log.error?.(`[@stonyx/orm] access() threw while resolving linkage for model "${type}" -- denying. ${error instanceof Error ? error.message : String(error)}`);
154
+
155
+ return DENIED;
156
+ }
157
+
158
+ return interpretAccess(access, 'read');
159
+ }
160
+
161
+ /**
162
+ * Build a request-scoped linkage filter.
163
+ *
164
+ * TWO CACHES, AND BOTH ARE LOAD-BEARING RATHER THAN AN OPTIMISATION:
165
+ *
166
+ * - one verdict per TYPE. Resolving means CALLING the consumer's `access()`,
167
+ * which is arbitrary code with arbitrary cost and which the module has
168
+ * already had to guard for throwing.
169
+ * - one decision per `(type, id)`. `included` is deduplicated by
170
+ * `buildResponse`; LINKAGE is not deduplicated at all, so it re-asks once
171
+ * per record. Measured on a bare `GET /animals` with no `include=`:
172
+ * 48 linkage entries -> 7 distinct `(type, id)` pairs (owner 20, trait 28),
173
+ * a 6.9x reduction and 41 predicate calls saved.
174
+ *
175
+ * The `(type, id)` cache is a `Map` per type keyed on the RAW id, not on a
176
+ * template-string composite: `Map` compares with SameValueZero, so the numeric
177
+ * id `1` and the string id `'1'` stay distinct, where `` `${type}:${id}` ``
178
+ * would collapse them and let one model's verdict answer for another record.
179
+ *
180
+ * SCOPE IS ONE REQUEST. The filter closes over the request and must not outlive
181
+ * it -- a verdict cached across requests would answer a second caller with the
182
+ * first caller's authorization.
183
+ */
184
+ export function createLinkageFilter(request: unknown): LinkageFilter {
185
+ const byType = new Map<string, { verdict: AccessVerdict; decisions: Map<unknown, boolean> }>();
186
+
187
+ return function isLinkable(type: string, record: unknown): boolean {
188
+ let entry = byType.get(type);
189
+
190
+ if (!entry) {
191
+ entry = { verdict: resolveVerdict(request, type), decisions: new Map() };
192
+ byType.set(type, entry);
193
+ }
194
+
195
+ const { verdict, decisions } = entry;
196
+
197
+ if (!verdict.granted) return false;
198
+ if (!verdict.filter) return true;
199
+
200
+ const id = (record as { id?: unknown } | null)?.id;
201
+ const cached = decisions.get(id);
202
+ if (cached !== undefined) return cached;
203
+
204
+ let allowed: boolean;
205
+
206
+ try {
207
+ allowed = Boolean(verdict.filter(record));
208
+ } catch (error) {
209
+ // A predicate that throws is a denial -- the same reading `isDenied` uses
210
+ // one layer down. Logged, because a predicate that throws on every record
211
+ // empties every relationship and, silently, that is indistinguishable
212
+ // from a database with no relationships in it.
213
+ log.error?.(`[@stonyx/orm] access filter threw while filtering linkage for model "${type}" -- denying. ${error instanceof Error ? error.message : String(error)}`);
214
+
215
+ allowed = false;
216
+ }
217
+
218
+ decisions.set(id, allowed);
219
+
220
+ return allowed;
221
+ };
222
+ }
@@ -2,7 +2,7 @@ import Orm, { store } from '@stonyx/orm';
2
2
  import OrmRecord from './record.js';
3
3
  import { getGlobalRegistry, getPendingRegistry, getPendingBelongsToRegistry, getBelongsToRegistry, getHasManyRegistry } from './relationships.js';
4
4
  import type Serializer from './serializer.js';
5
- import { isOrmRecord } from './utils.js';
5
+ import { isOrmRecord, maxNumericId, NO_FREE_ID_ERROR } from './utils.js';
6
6
 
7
7
  interface CreateRecordOptions {
8
8
  isDbRecord?: boolean;
@@ -195,17 +195,58 @@ export function updateRecord(record: OrmRecord, rawData: unknown, userOptions: C
195
195
  }
196
196
 
197
197
  /**
198
- * gets the next available id based on last record entry.
198
+ * gets the next available id, based on the HIGHEST id present.
199
199
  *
200
200
  * In MySQL mode with numeric IDs, assigns a temporary pending ID.
201
201
  * MySQL's AUTO_INCREMENT provides the real ID after INSERT.
202
+ *
203
+ * ---------------------------------------------------------------------------
204
+ * WAS: `Array.from(storeMap.values()).at(-1).id + 1` — the LAST INSERTED id,
205
+ * not the maximum (abofs/stonyx-orm#203). The store is a Map, so insertion
206
+ * order stops being ascending the moment a record is deleted and recreated, a
207
+ * db.json is written out of order, a directory-mode store is read back in file
208
+ * order, or a caller POSTs a high id and then a low one. After that, every
209
+ * server-assigned id is one that is ALREADY TAKEN — and `createRecord`'s
210
+ * last-entry-wins branch then overwrites that record IN PLACE and answers 200.
211
+ * No error, no 409, and the store's size does not change. That is the whole
212
+ * defect, and it is reachable from a create with NO id at all, which is the
213
+ * most ordinary write a consumer performs.
214
+ *
215
+ * Covered by test/unit/assign-record-id-test.ts. Note for anyone changing this
216
+ * function: before that file existed, the whole suite scored 951/0 both on the
217
+ * defect and on a naive `Math.max` fix that introduced a second one. A green
218
+ * suite is not evidence here; those assertions are.
219
+ * ---------------------------------------------------------------------------
202
220
  */
203
221
  function assignRecordId(modelName: string, rawData: { [key: string]: unknown }): void {
204
- if (rawData.id) return;
222
+ // PRESENCE, not truthiness. `0` is a legal value for an `attr('number')` id,
223
+ // and `if (rawData.id) return` silently reassigned it, handing the caller back
224
+ // a different record than the one it named (#203).
225
+ //
226
+ // `''` is deliberately NOT honoured here and this is not an oversight: it is
227
+ // the one string that means "no id". `parseInt('')` is `NaN`, a record CAN be
228
+ // held under the key `NaN`, and orm-request.ts's body-id normalisation relies
229
+ // on `''` staying absent — otherwise `POST {"id":""}` answers 409 against a
230
+ // record it never named.
231
+ //
232
+ // WHAT WIDENING THIS TO `!== undefined` ACTUALLY DOES, measured rather than
233
+ // asserted: `{id: ''}` early-returns, `parseInt('')` NaNs it, and the record
234
+ // lands on the store's `NaN` slot and OVERWRITES whatever is there — #203's
235
+ // own defect class. It does NOT turn access-filter-enforcement-test.ts
236
+ // assertion 44 red; an earlier revision of this comment claimed it did, which
237
+ // converted an unknown into a false assurance. AC6's BOUNDARY assertions are
238
+ // what catch it, and they only do so because they seed the `NaN` slot first.
239
+ if (rawData.id || rawData.id === 0) return;
205
240
 
206
241
  // In SQL mode with numeric IDs, defer to database auto-increment.
207
242
  // Use unique negative integers — they survive the number transform (parseInt preserves negatives)
208
243
  // and avoid NaN store-key collisions that string pending IDs caused.
244
+ //
245
+ // This early return is ABOVE the max computation on purpose: a pending
246
+ // negative must never be a candidate for, or be perturbed by, the max path.
247
+ // Pinned directly (AC5.3) rather than by asserting the max is unaffected —
248
+ // that assertion could not have failed, because nothing negative ever reaches
249
+ // the code below.
209
250
  if (Orm.instance?.sqlDb && !isStringIdModel(modelName)) {
210
251
  rawData.id = -(++pendingIdCounter);
211
252
  rawData.__pendingSqlId = true;
@@ -215,15 +256,218 @@ function assignRecordId(modelName: string, rawData: { [key: string]: unknown }):
215
256
  const storeMap = store.get(modelName);
216
257
  if (!storeMap) throw new Error(`Cannot assign record ID: model "${modelName}" not found in store`);
217
258
  const modelStore = Array.from(storeMap.values()).filter(isOrmRecord);
218
- const lastRecord = modelStore.at(-1);
219
- rawData.id = lastRecord ? (lastRecord.id as number) + 1 : 1;
259
+
260
+ // ONE COPY of the max-numeric-id reduce, in src/utils.ts. There were three
261
+ // (here, StandaloneDB.create, and the #203 test helper) and `docs/
262
+ // improvements.md`'s WET Code category prescribes the extraction. What that
263
+ // helper must NOT be is `Math.max(...ids)`; the reason is measured and it is
264
+ // documented at the helper rather than duplicated here. Pinned by AC2.
265
+ const maxId = maxNumericId(modelStore);
266
+
267
+ // THE OCCUPANCY CHECK RUNS ON THE LANDING KEY, NOT ON THE RAW CANDIDATE, and
268
+ // the difference is a silent data loss rather than a nicety.
269
+ //
270
+ // `createRecord` looks the record up under `rawData.id` (:50) but WRITES it
271
+ // under `record.id` (:69) — the value after the model's declared id transform
272
+ // has run inside `serialize`. When the transform is not the identity those two
273
+ // differ, so a guard written as `storeMap.has(rawData.id)` checks a key the
274
+ // record will never occupy, misses an occupied slot and overwrites it —
275
+ // measured on an `uppercase`-id model: the guard checks `owner-1`, the record
276
+ // lands under `OWNER-1`, store size unchanged, no error. That is
277
+ // abofs/stonyx-orm#205's lookup-key/landing-key divergence reappearing inside
278
+ // #203's own fix, which is why AC4 exists and why `rawData.id` is set to the
279
+ // LANDING key below.
280
+ //
281
+ // THE SCOPE OF THAT CLAIM, stated rather than implied. Setting `rawData.id` to
282
+ // the landing key makes :50 and :69 agree for every IDEMPOTENT id transform —
283
+ // `number`, `float`, `string`, `passthrough`, `uppercase`, `trim`. It does NOT
284
+ // make them agree for `date` or `timestamp`: `transforms.date` returns a NEW
285
+ // object every call and a `Map` keys by identity, so `storeMap.has(landingKey)`
286
+ // is always `false` there and the occupancy check is vacuous. `dev` is broken
287
+ // for those types too — this is not a regression — but no comment here may
288
+ // claim a property it was not measured to have (#212 § AC5).
289
+ //
290
+ // Resolved ONCE, outside the walk: `getIdType` instantiates the model class,
291
+ // so resolving it per candidate would put a model construction on every
292
+ // iteration of a loop that exists to walk past occupied slots.
293
+ const toStoreKey = storeKeyDeriver(modelName);
294
+
295
+ // DOES THIS MODEL FILE ITS RECORDS UNDER STRING KEYS? Decided by RUNNING the
296
+ // model's own id transform once, not by matching a type NAME against a list:
297
+ // `Orm.instance.transforms` (main.ts:70) is a public, MUTABLE instance
298
+ // property, so any enumeration of "the string-ish types" written here would be
299
+ // wrong the moment a consumer registers one.
300
+ const stringKeyed = typeof toStoreKey(maxId + 1) === 'string';
301
+
302
+ // THE CANDIDATE FOR A STRING-KEYED MODEL IS NOT A BARE NUMBER, and this is
303
+ // abofs/stonyx-orm#209 — which is REOPENED — not aesthetics.
304
+ //
305
+ // `orm-request.ts`'s `coerceId` (:322) resolves a NUMERIC-LOOKING string to a
306
+ // NUMBER on every id-bearing surface, while a model declaring
307
+ // `id = attr('string')` files under the STRING key. So a server-assigned `'1'`
308
+ // produces a record that is created and then NOT ADDRESSABLE. Measured over
309
+ // the route, owner store `{'1': ...}`:
310
+ //
311
+ // GET /owners/1 -> 404 (the record exists)
312
+ // DELETE /owners/1 -> 404
313
+ // GET /owners/owner-1 -> 200
314
+ //
315
+ // and `_withHooks` (:1185) hands an after-`create` hook
316
+ // `context.record === undefined` for the same reason. `dev` assigned `'bob1'`,
317
+ // which is not numeric-looking, so `dev` has neither problem: a bare-number
318
+ // candidate would move #209 from "a caller supplied a numeric-looking id" onto
319
+ // the DEFAULT path for every server-assigned create on every string-id model.
320
+ // Prefixing with the model name keeps #209's population exactly as narrow as
321
+ // it already was, without touching the one shared coercion or the assertion
322
+ // that pins #209 open. Pinned by AC3.
323
+ const toCandidate = stringKeyed
324
+ ? (value: number) => `${modelName}-${value}`
325
+ : (value: number) => value;
326
+
327
+ // `maxId + 1` is the id AC1 pins: strictly greater than every numeric key
328
+ // present. IT IS NOT ALWAYS AVAILABLE, and that gap was a live denial of
329
+ // service. Float64 has no integer successor at or above 2^53, so
330
+ // `maxId + 1 === maxId` for every `maxId >= 9007199254740992` and `+ 1` inside
331
+ // the walk is a NO-OP there. One record filed under that key — which an
332
+ // unauthenticated `POST {"id":9007199254740992}` puts there, and which reaches
333
+ // even a filter-protected collection through has-many.ts:65 (#207), a channel
334
+ // GATE 0 does not cover — made the walk unable to advance, so it exhausted its
335
+ // budget and threw on EVERY subsequent server-assigned create, permanently,
336
+ // until that record was deleted. Measured over the route: 200, then 500 for
337
+ // every no-id create. `dev` answers 200.
338
+ //
339
+ // So a store holding one adversarial record must not disable its collection.
340
+ // When "above the max" is not a usable strategy the walk RESTARTS FROM 1: the
341
+ // store holds at most `size` keys, so one of `1 .. size + 1` is always free
342
+ // under an injective id transform. Pinned by AC7.
343
+ const start = maxId + 1;
344
+ let landingKey = firstFreeKey(storeMap, toStoreKey, toCandidate, start);
345
+
346
+ // THE RESTART, and it is the whole of the ceiling fix. Killing mutation:
347
+ // delete this block -> AC7 goes red (the route answers 409 instead of the
348
+ // created resource).
349
+ if (landingKey === NO_FREE_KEY && start !== 1) {
350
+ landingKey = firstFreeKey(storeMap, toStoreKey, toCandidate, 1);
351
+ }
352
+
353
+ if (landingKey === NO_FREE_KEY) {
354
+ // Reachable only with a NON-INJECTIVE id transform — see `firstFreeKey`.
355
+ // `createHandler` matches this message and answers 409 rather than letting it
356
+ // reach express's default handler, which serialises a stack trace with
357
+ // absolute install paths outside NODE_ENV=production (the hazard
358
+ // orm-request.ts:553-558 exists to name). Pinned by AC8.
359
+ throw new Error(`${NO_FREE_ID_ERROR} for model "${modelName}"`);
360
+ }
361
+
362
+ rawData.id = landingKey;
220
363
  }
221
364
 
222
- function isStringIdModel(modelName: string): boolean {
223
- const modelClass = Orm.instance.getRecordClasses(modelName).modelClass as (new (name: string) => { [key: string]: unknown }) | undefined;
224
- if (!modelClass) return false;
365
+ // Returned instead of a key so that "no key" cannot be confused with a transform
366
+ // that legitimately produced `undefined` or `null`.
367
+ const NO_FREE_KEY = Symbol('no free store key');
368
+
369
+ /**
370
+ * The first store key at or above `start` that no record occupies, walking
371
+ * candidate ids upward, or `NO_FREE_KEY` if the walk cannot reach one.
372
+ */
373
+ function firstFreeKey(
374
+ storeMap: Map<number | string, unknown>,
375
+ toStoreKey: (value: number | string) => number | string,
376
+ toCandidate: (value: number) => number | string,
377
+ start: number
378
+ ): number | string | typeof NO_FREE_KEY {
379
+ let candidate = start;
380
+ let landingKey = toStoreKey(toCandidate(candidate));
381
+ let attempts = 0;
382
+
383
+ while (storeMap.has(landingKey)) {
384
+ // THE BOUND IS EXACTLY TIGHT, not conservative: this walk tries
385
+ // `storeMap.size + 1` DISTINCT candidates against at most `storeMap.size`
386
+ // occupied keys, so under an injective `toStoreKey` it provably cannot fire.
387
+ // Under a non-injective one it provably terminates — and that is a reachable
388
+ // consumer state rather than a hypothesis: `transforms.boolean`
389
+ // (transforms.ts:4) collapses every candidate onto `true`/`false`, and
390
+ // `Orm.instance.transforms` (main.ts:70) is public and MUTABLE, so a consumer
391
+ // can register an arbitrary non-injective transform and name it as an id
392
+ // type. Without this, a no-id create spins forever inside a synchronous store
393
+ // walk and pins a worker, which is worse than either collision policy. Its
394
+ // EXISTENCE and its THRESHOLD are both pinned by AC8: deleting it makes AC8
395
+ // HANG rather than fail, and weakening it to fire on the first collision
396
+ // makes AC8.1 red.
397
+ if (++attempts > storeMap.size) return NO_FREE_KEY;
398
+
399
+ // NOTE FOR ANYONE ADDING A SECOND EXIT HERE. A `candidate + 1 === candidate`
400
+ // float-saturation check was written, measured, and REMOVED: with the
401
+ // restart-from-1 above in place, deleting the saturation check leaves the
402
+ // whole suite green, because the budget reaches the same `NO_FREE_KEY` one
403
+ // pass later and the restart still answers. An unkillable guard in a change
404
+ // whose deliverable is falsifiable coverage is exactly what this story exists
405
+ // to stop shipping. `+ 1` being a no-op at 2^53 costs `size` extra `Map.has`
406
+ // calls on that one path and changes no outcome.
407
+ candidate += 1;
408
+ landingKey = toStoreKey(toCandidate(candidate));
409
+ }
410
+
411
+ return landingKey;
412
+ }
413
+
414
+ /**
415
+ * Returns the derivation that maps an id VALUE to the store KEY a record
416
+ * carrying it will actually be filed under — the model's declared id transform,
417
+ * the same one `serialize` runs at createRecord:68 before the `.set` at :69.
418
+ */
419
+ function storeKeyDeriver(modelName: string): (value: number | string) => number | string {
420
+ const idType = getIdType(modelName);
421
+ const transform = idType ? Orm.instance?.transforms?.[idType] : undefined;
422
+
423
+ // SURVIVOR, RETAINED, with its reachability condition stated rather than left
424
+ // silent — `docs/project-structure.md` § "unkillable code reads as coverage and
425
+ // is not" is the standing rule and it applies outside orm-request.ts too.
426
+ //
427
+ // No mutation in this repo can kill this branch, and that is STRUCTURAL rather
428
+ // than an untested gap: `Model` declares `id = attr('number')` (model.ts:15) so
429
+ // every registered model has an id type; `ModelProperty` refuses a type with no
430
+ // registered transform (model-property.ts:4) so a declared type always
431
+ // resolves; and `getIdType` can therefore only return `undefined` when
432
+ // `getRecordClasses` yields no `modelClass` — in which case `createRecord`
433
+ // throws at :62 a few lines later regardless, so no record is ever filed
434
+ // through this branch.
435
+ //
436
+ // BECOMES REACHABLE if a model can be declared without an `id` property, if a
437
+ // store map can exist for a model with no registered class, or if
438
+ // `createRecord` stops constructing the model class. Kept rather than deleted
439
+ // because the alternative on that path is a `transform is not a function`
440
+ // TypeError, and because identity is exactly what `createRecord` would file
441
+ // under when no transform exists — the two agree, which is the property AC4 is
442
+ // about.
443
+ if (typeof transform !== 'function') return value => value;
444
+
445
+ return value => {
446
+ try {
447
+ return transform(value) as number | string;
448
+ } catch {
449
+ // `uppercase` and `trim` (transforms.ts:11-12) call a string method on the
450
+ // value directly, so a NUMERIC candidate throws `value?.toUpperCase is not
451
+ // a function`. On `dev` they never saw one — `lastRecord.id + 1` on a
452
+ // string id is a string — so feeding them a number here would regress a
453
+ // legal, registered id type into an uncaught 500. The retry feeds the
454
+ // string form, which is the shape an id actually arrives in off a JSON body
455
+ // or a URL param. A transform that throws on BOTH shapes still propagates.
456
+ // Pinned by AC9.
457
+ return transform(String(value)) as number | string;
458
+ }
459
+ };
460
+ }
461
+
462
+ function getIdType(modelName: string): string | undefined {
463
+ const modelClass = Orm.instance?.getRecordClasses(modelName).modelClass as (new (name: string) => { [key: string]: unknown }) | undefined;
464
+ if (!modelClass) return undefined;
225
465
 
226
466
  const model = new modelClass(modelName);
227
467
 
228
- return (model.id as { type?: string } | undefined)?.type === 'string';
468
+ return (model.id as { type?: string } | undefined)?.type;
469
+ }
470
+
471
+ function isStringIdModel(modelName: string): boolean {
472
+ return getIdType(modelName) === 'string';
229
473
  }