@stonyx/orm 0.3.2-beta.160 → 0.3.2-beta.161
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 +9 -1373
- package/dist/hooks.d.ts +1 -15
- package/dist/index.d.ts +0 -3
- package/dist/index.js +0 -8
- package/dist/main.d.ts +0 -116
- package/dist/main.js +0 -119
- package/dist/manage-record.js +9 -234
- package/dist/orm-request.d.ts +3 -274
- package/dist/orm-request.js +62 -1255
- package/dist/record.d.ts +0 -16
- package/dist/record.js +3 -149
- package/dist/setup-rest-server.js +5 -51
- package/dist/standalone-db.js +5 -17
- package/dist/types/orm-types.d.ts +0 -249
- package/dist/utils.d.ts +0 -44
- package/dist/utils.js +0 -47
- package/package.json +4 -4
- package/src/hooks.ts +1 -15
- package/src/index.ts +0 -10
- package/src/main.ts +0 -123
- package/src/manage-record.ts +9 -253
- package/src/orm-request.ts +65 -1276
- package/src/record.ts +3 -176
- package/src/setup-rest-server.ts +6 -59
- package/src/standalone-db.ts +6 -17
- package/src/types/orm-types.ts +1 -256
- package/src/types/stonyx-rest-server.d.ts +1 -14
- package/src/utils.ts +0 -50
- package/dist/access-verdict.d.ts +0 -85
- package/dist/access-verdict.js +0 -284
- package/src/access-verdict.ts +0 -312
package/dist/utils.js
CHANGED
|
@@ -15,50 +15,3 @@ 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-beta.
|
|
7
|
+
"version": "0.3.2-beta.161",
|
|
8
8
|
"description": "",
|
|
9
9
|
"main": "dist/index.js",
|
|
10
10
|
"type": "module",
|
|
@@ -61,10 +61,10 @@
|
|
|
61
61
|
},
|
|
62
62
|
"homepage": "https://github.com/abofs/stonyx-orm#readme",
|
|
63
63
|
"dependencies": {
|
|
64
|
-
"@stonyx/cron": "0.2.1-beta.
|
|
64
|
+
"@stonyx/cron": "0.2.1-beta.81",
|
|
65
65
|
"@stonyx/events": "0.1.1-beta.52",
|
|
66
66
|
"@stonyx/utils": "0.2.3-beta.26",
|
|
67
|
-
"stonyx": "0.2.3-beta.
|
|
67
|
+
"stonyx": "0.2.3-beta.76"
|
|
68
68
|
},
|
|
69
69
|
"peerDependencies": {
|
|
70
70
|
"@aws-sdk/client-dynamodb": "^3.0.0",
|
|
@@ -91,7 +91,7 @@
|
|
|
91
91
|
}
|
|
92
92
|
},
|
|
93
93
|
"devDependencies": {
|
|
94
|
-
"@stonyx/rest-server": "0.2.1-beta.
|
|
94
|
+
"@stonyx/rest-server": "0.2.1-beta.80",
|
|
95
95
|
"@types/node": "^25.6.0",
|
|
96
96
|
"mysql2": "^3.20.0",
|
|
97
97
|
"pg": "^8.20.0",
|
package/src/hooks.ts
CHANGED
|
@@ -37,21 +37,7 @@ export interface HookContext {
|
|
|
37
37
|
state?: Record<string, unknown>;
|
|
38
38
|
/** Previous record state (available in update hooks). */
|
|
39
39
|
oldState?: unknown;
|
|
40
|
-
/**
|
|
41
|
-
* Target record ID for single-record operations.
|
|
42
|
-
*
|
|
43
|
-
* SET ONLY UNDER `delete`. `_withHooks` assigns this key in the two
|
|
44
|
-
* `operation === 'delete'` branches and nowhere else, so on `get`, `list`,
|
|
45
|
-
* `create` and `update` the key is ABSENT -- not `undefined`-valued, absent.
|
|
46
|
-
* A hook rule written as `ctx.recordId === '<id>'` never fires on an update;
|
|
47
|
-
* the addressed id is in `ctx.params`. Tracked as abofs/stonyx-orm#242.
|
|
48
|
-
*
|
|
49
|
-
* @see AccessContext.recordId in ./types/orm-types.ts -- an identically-named
|
|
50
|
-
* key on an identically-shaped context object, and NOT interchangeable with
|
|
51
|
-
* this one: it is present on every route `auth()` classifies, and spells
|
|
52
|
-
* absence as `null` rather than `undefined`. They differ in coverage on four
|
|
53
|
-
* of five operations, not only in the absence spelling.
|
|
54
|
-
*/
|
|
40
|
+
/** Target record ID for single-record operations. */
|
|
55
41
|
recordId?: string | number;
|
|
56
42
|
/** Response data (available in after hooks). */
|
|
57
43
|
response?: unknown;
|
package/src/index.ts
CHANGED
|
@@ -27,16 +27,6 @@ import { count, avg, sum, min, max } from './aggregates.js';
|
|
|
27
27
|
export { default } from './main.js';
|
|
28
28
|
export { store, relationships } from './main.js';
|
|
29
29
|
export type { PersistErrorDetail } from './main.js';
|
|
30
|
-
export type { AccessContext, AccessFunction, AccessMethod, AccessOperation } from './types/orm-types.js'; // access() contract (#202)
|
|
31
|
-
export type { LinkageFilter } from './types/orm-types.js'; // linkage verdict contract (#234)
|
|
32
|
-
// The request-scoped linkage-verdict factory (#234). PUBLIC on purpose: the
|
|
33
|
-
// README tells a consumer serializing a `Record` outside the REST layer to pass
|
|
34
|
-
// their own resolved `linkage` option, and without an exported factory the only
|
|
35
|
-
// way to follow that advice is to write a SECOND reading of `access()` in
|
|
36
|
-
// consumer code -- the exact "unreviewed second authorization vocabulary" that
|
|
37
|
-
// src/access-verdict.ts exists to prevent, reproduced where no reviewer sees it
|
|
38
|
-
// drift. Give them the one interpreter instead of an invitation to fork it.
|
|
39
|
-
export { createLinkageFilter } from './access-verdict.js';
|
|
40
30
|
export { Model, View, Serializer }; // base classes
|
|
41
31
|
export { attr, belongsTo, hasMany, createRecord, updateRecord }; // helpers
|
|
42
32
|
export { count, avg, sum, min, max }; // aggregate helpers
|
package/src/main.ts
CHANGED
|
@@ -25,7 +25,6 @@ import baseTransforms from './transforms.js';
|
|
|
25
25
|
import Store from './store.js';
|
|
26
26
|
import Serializer from './serializer.js';
|
|
27
27
|
import { setup } from '@stonyx/events';
|
|
28
|
-
import type { AccessFunction } from './types/orm-types.js';
|
|
29
28
|
|
|
30
29
|
interface OrmOptions {
|
|
31
30
|
dbType?: string;
|
|
@@ -69,53 +68,6 @@ export default class Orm {
|
|
|
69
68
|
views: Record<string, unknown> = {};
|
|
70
69
|
transforms: Record<string, (value: unknown) => unknown> = { ...baseTransforms };
|
|
71
70
|
warnings: Set<string> = new Set();
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* Model name -> the `access` predicate of the access class that CLAIMS that
|
|
75
|
-
* model (abofs/stonyx-orm#202).
|
|
76
|
-
*
|
|
77
|
-
* Not "that model's own predicate". One access class may claim many models
|
|
78
|
-
* -- `GlobalAccess` in this repo's fixtures declares five, and `models = '*'`
|
|
79
|
-
* claims every model in the store -- and it declares ONE `access` method, so
|
|
80
|
-
* the same function object is registered under every one of those keys.
|
|
81
|
-
* `getAccess('owner') === getAccess('animal')` is `true` there. The
|
|
82
|
-
* one-to-one guarantee below is key -> function, never function -> model,
|
|
83
|
-
* and a caller must not read a resolved predicate as being animal-specific.
|
|
84
|
-
* What makes the ANSWER model-specific is the context the caller passes and
|
|
85
|
-
* the predicate actually reading it -- see {@link Orm#getAccess}.
|
|
86
|
-
*
|
|
87
|
-
* NAMED FOR WHAT IT HOLDS. It was `accessFiles` through review, inherited
|
|
88
|
-
* from the function-local in `setup-rest-server.ts` where the values came
|
|
89
|
-
* straight out of `forEachFileImport` and "files" was defensible. The values
|
|
90
|
-
* are `AccessFunction`s, and the sibling public registries on this class
|
|
91
|
-
* (`models`, `serializers`, `views`, `transforms`) are all plural nouns of
|
|
92
|
-
* the thing held. Renamed here because #202 is the last moment it is free.
|
|
93
|
-
*
|
|
94
|
-
* Populated by `setup-rest-server.ts` at boot, from the access classes under
|
|
95
|
-
* `config.orm.paths.access`, BEFORE any route is mounted -- so it is complete
|
|
96
|
-
* and reachable before the first request can be served. The mapping is
|
|
97
|
-
* one-to-one by construction: setup-rest-server throws if two access classes
|
|
98
|
-
* claim the same model.
|
|
99
|
-
*
|
|
100
|
-
* Keys are model names as declared and stored (kebab-case, e.g.
|
|
101
|
-
* `'phone-number'`), NOT pluralised or mount-prefixed route names.
|
|
102
|
-
*
|
|
103
|
-
* WHY THIS EXISTS AS A FIELD. It used to be a function-local in
|
|
104
|
-
* setup-rest-server that was discarded when that function returned, so at
|
|
105
|
-
* request time there was no way to get from a model name to that model's
|
|
106
|
-
* predicate at all. Each `OrmRequest` held only its OWN model's predicate.
|
|
107
|
-
* That made cross-model authorization -- asking model X's predicate about a
|
|
108
|
-
* request routed to model Y -- inexpressible, which is the capability
|
|
109
|
-
* abofs/stonyx-orm#196 and abofs/stonyx-orm#207 are built on.
|
|
110
|
-
*
|
|
111
|
-
* Empty when the REST server is disabled, and PARTIAL when one access file
|
|
112
|
-
* failed to load (`setup-rest-server.ts` catches, warns and assigns whatever
|
|
113
|
-
* it had). So a missing key does NOT mean the model has no access class.
|
|
114
|
-
* Prefer {@link Orm#getAccess} over indexing this directly -- it is guarded
|
|
115
|
-
* against the prototype chain and this is not.
|
|
116
|
-
*/
|
|
117
|
-
accessFunctions: Record<string, AccessFunction> = {};
|
|
118
|
-
|
|
119
71
|
options!: OrmOptions;
|
|
120
72
|
sqlDb?: SqlDb;
|
|
121
73
|
db?: OrmDB | SqlDb;
|
|
@@ -243,81 +195,6 @@ export default class Orm {
|
|
|
243
195
|
Orm.initialized = true;
|
|
244
196
|
}
|
|
245
197
|
|
|
246
|
-
/**
|
|
247
|
-
* Resolve the `access` predicate registered for a model name
|
|
248
|
-
* (abofs/stonyx-orm#202).
|
|
249
|
-
*
|
|
250
|
-
* This is the supported way to reach another model's predicate while
|
|
251
|
-
* servicing a request routed to a different model. Call it with the model
|
|
252
|
-
* name and invoke the result with the live request and an explicit context
|
|
253
|
-
* naming THAT model:
|
|
254
|
-
*
|
|
255
|
-
* ```js
|
|
256
|
-
* const predicate = Orm.instance.getAccess('animal');
|
|
257
|
-
* if (!predicate) return deny;
|
|
258
|
-
* const verdict = predicate(request, { model: 'animal', operation: 'read' });
|
|
259
|
-
* ```
|
|
260
|
-
*
|
|
261
|
-
* WHAT IT RESOLVES. The predicate of the access CLASS that claims the model,
|
|
262
|
-
* which is not necessarily specific to it: one class may claim many models
|
|
263
|
-
* and declares one `access` method, so
|
|
264
|
-
* `getAccess('owner') === getAccess('animal')` is `true` against this repo's
|
|
265
|
-
* fixture. See {@link Orm#accessFunctions}.
|
|
266
|
-
*
|
|
267
|
-
* `undefined` means NO PREDICATE COULD BE RESOLVED for that name. That
|
|
268
|
-
* includes a model whose access class failed to LOAD -- `setup-rest-server`
|
|
269
|
-
* catches, warns and publishes the partial map -- so it is not the same claim
|
|
270
|
-
* as "this model is unrestricted". Treat it as DENY, the same way
|
|
271
|
-
* `AccessContext.operation === undefined` is treated.
|
|
272
|
-
*
|
|
273
|
-
* PASSING THE CONTEXT MAKES A MODEL-CORRECT ANSWER POSSIBLE. It does not, on
|
|
274
|
-
* its own, make the answer model-correct: the resolved predicate has to READ
|
|
275
|
-
* the context. Measured against this repo's shipped access class on a request
|
|
276
|
-
* express dispatched to `GET /owners/angela`, asked about ANIMALS:
|
|
277
|
-
*
|
|
278
|
-
* ```
|
|
279
|
-
* getAccess('animal')(ownersRequest, { model: 'animal', operation: 'read' })
|
|
280
|
-
* -> record => record.id !== 'angela' && record.id !== 'restricted'
|
|
281
|
-
* ```
|
|
282
|
-
*
|
|
283
|
-
* The OWNERS filter, which returns `true` for animal 21 -- the record hidden
|
|
284
|
-
* on every animal surface. Under a mount that predicate recognises neither
|
|
285
|
-
* way it falls through to `['read', 'create', 'update', 'delete']`, a full
|
|
286
|
-
* CRUD grant. Either way: context supplied, answer not the animal answer,
|
|
287
|
-
* wrong in the GRANTING direction, because that predicate is arity-1 and
|
|
288
|
-
* identifies its collection from the request. AC9 asserts the first case on a
|
|
289
|
-
* live dispatch.
|
|
290
|
-
*
|
|
291
|
-
* Every predicate in this repo and in every consumer tree is arity-1 today,
|
|
292
|
-
* and there is no supported way for the caller to tell which kind it got; the
|
|
293
|
-
* boot-time arity warning that would surface it is abofs/stonyx-orm#213. Pass
|
|
294
|
-
* the context, and do not treat a resolved predicate's answer as
|
|
295
|
-
* model-specific until that predicate reads it.
|
|
296
|
-
*
|
|
297
|
-
* OWN PROPERTIES ONLY. A bare `this.accessFunctions[modelName]` walks the
|
|
298
|
-
* prototype chain, so `getAccess('constructor')` resolved `Object` and
|
|
299
|
-
* `getAccess('toString')` resolved `Object.prototype.toString` -- both
|
|
300
|
-
* callable, and the documented `predicate?.(request, ctx)` pattern then
|
|
301
|
-
* returned a TRUTHY value (`Object(request)` is the request), bypassing the
|
|
302
|
-
* `undefined`-means-deny contract entirely. Nothing in the ORM calls
|
|
303
|
-
* `getAccess` yet, so it was not exploitable as shipped -- but #207 takes the
|
|
304
|
-
* model name from the REQUEST BODY (`data.relationships.<key>.data.type`),
|
|
305
|
-
* which would have made a one-field body an authorization bypass. Guarded
|
|
306
|
-
* here at the read point rather than by constructing the map with a null
|
|
307
|
-
* prototype, because the field is public and reassignable and the guard has
|
|
308
|
-
* to hold whatever object it is holding.
|
|
309
|
-
*
|
|
310
|
-
* @param modelName - Model name as declared and stored (kebab-case).
|
|
311
|
-
* @returns The predicate, or `undefined` when no predicate could be resolved
|
|
312
|
-
* for that name. `undefined` is NOT "this model is unrestricted" -- see the
|
|
313
|
-
* note above. Treat it as deny.
|
|
314
|
-
*/
|
|
315
|
-
getAccess(modelName: string): AccessFunction | undefined {
|
|
316
|
-
if (!Object.hasOwn(this.accessFunctions, modelName)) return undefined;
|
|
317
|
-
|
|
318
|
-
return this.accessFunctions[modelName];
|
|
319
|
-
}
|
|
320
|
-
|
|
321
198
|
async startup(): Promise<void> {
|
|
322
199
|
if (this.sqlDb) await this.sqlDb.startup();
|
|
323
200
|
}
|
package/src/manage-record.ts
CHANGED
|
@@ -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
|
|
5
|
+
import { isOrmRecord } from './utils.js';
|
|
6
6
|
|
|
7
7
|
interface CreateRecordOptions {
|
|
8
8
|
isDbRecord?: boolean;
|
|
@@ -195,58 +195,17 @@ export function updateRecord(record: OrmRecord, rawData: unknown, userOptions: C
|
|
|
195
195
|
}
|
|
196
196
|
|
|
197
197
|
/**
|
|
198
|
-
* gets the next available id
|
|
198
|
+
* gets the next available id based on last record entry.
|
|
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
|
-
* ---------------------------------------------------------------------------
|
|
220
202
|
*/
|
|
221
203
|
function assignRecordId(modelName: string, rawData: { [key: string]: unknown }): void {
|
|
222
|
-
|
|
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;
|
|
204
|
+
if (rawData.id) return;
|
|
240
205
|
|
|
241
206
|
// In SQL mode with numeric IDs, defer to database auto-increment.
|
|
242
207
|
// Use unique negative integers — they survive the number transform (parseInt preserves negatives)
|
|
243
208
|
// 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.
|
|
250
209
|
if (Orm.instance?.sqlDb && !isStringIdModel(modelName)) {
|
|
251
210
|
rawData.id = -(++pendingIdCounter);
|
|
252
211
|
rawData.__pendingSqlId = true;
|
|
@@ -256,218 +215,15 @@ function assignRecordId(modelName: string, rawData: { [key: string]: unknown }):
|
|
|
256
215
|
const storeMap = store.get(modelName);
|
|
257
216
|
if (!storeMap) throw new Error(`Cannot assign record ID: model "${modelName}" not found in store`);
|
|
258
217
|
const modelStore = Array.from(storeMap.values()).filter(isOrmRecord);
|
|
259
|
-
|
|
260
|
-
|
|
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;
|
|
218
|
+
const lastRecord = modelStore.at(-1);
|
|
219
|
+
rawData.id = lastRecord ? (lastRecord.id as number) + 1 : 1;
|
|
363
220
|
}
|
|
364
221
|
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
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;
|
|
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;
|
|
465
225
|
|
|
466
226
|
const model = new modelClass(modelName);
|
|
467
227
|
|
|
468
|
-
return (model.id as { type?: string } | undefined)?.type;
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
function isStringIdModel(modelName: string): boolean {
|
|
472
|
-
return getIdType(modelName) === 'string';
|
|
228
|
+
return (model.id as { type?: string } | undefined)?.type === 'string';
|
|
473
229
|
}
|