@forestfuture/active-record 0.8.1 → 0.9.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/dist/adapter.d.mts +2 -2
- package/dist/adapter.mjs +4 -4
- package/dist/{batch-Ms5p9lKq.mjs → batch-Ca1JtVcK.mjs} +8600 -7283
- package/dist/cli.d.mts +4 -4
- package/dist/cli.mjs +3 -3
- package/dist/command.mjs +19 -18
- package/dist/d1.d.mts +2 -2
- package/dist/d1.mjs +9 -4
- package/dist/for-adapters-Bl6BCiR1.mjs +12 -0
- package/dist/{for-adapters-BbIMUNcz.mjs → for-adapters-D35a5x3t.mjs} +6 -3
- package/dist/{for-adapters-BT2GDjIA.d.mts → for-adapters-DoyXc8Dq.d.mts} +1 -1
- package/dist/{generated-model-DJA8vmNE.mjs → generated-model-L4WAqgOZ.mjs} +1488 -684
- package/dist/{identifiers-Dh5DFACX.mjs → identifiers-CzqYL_nC.mjs} +283 -258
- package/dist/{index-D5getfHx.d.mts → index-Fq4gT3c8.d.mts} +117 -77
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +5 -5
- package/dist/metadata-BIUbGJlS.d.mts +363 -0
- package/dist/{plugin-CZPDqguF.mjs → plugin-BHUP4ssD.mjs} +10 -7
- package/dist/{plugin-Cf-5Z0_h.mjs → plugin-BMAJKgj6.mjs} +7 -7
- package/dist/postgresql.d.mts +1 -1
- package/dist/postgresql.mjs +28 -4
- package/dist/{src-BAVZKQ7J.mjs → src-fYq-nVHE.mjs} +2 -2
- package/dist/{storage-override-0ZgeP2sc.mjs → storage-override-yF2NT5ST.mjs} +1 -1
- package/dist/{validations-BSZ5gVeI.d.mts → validations-CKPJoSj4.d.mts} +507 -269
- package/llms-full.txt +9202 -4192
- package/package.json +1 -1
- package/skills/active-record/SKILL.md +6 -5
- package/dist/for-adapters-C-MQxaIx.mjs +0 -31
- package/dist/metadata-CzntpYzC.d.mts +0 -182
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as pluralize,
|
|
1
|
+
import { B as MissingAttribute, C as pluralize, D as underscore, E as capitalized, L as InvalidModel, S as listedNames, V as NoDatabase, W as RecordDestroyed, _ as enumEntries, a as isSameCell, c as castValue, d as uncastable, et as UnknownAttribute, h as digitsProblem, l as isInvalidDate, n as reservedWords, o as castCondition, p as writeValue, r as epochStorages, s as castKey, t as isIdentifier, u as readValue, v as enumProblem, x as isEnumValues } from "./identifiers-CzqYL_nC.mjs";
|
|
2
2
|
// src/ancestors.ts
|
|
3
3
|
/** A class and every class (and object) it extends, nearest first. */
|
|
4
4
|
function ancestors(model) {
|
|
@@ -38,7 +38,7 @@ function modelNameOf(model) {
|
|
|
38
38
|
return model.modelName;
|
|
39
39
|
}
|
|
40
40
|
/**
|
|
41
|
-
* Gives the library's base class `modelName`: each class's own name,
|
|
41
|
+
* Gives the library's base class `modelName`: each class's own name,
|
|
42
42
|
* unless it sets `static modelName = "…"`, which the classes extending it inherit (a set one is
|
|
43
43
|
* a value, found before this getter). Empty for a class with no name: anonymous, or `export
|
|
44
44
|
* default`.
|
|
@@ -53,8 +53,8 @@ function defineModelName(root) {
|
|
|
53
53
|
});
|
|
54
54
|
}
|
|
55
55
|
/**
|
|
56
|
-
* The `modelName` of the class that extends `base` directly, the one a table is named after
|
|
57
|
-
*
|
|
56
|
+
* The `modelName` of the class that extends `base` directly, the one a table is named after;
|
|
57
|
+
* empty when it has none (anonymous, `export default`, or `Model.define({...})` itself).
|
|
58
58
|
*/
|
|
59
59
|
function modelNameBelow(base, model) {
|
|
60
60
|
let current = model;
|
|
@@ -62,7 +62,7 @@ function modelNameBelow(base, model) {
|
|
|
62
62
|
return current === base ? "" : modelNameOf(current);
|
|
63
63
|
}
|
|
64
64
|
/**
|
|
65
|
-
* A class name's table
|
|
65
|
+
* A class name's table: the name through `underscore`, pluralized
|
|
66
66
|
* (`BlogPost` → `blog_posts`, `Person` → `people`). The generators name tables with it too.
|
|
67
67
|
*/
|
|
68
68
|
function tableize(className) {
|
|
@@ -125,7 +125,7 @@ function boundTableOf(model) {
|
|
|
125
125
|
}
|
|
126
126
|
/**
|
|
127
127
|
* Whether a Model ignores some of its table's columns, so its queries name their columns rather
|
|
128
|
-
* than `*` and an ignored column is never read
|
|
128
|
+
* than `*` and an ignored column is never read. The nearest bound table decides.
|
|
129
129
|
* Remembered per Model: its table is bound when it's first used, before any query, so the
|
|
130
130
|
* answer can't change.
|
|
131
131
|
*/
|
|
@@ -139,7 +139,7 @@ function isIgnoringColumns(model) {
|
|
|
139
139
|
}
|
|
140
140
|
/**
|
|
141
141
|
* An abstract base class (the app's `ApplicationRecord`, or one marked `static abstract = true`)
|
|
142
|
-
* has no table
|
|
142
|
+
* has no table: it's only inherited from, so using it is an
|
|
143
143
|
* `InvalidModel`.
|
|
144
144
|
*/
|
|
145
145
|
function rejectAbstract(model) {
|
|
@@ -180,60 +180,344 @@ function tableOwnerModelName(model) {
|
|
|
180
180
|
if (base !== void 0) return modelNameBelow(base, model);
|
|
181
181
|
return modelNameOf(boundTableOf(model)?.owner ?? model);
|
|
182
182
|
}
|
|
183
|
-
// src/
|
|
184
|
-
/** What a listener sees in place of a filtered attribute's value (#83). */
|
|
185
|
-
const FILTERED = "[FILTERED]";
|
|
183
|
+
// src/declarations.ts
|
|
186
184
|
/**
|
|
187
|
-
*
|
|
188
|
-
*
|
|
185
|
+
* Per-Model declarations (validations, callbacks, …), keyed by Model class. A subclass starts
|
|
186
|
+
* from a copy of its parent's list, so declaring on it never changes the parent.
|
|
187
|
+
*
|
|
188
|
+
* Module-level, but not request state (ADR-0003): declarations are made once, when a Model
|
|
189
|
+
* class is defined, and only read afterwards.
|
|
189
190
|
*/
|
|
190
|
-
const
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
"_key",
|
|
196
|
-
"crypt",
|
|
197
|
-
"salt",
|
|
198
|
-
"certificate",
|
|
199
|
-
"otp",
|
|
200
|
-
"ssn",
|
|
201
|
-
"cvv",
|
|
202
|
-
"cvc"
|
|
203
|
-
];
|
|
191
|
+
const registry = /* @__PURE__ */ new WeakMap();
|
|
192
|
+
/** The declarations each class made itself, without its parent's, for reading class by class. */
|
|
193
|
+
const ownRegistry = /* @__PURE__ */ new WeakMap();
|
|
194
|
+
/** Models that have been used; their declarations can no longer change. */
|
|
195
|
+
const sealed = /* @__PURE__ */ new WeakSet();
|
|
204
196
|
/**
|
|
205
|
-
*
|
|
206
|
-
*
|
|
207
|
-
* matches the attribute or its snake_case name.
|
|
197
|
+
* Called on a Model's first use. From then on, declaring on it throws: declarations belong in
|
|
198
|
+
* the class's `static {}` block, never in request code, where they'd leak into every request.
|
|
208
199
|
*/
|
|
209
|
-
function
|
|
210
|
-
|
|
211
|
-
return model.filterAttributes.some((entry) => typeof entry === "string" ? name.includes(entry.toLowerCase()) || name.includes(underscore(entry)) : attribute.search(entry) !== -1 || name.search(entry) !== -1);
|
|
200
|
+
function seal(model) {
|
|
201
|
+
sealed.add(model);
|
|
212
202
|
}
|
|
213
|
-
/**
|
|
214
|
-
function
|
|
215
|
-
return
|
|
203
|
+
/** Whether a Model has been used, so its declarations, and its ancestors', can no longer change. */
|
|
204
|
+
function isSealed(model) {
|
|
205
|
+
return sealed.has(model);
|
|
216
206
|
}
|
|
217
|
-
/**
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
207
|
+
/** The declarations of `kind` for `model`: its own, or else its nearest ancestor's. */
|
|
208
|
+
function declared(model, kind) {
|
|
209
|
+
for (const current of ancestors(model)) {
|
|
210
|
+
const list = registry.get(current)?.get(kind);
|
|
211
|
+
if (list !== void 0) return list;
|
|
212
|
+
}
|
|
213
|
+
return [];
|
|
214
|
+
}
|
|
215
|
+
/** The declarations of `kind` that `model` and each class it extends made themselves, nearest first. */
|
|
216
|
+
function declaredByClass(model, kind) {
|
|
217
|
+
return ancestors(model).flatMap((from) => {
|
|
218
|
+
const values = ownRegistry.get(from)?.get(kind);
|
|
219
|
+
return values === void 0 ? [] : [{
|
|
220
|
+
from,
|
|
221
|
+
values
|
|
222
|
+
}];
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
/** Adds a declaration of `kind` to `model`, copying its inherited list first. */
|
|
226
|
+
function declare(model, kind, entry) {
|
|
227
|
+
if (sealed.has(model)) {
|
|
228
|
+
const { name } = model;
|
|
229
|
+
throw new InvalidModel(`${name} has already been used; declare validations, callbacks and messages in its static {} block`);
|
|
230
|
+
}
|
|
231
|
+
listsOf(registry, model).set(kind, [...declared(model, kind), entry]);
|
|
232
|
+
const own = listsOf(ownRegistry, model);
|
|
233
|
+
own.set(kind, [...own.get(kind) ?? [], entry]);
|
|
234
|
+
}
|
|
235
|
+
/** `model`'s lists in a registry, by kind, made empty the first time. */
|
|
236
|
+
function listsOf(lists, model) {
|
|
237
|
+
const found = lists.get(model) ?? /* @__PURE__ */ new Map();
|
|
238
|
+
lists.set(model, found);
|
|
239
|
+
return found;
|
|
240
|
+
}
|
|
241
|
+
// src/attribute-aliases.ts
|
|
242
|
+
/** Whether a declared attribute is an alias: an object with `aliasOf`. */
|
|
243
|
+
function isAlias(declared) {
|
|
244
|
+
return typeof declared === "object" && declared !== null && "aliasOf" in declared;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* The aliases a Model's declared attributes hold, by alias, each to the attribute it names;
|
|
248
|
+
* `prefix` goes before an alias's name in an error (`"Post."`, or nothing for `define`).
|
|
249
|
+
*/
|
|
250
|
+
function aliasesIn(prefix, declared, attributes) {
|
|
251
|
+
const given = Object.entries(declared).filter((entry) => isAlias(entry[1]));
|
|
252
|
+
const aliases = new Map(given.map(([name, { aliasOf }]) => [name, aliasOf]));
|
|
253
|
+
for (const [name, alias] of given) {
|
|
254
|
+
const problem = aliasProblem(name, alias, aliases, attributes);
|
|
255
|
+
if (problem !== void 0) throw new InvalidModel(`${prefix}${name}${problem}`);
|
|
256
|
+
}
|
|
257
|
+
return aliases;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* What's wrong with an alias, after its name: another key, a name that's an attribute already,
|
|
261
|
+
* an alias of an alias, or of a name that isn't an attribute.
|
|
262
|
+
*/
|
|
263
|
+
function aliasProblem(name, alias, aliases, attributes) {
|
|
264
|
+
const { aliasOf } = alias;
|
|
265
|
+
if (Object.keys(alias).length !== 1 || typeof aliasOf !== "string") return ": an alias is { aliasOf: \"attribute\" }, and nothing else";
|
|
266
|
+
if (attributes.has(name)) return " is an attribute already, so it can't be an alias";
|
|
267
|
+
const target = aliases.get(aliasOf);
|
|
268
|
+
if (target !== void 0) return ` is an alias of ${aliasOf}, an alias itself; name ${target}`;
|
|
269
|
+
if (!attributes.has(aliasOf)) return ` is an alias of ${aliasOf}, which isn't an attribute`;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* The attribute `name` names: itself, or the one it's an alias of. Every name a query, a write, a
|
|
273
|
+
* validation or a change-tracking method takes goes through it.
|
|
274
|
+
*/
|
|
275
|
+
function attributeName(model, name) {
|
|
276
|
+
return model.attributeAliases?.get(name) ?? name;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* `values` keyed by attribute: an alias's value under the attribute it names, so a row writes
|
|
280
|
+
* each column once. Giving both an alias and its attribute is a `TypeError`.
|
|
281
|
+
*/
|
|
282
|
+
function withAttributeNames(model, values) {
|
|
283
|
+
const givenAs = /* @__PURE__ */ new Map();
|
|
284
|
+
for (const given of Object.keys(values)) {
|
|
285
|
+
const name = attributeName(model, given);
|
|
286
|
+
const earlier = givenAs.get(name);
|
|
287
|
+
if (earlier !== void 0) {
|
|
288
|
+
const alias = given === name ? earlier : given;
|
|
289
|
+
throw new TypeError(`${model.name}: ${alias} is an alias of ${name}, so give one of them`);
|
|
290
|
+
}
|
|
291
|
+
givenAs.set(name, given);
|
|
292
|
+
}
|
|
293
|
+
return Object.fromEntries([...givenAs].map(([name, given]) => [name, values[given]]));
|
|
294
|
+
}
|
|
295
|
+
// src/password-algorithm.ts
|
|
296
|
+
/**
|
|
297
|
+
* The iterations a new digest takes: the most Workers allow in production, as each request's CPU
|
|
298
|
+
* time can't stop PBKDF2 once it's started.
|
|
299
|
+
*/
|
|
300
|
+
const ITERATIONS = 1e5;
|
|
301
|
+
const SALT_BYTES = 16;
|
|
302
|
+
const KEY_BITS = 256;
|
|
303
|
+
const PREFIX = "$pbkdf2-sha256$";
|
|
304
|
+
/** `$pbkdf2-sha256$i=<iterations>$<salt>$<key>`, each part in base64 without padding. */
|
|
305
|
+
const DIGEST = /^\$pbkdf2-sha256\$i=(\d{1,9})\$([A-Za-z0-9+/]+)\$([A-Za-z0-9+/]+)$/;
|
|
306
|
+
/**
|
|
307
|
+
* The default algorithm: PBKDF2 with HMAC-SHA256, a 16-byte salt, and the iterations its digest
|
|
308
|
+
* names, so a digest made with another count still verifies. At most 72 bytes, as bcrypt's.
|
|
309
|
+
*/
|
|
310
|
+
const pbkdf2Sha256 = {
|
|
311
|
+
maxBytes: 72,
|
|
312
|
+
async hash(password) {
|
|
313
|
+
const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES));
|
|
314
|
+
const key = await derive(password, salt, ITERATIONS);
|
|
315
|
+
return `${PREFIX}i=${ITERATIONS}$${toBase64(salt)}$${toBase64(key)}`;
|
|
316
|
+
},
|
|
317
|
+
async verify(password, digest) {
|
|
318
|
+
const { iterations, salt, key } = parsed(digest);
|
|
319
|
+
return isSameBytes(await derive(password, salt, iterations), key);
|
|
224
320
|
}
|
|
225
321
|
};
|
|
226
|
-
/**
|
|
227
|
-
|
|
228
|
-
|
|
322
|
+
/**
|
|
323
|
+
* The fewest and most iterations a digest may name: a digest is data, so one naming a count no
|
|
324
|
+
* digest this algorithm made could have would weaken a check, or stall it.
|
|
325
|
+
*/
|
|
326
|
+
const FEWEST_ITERATIONS = 1e3;
|
|
327
|
+
const MOST_ITERATIONS = 1e7;
|
|
328
|
+
/** A digest's parts; `TypeError` for one this algorithm couldn't have made. */
|
|
329
|
+
function parsed(digest) {
|
|
330
|
+
const [, count = "", salt = "", key = ""] = DIGEST.exec(digest) ?? [];
|
|
331
|
+
const iterations = Number(count);
|
|
332
|
+
const decoded = {
|
|
333
|
+
iterations,
|
|
334
|
+
salt: fromBase64(salt),
|
|
335
|
+
key: fromBase64(key)
|
|
336
|
+
};
|
|
337
|
+
if (!(iterations >= FEWEST_ITERATIONS && iterations <= MOST_ITERATIONS && decoded.salt.length === SALT_BYTES && decoded.key.length === KEY_BITS / 8)) throw new TypeError(`The password digest isn't one PBKDF2-SHA256 made (${PREFIX}…); give the algorithm that made it as securePassword's algorithm`);
|
|
338
|
+
return decoded;
|
|
339
|
+
}
|
|
340
|
+
/** PBKDF2-SHA256's key for `password`'s UTF-8 bytes. */
|
|
341
|
+
async function derive(password, salt, iterations) {
|
|
342
|
+
const material = await crypto.subtle.importKey("raw", new TextEncoder().encode(password), "PBKDF2", false, ["deriveBits"]);
|
|
343
|
+
const bits = await crypto.subtle.deriveBits({
|
|
344
|
+
name: "PBKDF2",
|
|
345
|
+
hash: "SHA-256",
|
|
346
|
+
salt,
|
|
347
|
+
iterations
|
|
348
|
+
}, material, KEY_BITS);
|
|
349
|
+
return new Uint8Array(bits);
|
|
350
|
+
}
|
|
351
|
+
/** Whether two keys are the same, in a time that doesn't depend on where they differ. */
|
|
352
|
+
function isSameBytes(left, right) {
|
|
353
|
+
if (left.length !== right.length) return false;
|
|
354
|
+
let difference = 0;
|
|
355
|
+
for (let index = 0; index < left.length; index += 1) difference |= left[index] ^ right[index];
|
|
356
|
+
return difference === 0;
|
|
357
|
+
}
|
|
358
|
+
function toBase64(bytes) {
|
|
359
|
+
return btoa(String.fromCharCode(...bytes)).replaceAll("=", "");
|
|
360
|
+
}
|
|
361
|
+
/** Base64's bytes; none for text that isn't base64, which a digest's check then refuses. */
|
|
362
|
+
function fromBase64(text) {
|
|
363
|
+
try {
|
|
364
|
+
return Uint8Array.from(atob(text), (character) => character.charCodeAt(0));
|
|
365
|
+
} catch {
|
|
366
|
+
return /* @__PURE__ */ new Uint8Array();
|
|
367
|
+
}
|
|
229
368
|
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
369
|
+
// src/custom-types.ts
|
|
370
|
+
/** Every type `defineType` made, so a spec can't pass off another object as one. */
|
|
371
|
+
const defined = /* @__PURE__ */ new WeakSet();
|
|
372
|
+
/**
|
|
373
|
+
* Defines an attribute type, used in a spec as a type name is: `price: money`, or
|
|
374
|
+
* `{ type: money, null: false }`. Its values are kept as `storedAs` keeps its own, so they're
|
|
375
|
+
* read strictly, compared and ordered as that type's are.
|
|
376
|
+
*/
|
|
377
|
+
function defineType(type) {
|
|
378
|
+
requireWellFormed(type);
|
|
379
|
+
const made = Object.freeze({
|
|
380
|
+
storedAs: type.storedAs,
|
|
381
|
+
cast: (input) => type.cast(input),
|
|
382
|
+
serialize: (value) => type.serialize(value),
|
|
383
|
+
deserialize: (stored) => type.deserialize(stored)
|
|
384
|
+
});
|
|
385
|
+
defined.add(made);
|
|
386
|
+
return made;
|
|
233
387
|
}
|
|
234
|
-
/** The
|
|
235
|
-
|
|
236
|
-
|
|
388
|
+
/** The functions a type needs, each checked when it's made. */
|
|
389
|
+
const functionNames = [
|
|
390
|
+
"cast",
|
|
391
|
+
"serialize",
|
|
392
|
+
"deserialize"
|
|
393
|
+
];
|
|
394
|
+
/**
|
|
395
|
+
* Throws `TypeError` for a type that couldn't work, past the types (plain JavaScript, or a cast):
|
|
396
|
+
* a `storedAs` that isn't a built-in type's name, or a function it lacks.
|
|
397
|
+
*/
|
|
398
|
+
function requireWellFormed(type) {
|
|
399
|
+
if (!isAttributeType(type.storedAs)) throw new TypeError(`defineType: storedAs ${JSON.stringify(type.storedAs)} isn't a type's name; use ${attributeTypeNames}`);
|
|
400
|
+
const missing = functionNames.find((name) => typeof type[name] !== "function");
|
|
401
|
+
if (missing !== void 0) throw new TypeError(`defineType: ${missing} isn't a function`);
|
|
402
|
+
}
|
|
403
|
+
/** Whether `value` is a type `defineType` made. */
|
|
404
|
+
function isCustomType(value) {
|
|
405
|
+
return typeof value === "object" && value !== null && defined.has(value);
|
|
406
|
+
}
|
|
407
|
+
// src/durations.ts
|
|
408
|
+
const SECONDS = {
|
|
409
|
+
seconds: 1,
|
|
410
|
+
minutes: 60,
|
|
411
|
+
hours: 3600,
|
|
412
|
+
days: 86400
|
|
413
|
+
};
|
|
414
|
+
/** The longest a token may last: 10,000 years, well inside what a Date can hold from now. */
|
|
415
|
+
const MOST_SECONDS = 365e4 * SECONDS.days;
|
|
416
|
+
/**
|
|
417
|
+
* Whether `value` is a duration: one or more units, each a number that isn't negative, lasting
|
|
418
|
+
* at most 10,000 years in all.
|
|
419
|
+
*/
|
|
420
|
+
function isDuration(value) {
|
|
421
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
422
|
+
const entries = Object.entries(value).filter(([, each]) => each !== void 0);
|
|
423
|
+
const isEach = entries.every(([unit, each]) => Object.hasOwn(SECONDS, unit) && typeof each === "number" && each >= 0);
|
|
424
|
+
return entries.length > 0 && isEach && totalSeconds(entries) <= MOST_SECONDS;
|
|
425
|
+
}
|
|
426
|
+
function totalSeconds(entries) {
|
|
427
|
+
return entries.reduce((total, [unit, value]) => total + SECONDS[unit] * value, 0);
|
|
428
|
+
}
|
|
429
|
+
/** The seconds a duration lasts; `TypeError`, after `where`, for one that isn't a duration. */
|
|
430
|
+
function secondsOf(duration, where) {
|
|
431
|
+
if (!isDuration(duration)) throw new TypeError(`${where} takes a duration such as { minutes: 15 }: seconds, minutes, hours or days, none negative, at most 10,000 years`);
|
|
432
|
+
return totalSeconds(Object.entries(duration).filter(([, value]) => value !== void 0));
|
|
433
|
+
}
|
|
434
|
+
/** When a token made now, lasting `duration`, expires. */
|
|
435
|
+
function expiryAfter(duration, where) {
|
|
436
|
+
return new Date(Date.now() + secondsOf(duration, where) * 1e3);
|
|
437
|
+
}
|
|
438
|
+
// src/secure-tokens.ts
|
|
439
|
+
/** The fewest characters a secure token has. */
|
|
440
|
+
const MINIMUM_TOKEN_LENGTH = 24;
|
|
441
|
+
/** Base58: digits and letters, without `0`, `O`, `I` and `l`, which read alike. */
|
|
442
|
+
const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
443
|
+
/** The bytes below it map onto the alphabet evenly; the rest are drawn again. */
|
|
444
|
+
const EVEN_BYTES = 232;
|
|
445
|
+
/**
|
|
446
|
+
* A random base58 token of `length` characters (24 unless given), from `crypto.getRandomValues`,
|
|
447
|
+
* each character equally likely. Nothing checks it's unique: a unique index does that.
|
|
448
|
+
*/
|
|
449
|
+
function generateSecureToken(length = MINIMUM_TOKEN_LENGTH) {
|
|
450
|
+
if (!Number.isSafeInteger(length) || length < 1) throw new RangeError(`generateSecureToken needs a whole number of characters, not ${length}`);
|
|
451
|
+
let token = "";
|
|
452
|
+
while (token.length < length) for (const byte of crypto.getRandomValues(new Uint8Array(length))) if (byte < EVEN_BYTES && token.length < length) token += ALPHABET[byte % 58];
|
|
453
|
+
return token;
|
|
454
|
+
}
|
|
455
|
+
/** Whether an attribute's `secureToken` is well formed: `true`, `false`, or its options. */
|
|
456
|
+
function isSecureTokenOption(value) {
|
|
457
|
+
if (typeof value === "boolean") return true;
|
|
458
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
459
|
+
return Object.entries(value).every(([key, each]) => isTokenOption(key, each));
|
|
460
|
+
}
|
|
461
|
+
function isTokenOption(key, value) {
|
|
462
|
+
if (value === void 0) return true;
|
|
463
|
+
if (key === "length") return Number.isSafeInteger(value);
|
|
464
|
+
if (key === "prefix") return value === true || typeof value === "string" && value !== "";
|
|
465
|
+
return key === "on" && (value === "initialize" || value === "create");
|
|
466
|
+
}
|
|
467
|
+
/** What's wrong with a well-formed `secureToken`, after the attribute's name: too short a length. */
|
|
468
|
+
function secureTokenProblem(value) {
|
|
469
|
+
const length = value?.length;
|
|
470
|
+
return length !== void 0 && length < MINIMUM_TOKEN_LENGTH ? ` has a secureToken of length ${length}; a secure token is at least ${MINIMUM_TOKEN_LENGTH} characters` : void 0;
|
|
471
|
+
}
|
|
472
|
+
/** An attribute's secure token options, if it has one. */
|
|
473
|
+
function tokenOptionsOf(definition) {
|
|
474
|
+
const { secureToken } = definition;
|
|
475
|
+
if (secureToken === void 0) return void 0;
|
|
476
|
+
return secureToken === true ? {} : secureToken;
|
|
477
|
+
}
|
|
478
|
+
/** Whether an attribute's token is generated as a record is built: its `on` isn't `"create"`. */
|
|
479
|
+
function isTokenOnInitialize(definition) {
|
|
480
|
+
const options = tokenOptionsOf(definition);
|
|
481
|
+
return options !== void 0 && options.on !== "create";
|
|
482
|
+
}
|
|
483
|
+
/** A new token for an attribute declared with `secureToken`: its prefix, then its characters. */
|
|
484
|
+
function tokenFor(definition) {
|
|
485
|
+
const { length = MINIMUM_TOKEN_LENGTH, prefix } = tokenOptionsOf(definition) ?? {};
|
|
486
|
+
return `${prefix === true ? `${definition.column}_` : prefix ?? ""}${generateSecureToken(length)}`;
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Generates each token a new record doesn't have (null or `""`) as it's built (`"initialize"`,
|
|
490
|
+
* after its given values) or created (`"create"`), whichever its `on` says.
|
|
491
|
+
*/
|
|
492
|
+
function generateTokens(definitions, holder, moment) {
|
|
493
|
+
for (const [name, definition] of definitions) {
|
|
494
|
+
const options = tokenOptionsOf(definition);
|
|
495
|
+
if (options === void 0 || (options.on ?? "initialize") !== moment) continue;
|
|
496
|
+
const value = holder.read(name);
|
|
497
|
+
if (value === null || value === "") holder.write(name, tokenFor(definition));
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* Defines each secure token's methods on a Model's prototype: `regenerateAuthToken()`, which
|
|
502
|
+
* saves a new token as `update` would, and its `OrThrow`.
|
|
503
|
+
*/
|
|
504
|
+
function defineSecureTokenMethods(prototype, definitions) {
|
|
505
|
+
for (const [name, definition] of definitions) {
|
|
506
|
+
if (definition.secureToken === void 0) continue;
|
|
507
|
+
const methods = {
|
|
508
|
+
[`regenerate${capitalized(name)}`]: function() {
|
|
509
|
+
return this.update({ [name]: tokenFor(definition) });
|
|
510
|
+
},
|
|
511
|
+
[`regenerate${capitalized(name)}OrThrow`]: function() {
|
|
512
|
+
return this.updateOrThrow({ [name]: tokenFor(definition) });
|
|
513
|
+
}
|
|
514
|
+
};
|
|
515
|
+
for (const [method, value] of Object.entries(methods)) Object.defineProperty(prototype, method, {
|
|
516
|
+
value,
|
|
517
|
+
configurable: true,
|
|
518
|
+
writable: true
|
|
519
|
+
});
|
|
520
|
+
}
|
|
237
521
|
}
|
|
238
522
|
// src/spec-keys.ts
|
|
239
523
|
const attributeTypes = Object.keys({
|
|
@@ -322,8 +606,75 @@ const rules = {
|
|
|
322
606
|
isGiven: isGivenUnless(false),
|
|
323
607
|
requires: "enum",
|
|
324
608
|
onRetype: "drop"
|
|
325
|
-
}
|
|
609
|
+
},
|
|
610
|
+
virtual: {
|
|
611
|
+
isWellFormed: (value) => typeof value === "boolean",
|
|
612
|
+
describedAs: "virtual",
|
|
613
|
+
isGiven: isGivenUnless(false),
|
|
614
|
+
conflictsWith: [
|
|
615
|
+
"column",
|
|
616
|
+
"generateId",
|
|
617
|
+
"storage",
|
|
618
|
+
"enum"
|
|
619
|
+
]
|
|
620
|
+
},
|
|
621
|
+
securePassword: {
|
|
622
|
+
isWellFormed: isSecurePasswordOption,
|
|
623
|
+
describedAs: "securePassword",
|
|
624
|
+
wellFormedAs: "use true, or { algorithm?, validations? }",
|
|
625
|
+
onlyFor: {
|
|
626
|
+
types: ["string"],
|
|
627
|
+
because: "a password is a string"
|
|
628
|
+
},
|
|
629
|
+
requires: "virtual",
|
|
630
|
+
conflictsWith: ["default"]
|
|
631
|
+
},
|
|
632
|
+
secureToken: secureTokenRule()
|
|
326
633
|
};
|
|
634
|
+
/** The rule for `secureToken`: a string's random token, generated for a new record (#355). */
|
|
635
|
+
function secureTokenRule() {
|
|
636
|
+
return {
|
|
637
|
+
isWellFormed: isSecureTokenOption,
|
|
638
|
+
describedAs: "secureToken",
|
|
639
|
+
wellFormedAs: "use true, or { length?, prefix?, on?: \"initialize\" | \"create\" }",
|
|
640
|
+
isGiven: isGivenUnless(false),
|
|
641
|
+
onlyFor: {
|
|
642
|
+
types: ["string"],
|
|
643
|
+
because: "a token is a string"
|
|
644
|
+
},
|
|
645
|
+
problemFor: secureTokenProblem,
|
|
646
|
+
conflictsWith: [
|
|
647
|
+
"default",
|
|
648
|
+
"generateId",
|
|
649
|
+
"virtual",
|
|
650
|
+
"enum"
|
|
651
|
+
],
|
|
652
|
+
onRetype: "drop"
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
/** `true`, or an object with only an algorithm (`hash` and `verify`) and a boolean `validations`. */
|
|
656
|
+
function isSecurePasswordOption(value) {
|
|
657
|
+
if (value === true) return true;
|
|
658
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
659
|
+
return Object.entries(value).every(([key, each]) => {
|
|
660
|
+
if (each === void 0) return true;
|
|
661
|
+
if (key === "validations") return typeof each === "boolean";
|
|
662
|
+
if (key === "resetToken") return isResetTokenOption(each);
|
|
663
|
+
return key === "algorithm" && isAlgorithm(each);
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
/** Whether a secure password's `resetToken` is well formed: a boolean, or `{ expiresIn }`. */
|
|
667
|
+
function isResetTokenOption(value) {
|
|
668
|
+
if (typeof value === "boolean") return true;
|
|
669
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
670
|
+
return Object.entries(value).every(([key, each]) => each === void 0 || key === "expiresIn" && isDuration(each));
|
|
671
|
+
}
|
|
672
|
+
/** Whether a value can hash and verify a password: an object with both functions. */
|
|
673
|
+
function isAlgorithm(value) {
|
|
674
|
+
if (typeof value !== "object" || value === null) return false;
|
|
675
|
+
const { hash, verify } = value;
|
|
676
|
+
return typeof hash === "function" && typeof verify === "function";
|
|
677
|
+
}
|
|
327
678
|
/** The rule for a decimal's precision or scale: a whole number of digits. */
|
|
328
679
|
function decimalDigits(describedAs) {
|
|
329
680
|
return {
|
|
@@ -477,433 +828,48 @@ function copiedKeys(spec) {
|
|
|
477
828
|
const copied = entries.filter(([key, rule]) => rule.copiedToDefinition !== false && givenValue(spec, key) !== void 0).map(([key]) => [key, spec[key]]);
|
|
478
829
|
return Object.fromEntries(copied);
|
|
479
830
|
}
|
|
480
|
-
// src/
|
|
481
|
-
/**
|
|
482
|
-
const
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
/**
|
|
520
|
-
function
|
|
521
|
-
return
|
|
522
|
-
}
|
|
523
|
-
/** Resolves an attribute's spec into its type, column and default. */
|
|
524
|
-
function define(name, spec) {
|
|
525
|
-
if (typeof spec === "string") return {
|
|
526
|
-
type: spec,
|
|
527
|
-
column: underscore(name)
|
|
528
|
-
};
|
|
529
|
-
if (isCustomType(spec)) return {
|
|
530
|
-
...resolvedType(spec),
|
|
531
|
-
column: underscore(name)
|
|
532
|
-
};
|
|
533
|
-
return {
|
|
534
|
-
...resolvedType(spec.type),
|
|
535
|
-
column: spec.column ?? underscore(name),
|
|
536
|
-
...copiedKeys(spec)
|
|
537
|
-
};
|
|
538
|
-
}
|
|
539
|
-
/** A spec's type as a definition holds it: a custom type as the type it's stored as, and itself. */
|
|
540
|
-
function resolvedType(type) {
|
|
541
|
-
return isCustomType(type) ? {
|
|
542
|
-
type: type.storedAs,
|
|
543
|
-
customType: type
|
|
544
|
-
} : { type };
|
|
545
|
-
}
|
|
546
|
-
/** Looks up a declared attribute; throws `UnknownAttribute` for any other name. */
|
|
547
|
-
function attributeOf(model, name) {
|
|
548
|
-
const attribute = model.attributeDefinitions.get(name);
|
|
549
|
-
if (attribute === void 0) throw new UnknownAttribute(`${model.name} has no attribute "${name}"`);
|
|
550
|
-
return attribute;
|
|
551
|
-
}
|
|
552
|
-
/** The attribute names mapped to `column` (usually one; none if the column isn't declared). */
|
|
553
|
-
function attributesForColumn(model, column) {
|
|
554
|
-
return [...model.attributeDefinitions].filter(([, definition]) => definition.column === column).map(([name]) => name);
|
|
555
|
-
}
|
|
556
|
-
/** `undefined` would silently store NULL, so writing it throws `TypeError` (use `null`). */
|
|
557
|
-
function requireDefined(model, name, value) {
|
|
558
|
-
if (value === void 0) throw new TypeError(`${model.name}: got undefined for "${name}"; use null to store NULL`);
|
|
559
|
-
}
|
|
560
|
-
/**
|
|
561
|
-
* The initial values of every attribute not in `given` that has one, made now: each one's
|
|
562
|
-
* `default`, or for a generated id, the Model's `generateId(name)`.
|
|
563
|
-
*/
|
|
564
|
-
function initialValues(model, given = {}) {
|
|
565
|
-
return [...model.attributeDefinitions].filter(([name, definition]) => !(name in given) && hasInitialValue(definition)).map(([name, definition]) => [name, definition.generateId ? model.generateId(name) : definition.default()]);
|
|
566
|
-
}
|
|
567
|
-
/** Whether an attribute gets a value when none is given: from its `default`, or `generateId`. */
|
|
568
|
-
function hasInitialValue(definition) {
|
|
569
|
-
return definition.generateId === true || definition.default !== void 0;
|
|
570
|
-
}
|
|
571
|
-
// src/attribute.ts
|
|
572
|
-
/** What `condition()` and `conditionCell()` give for a value that can't match anything. */
|
|
573
|
-
const noMatch = uncastable;
|
|
574
|
-
/**
|
|
575
|
-
* One attribute's value path, resolved once per Model class by `attributeFor` (#163). Which
|
|
576
|
-
* Model and attribute a refusal names, whether the attribute is filtered, and how its type is
|
|
577
|
-
* stored are known here, so a caller only says what the value is for.
|
|
578
|
-
*/
|
|
579
|
-
var Attribute = class {
|
|
580
|
-
#model;
|
|
581
|
-
name;
|
|
582
|
-
column;
|
|
583
|
-
#definition;
|
|
584
|
-
/** @internal Use `attributeFor`. */
|
|
585
|
-
constructor(model, name) {
|
|
586
|
-
this.#model = model;
|
|
587
|
-
this.name = name;
|
|
588
|
-
this.#definition = attributeOf(model, name);
|
|
589
|
-
this.column = this.#definition.column;
|
|
590
|
-
}
|
|
591
|
-
/** Whether it's a `string` attribute, which D1 compares as text, not by number. */
|
|
592
|
-
get isText() {
|
|
593
|
-
return this.#definition.type === "string";
|
|
594
|
-
}
|
|
595
|
-
/** Whether it's a `binary` attribute, whose cells are bytes, which JSON can't hold (#20). */
|
|
596
|
-
get isBinary() {
|
|
597
|
-
return this.#definition.type === "binary";
|
|
598
|
-
}
|
|
599
|
-
/** Whether it's a `json` attribute, whose stored text is JSON itself. */
|
|
600
|
-
get isJson() {
|
|
601
|
-
return this.#definition.type === "json";
|
|
602
|
-
}
|
|
603
|
-
/**
|
|
604
|
-
* An assigned value (a setter, `build`, `update`, `insert`, `permit`) as the attribute's type:
|
|
605
|
-
* only what's unambiguous for it (#81). `undefined` throws, as it would store NULL silently;
|
|
606
|
-
* what can't be cast throws `TypeError` naming the Model and attribute, showing the value
|
|
607
|
-
* unless the attribute is filtered (#83).
|
|
608
|
-
*/
|
|
609
|
-
cast(value) {
|
|
610
|
-
requireDefined(this.#model, this.name, value);
|
|
611
|
-
const cast = this.#convertOrRefuse(value, () => castValue(this.#definition, value));
|
|
612
|
-
if (cast === uncastable && this.#isValidatedEnum()) return value;
|
|
613
|
-
return this.#orRefuse(cast, value);
|
|
614
|
-
}
|
|
615
|
-
/** Whether it's an enum declared `validate: true`, which keeps an unknown value it's given. */
|
|
616
|
-
#isValidatedEnum() {
|
|
617
|
-
const { enum: values, validate = false } = this.#definition;
|
|
618
|
-
return values !== void 0 && validate !== false;
|
|
619
|
-
}
|
|
620
|
-
/**
|
|
621
|
-
* A key copied from another record or inherited from a condition: cast as a condition's, but
|
|
622
|
-
* one that can't be cast throws, naming the association it came through.
|
|
623
|
-
*/
|
|
624
|
-
key(value, association) {
|
|
625
|
-
requireDefined(this.#model, this.name, value);
|
|
626
|
-
return this.#orRefuse(castKey(this.#definition, value), value, association);
|
|
627
|
-
}
|
|
628
|
-
/**
|
|
629
|
-
* A condition's value (`where`, `find`, a preload) as the attribute's type, or `noMatch`: a
|
|
630
|
-
* number also matches a string attribute as its digits, and a value that can't be cast
|
|
631
|
-
* matches nothing, so a value from a URL is never an error.
|
|
632
|
-
*/
|
|
633
|
-
condition(value) {
|
|
634
|
-
return castCondition(this.#definition, value);
|
|
635
|
-
}
|
|
636
|
-
/** A condition's value in the form D1 stores, or `noMatch`. */
|
|
637
|
-
conditionCell(value) {
|
|
638
|
-
const cast = this.condition(value);
|
|
639
|
-
return cast === noMatch ? noMatch : this.write(cast);
|
|
640
|
-
}
|
|
641
|
-
/**
|
|
642
|
-
* An already cast value in the form D1 stores. A `json` value changed in place into one JSON
|
|
643
|
-
* can't write throws `TypeError` naming the attribute, as assigning it would (#146).
|
|
644
|
-
*/
|
|
645
|
-
write(value) {
|
|
646
|
-
let stored;
|
|
647
|
-
try {
|
|
648
|
-
stored = writeValue(this.#definition, value);
|
|
649
|
-
} catch (error) {
|
|
650
|
-
if (this.#definition.customType !== void 0) throw this.#refusal(value, void 0, error);
|
|
651
|
-
if (this.#definition.type !== "json") throw error;
|
|
652
|
-
throw this.#refusal(value);
|
|
653
|
-
}
|
|
654
|
-
if (stored === void 0) throw this.#refusal(value);
|
|
655
|
-
return stored;
|
|
656
|
-
}
|
|
657
|
-
/** An assigned value cast, then in the form D1 stores. */
|
|
658
|
-
store(value) {
|
|
659
|
-
return this.write(this.cast(value));
|
|
660
|
-
}
|
|
661
|
-
/**
|
|
662
|
-
* A cell D1 returned as the attribute's value. One that isn't (text in a Unix time column, or
|
|
663
|
-
* past the range of a `Date`; a json cell that isn't JSON) throws `TypeError` naming the
|
|
664
|
-
* attribute, with the cell hidden if it's filtered, not the parser's own error (#73, #146).
|
|
665
|
-
*/
|
|
666
|
-
read(cell) {
|
|
667
|
-
const value = this.#convertOrRefuse(cell, () => readValue(this.#definition, cell));
|
|
668
|
-
if (value === uncastable) throw this.#refusal(cell);
|
|
669
|
-
return value;
|
|
670
|
-
}
|
|
671
|
-
/** A copy of a value: written as D1 stores it, then read back. */
|
|
672
|
-
copy(value) {
|
|
673
|
-
return this.read(this.write(value));
|
|
674
|
-
}
|
|
675
|
-
/**
|
|
676
|
-
* Whether two values are the same as stored (dates by time, json and bytes by content). Each is
|
|
677
|
-
* cast as a condition's value first, so `isAttributeChanged`'s `from` and `to` compare as
|
|
678
|
-
* Rails' do, and one that can't be cast is the same as nothing (#20).
|
|
679
|
-
*/
|
|
680
|
-
isSame(a, b) {
|
|
681
|
-
const [x, y] = [this.#comparable(a), this.#comparable(b)];
|
|
682
|
-
if (x === noMatch || y === noMatch) return false;
|
|
683
|
-
return isSameCell(writeValue(this.#definition, x), writeValue(this.#definition, y));
|
|
684
|
-
}
|
|
685
|
-
/**
|
|
686
|
-
* A value to compare, cast as a condition's: `null` stays `null`, and a validated enum's
|
|
687
|
-
* unknown value, which a record may hold, stays as it is (#340).
|
|
688
|
-
*/
|
|
689
|
-
#comparable(value) {
|
|
690
|
-
if (value === null || value === void 0) return value ?? null;
|
|
691
|
-
const cast = this.condition(value);
|
|
692
|
-
return cast === noMatch && this.#isValidatedEnum() ? value : cast;
|
|
693
|
-
}
|
|
694
|
-
/** An assigned value, cast and written, bound hidden from `onQuery` if filtered (#83). */
|
|
695
|
-
bind(params, value) {
|
|
696
|
-
this.bindCells(params, this.store(value));
|
|
697
|
-
}
|
|
698
|
-
/**
|
|
699
|
-
* Binds cells (as D1 holds them) as the attribute's, each hidden from `onQuery` listeners when
|
|
700
|
-
* the attribute is filtered (#83); D1 still gets the real values. Filtering is asked at the
|
|
701
|
-
* time, since `filterAttributes` is a static a Model may set after this was resolved.
|
|
702
|
-
*/
|
|
703
|
-
bindCells(params, ...cells) {
|
|
704
|
-
const hidden = this.#isHidden();
|
|
705
|
-
for (const cell of cells) params.push(hidden ? new Filtered(cell) : cell);
|
|
706
|
-
}
|
|
707
|
-
#orRefuse(cast, value, association) {
|
|
708
|
-
if (cast === uncastable) throw this.#refusal(value, association);
|
|
709
|
-
return cast;
|
|
710
|
-
}
|
|
711
|
-
/**
|
|
712
|
-
* `convert`'s result. What a custom type's own function throws for `value` is refused as any
|
|
713
|
-
* value its type can't hold, with the type's error as the cause (#20).
|
|
714
|
-
*/
|
|
715
|
-
#convertOrRefuse(value, convert) {
|
|
716
|
-
try {
|
|
717
|
-
return convert();
|
|
718
|
-
} catch (error) {
|
|
719
|
-
if (this.#definition.customType === void 0) throw error;
|
|
720
|
-
throw this.#refusal(value, void 0, error);
|
|
721
|
-
}
|
|
722
|
-
}
|
|
723
|
-
/** Whether the attribute's values are hidden from listeners and errors (#83). */
|
|
724
|
-
#isHidden() {
|
|
725
|
-
return isFiltered(this.#model, this.name);
|
|
726
|
-
}
|
|
727
|
-
/**
|
|
728
|
-
* "Sample: "no" isn't a boolean for "enabled"", the value hidden for a filtered attribute. Also
|
|
729
|
-
* what a stored value that can't be read says: a Unix time that isn't one (#73), or a json
|
|
730
|
-
* cell that isn't JSON (#146). A custom type's own error is its cause, unless the attribute is
|
|
731
|
-
* filtered: the error may show the value (#20).
|
|
732
|
-
*/
|
|
733
|
-
#refusal(value, association, cause) {
|
|
734
|
-
const hidden = this.#isHidden();
|
|
735
|
-
const text = hidden ? FILTERED : shown(value);
|
|
736
|
-
const from = association === void 0 ? "" : `, the key of ${association}`;
|
|
737
|
-
return new TypeError(`${this.#model.name}: ${text} isn't ${this.#described()} for "${this.name}"${from}`, hidden || cause === void 0 ? void 0 : { cause });
|
|
738
|
-
}
|
|
739
|
-
/** What a value of the attribute is, as a refusal says it: `a boolean`, `one of "draft", "published"`. */
|
|
740
|
-
#described() {
|
|
741
|
-
const { type, enum: values, customType } = this.#definition;
|
|
742
|
-
if (values !== void 0) return `one of ${listedNames(values)}`;
|
|
743
|
-
if (customType !== void 0) return "a valid value";
|
|
744
|
-
return valueNames[type] ?? withArticle(type);
|
|
745
|
-
}
|
|
746
|
-
};
|
|
747
|
-
const resolved = /* @__PURE__ */ new WeakMap();
|
|
748
|
-
/**
|
|
749
|
-
* The resolved attribute of a Model, remembered per class (derived from the class, ADR-0003):
|
|
750
|
-
* `UnknownAttribute` for a name it doesn't have.
|
|
751
|
-
*/
|
|
752
|
-
function attributeFor(model, name) {
|
|
753
|
-
let attributes = resolved.get(model);
|
|
754
|
-
if (attributes === void 0) {
|
|
755
|
-
attributes = /* @__PURE__ */ new Map();
|
|
756
|
-
resolved.set(model, attributes);
|
|
757
|
-
}
|
|
758
|
-
let attribute = attributes.get(name);
|
|
759
|
-
if (attribute === void 0) {
|
|
760
|
-
attribute = new Attribute(model, name);
|
|
761
|
-
attributes.set(name, attribute);
|
|
762
|
-
}
|
|
763
|
-
return attribute;
|
|
764
|
-
}
|
|
765
|
-
/**
|
|
766
|
-
* The values a record built from a Relation inherits from its conditions, cast as keys are: a
|
|
767
|
-
* hasMany's foreign key names its association (`link`) when it can't be cast.
|
|
768
|
-
*/
|
|
769
|
-
function castInherited(model, inherited, link) {
|
|
770
|
-
return Object.fromEntries(Object.entries(inherited).map(([attribute, value]) => {
|
|
771
|
-
const association = attribute === link?.attribute ? link.association : void 0;
|
|
772
|
-
return [attribute, attributeFor(model, attribute).key(value, association)];
|
|
773
|
-
}));
|
|
774
|
-
}
|
|
775
|
-
/** A word with `a` or `an` before it, as a message reads it: `an integer`, `a string`. */
|
|
776
|
-
function withArticle(word) {
|
|
777
|
-
return `${/^[aeiou]/.test(word) ? "an" : "a"} ${word}`;
|
|
778
|
-
}
|
|
779
|
-
/** How much of a value an error shows: it came from outside, and errors are often logged. */
|
|
780
|
-
const SHOWN_LENGTH = 60;
|
|
781
|
-
/** What a value of an attribute type is called in a refusal, where `a`/`an` and its name isn't it. */
|
|
782
|
-
const valueNames = {
|
|
783
|
-
json: "a JSON value",
|
|
784
|
-
binary: "binary data"
|
|
785
|
-
};
|
|
786
|
-
/** A value as an error shows it: JSON where it has one, numbers as written, and at most 60 characters. */
|
|
787
|
-
function shown(value) {
|
|
788
|
-
const text = textOf(value);
|
|
789
|
-
return text.length > SHOWN_LENGTH ? `${text.slice(0, SHOWN_LENGTH)}…` : text;
|
|
790
|
-
}
|
|
791
|
-
function textOf(value) {
|
|
792
|
-
if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return `<${value.constructor.name} of ${value.byteLength} bytes>`;
|
|
793
|
-
if (value instanceof Blob) return `<${value.constructor.name} of ${value.size} bytes>`;
|
|
794
|
-
if (typeof value === "number" || isInvalidDate(value)) return String(value);
|
|
795
|
-
try {
|
|
796
|
-
return JSON.stringify(value) ?? String(value);
|
|
797
|
-
} catch {
|
|
798
|
-
return plainText(value);
|
|
799
|
-
}
|
|
800
|
-
}
|
|
801
|
-
/** `String(value)`, or its tag (`[object Array]`) when it has no string form: building the refusal mustn't throw. */
|
|
802
|
-
function plainText(value) {
|
|
803
|
-
try {
|
|
804
|
-
return String(value);
|
|
805
|
-
} catch {
|
|
806
|
-
return Object.prototype.toString.call(value);
|
|
807
|
-
}
|
|
808
|
-
}
|
|
809
|
-
// src/declarations.ts
|
|
810
|
-
/**
|
|
811
|
-
* Per-Model declarations (validations, callbacks, …), keyed by Model class. A subclass starts
|
|
812
|
-
* from a copy of its parent's list, so declaring on it never changes the parent.
|
|
813
|
-
*
|
|
814
|
-
* Module-level, but not request state (ADR-0003): declarations are made once, when a Model
|
|
815
|
-
* class is defined, and only read afterwards.
|
|
816
|
-
*/
|
|
817
|
-
const registry = /* @__PURE__ */ new WeakMap();
|
|
818
|
-
/** The declarations each class made itself, without its parent's, for reading class by class. */
|
|
819
|
-
const ownRegistry = /* @__PURE__ */ new WeakMap();
|
|
820
|
-
/** Models that have been used; their declarations can no longer change. */
|
|
821
|
-
const sealed = /* @__PURE__ */ new WeakSet();
|
|
822
|
-
/**
|
|
823
|
-
* Called on a Model's first use. From then on, declaring on it throws: declarations belong in
|
|
824
|
-
* the class's `static {}` block, never in request code, where they'd leak into every request.
|
|
825
|
-
*/
|
|
826
|
-
function seal(model) {
|
|
827
|
-
sealed.add(model);
|
|
828
|
-
}
|
|
829
|
-
/** Whether a Model has been used, so its declarations, and its ancestors', can no longer change. */
|
|
830
|
-
function isSealed(model) {
|
|
831
|
-
return sealed.has(model);
|
|
832
|
-
}
|
|
833
|
-
/** The declarations of `kind` for `model`: its own, or else its nearest ancestor's. */
|
|
834
|
-
function declared(model, kind) {
|
|
835
|
-
for (const current of ancestors(model)) {
|
|
836
|
-
const list = registry.get(current)?.get(kind);
|
|
837
|
-
if (list !== void 0) return list;
|
|
838
|
-
}
|
|
839
|
-
return [];
|
|
840
|
-
}
|
|
841
|
-
/** The declarations of `kind` that `model` and each class it extends made themselves, nearest first. */
|
|
842
|
-
function declaredByClass(model, kind) {
|
|
843
|
-
return ancestors(model).flatMap((from) => {
|
|
844
|
-
const values = ownRegistry.get(from)?.get(kind);
|
|
845
|
-
return values === void 0 ? [] : [{
|
|
846
|
-
from,
|
|
847
|
-
values
|
|
848
|
-
}];
|
|
849
|
-
});
|
|
850
|
-
}
|
|
851
|
-
/** Adds a declaration of `kind` to `model`, copying its inherited list first. */
|
|
852
|
-
function declare(model, kind, entry) {
|
|
853
|
-
if (sealed.has(model)) {
|
|
854
|
-
const { name } = model;
|
|
855
|
-
throw new InvalidModel(`${name} has already been used; declare validations, callbacks and messages in its static {} block`);
|
|
856
|
-
}
|
|
857
|
-
listsOf(registry, model).set(kind, [...declared(model, kind), entry]);
|
|
858
|
-
const own = listsOf(ownRegistry, model);
|
|
859
|
-
own.set(kind, [...own.get(kind) ?? [], entry]);
|
|
860
|
-
}
|
|
861
|
-
/** `model`'s lists in a registry, by kind, made empty the first time. */
|
|
862
|
-
function listsOf(lists, model) {
|
|
863
|
-
const found = lists.get(model) ?? /* @__PURE__ */ new Map();
|
|
864
|
-
lists.set(model, found);
|
|
865
|
-
return found;
|
|
866
|
-
}
|
|
867
|
-
// src/error-messages.ts
|
|
868
|
-
/** @internal Rails' English messages, used where no class has its own (listed in the guide). */
|
|
869
|
-
const builtInMessages = {
|
|
870
|
-
blank: "can't be blank",
|
|
871
|
-
present: "must be blank",
|
|
872
|
-
invalid: "is invalid",
|
|
873
|
-
required: "must exist",
|
|
874
|
-
inclusion: "is not included in the list",
|
|
875
|
-
exclusion: "is reserved",
|
|
876
|
-
accepted: "must be accepted",
|
|
877
|
-
taken: "has already been taken",
|
|
878
|
-
tooShort: {
|
|
879
|
-
one: "is too short (minimum is 1 character)",
|
|
880
|
-
other: "is too short (minimum is %{count} characters)"
|
|
881
|
-
},
|
|
882
|
-
tooLong: {
|
|
883
|
-
one: "is too long (maximum is 1 character)",
|
|
884
|
-
other: "is too long (maximum is %{count} characters)"
|
|
885
|
-
},
|
|
886
|
-
wrongLength: {
|
|
887
|
-
one: "is the wrong length (should be 1 character)",
|
|
888
|
-
other: "is the wrong length (should be %{count} characters)"
|
|
889
|
-
},
|
|
890
|
-
notANumber: "is not a number",
|
|
891
|
-
notAnInteger: "must be an integer",
|
|
892
|
-
greaterThan: "must be greater than %{count}",
|
|
893
|
-
greaterThanOrEqualTo: "must be greater than or equal to %{count}",
|
|
894
|
-
lessThan: "must be less than %{count}",
|
|
895
|
-
lessThanOrEqualTo: "must be less than or equal to %{count}",
|
|
896
|
-
equalTo: "must be equal to %{count}",
|
|
897
|
-
otherThan: "must be other than %{count}",
|
|
898
|
-
restrictDependentDestroy: {
|
|
899
|
-
hasOne: "Cannot delete record because a dependent %{record} exists",
|
|
900
|
-
hasMany: "Cannot delete record because dependent %{record} exist"
|
|
901
|
-
}
|
|
902
|
-
};
|
|
903
|
-
const plurals = new Intl.PluralRules("en");
|
|
904
|
-
/** `object[key]` when it's the object's own, so `toString` is never a message. */
|
|
905
|
-
function ownValue(object, key) {
|
|
906
|
-
return object !== void 0 && Object.hasOwn(object, key) ? object[key] : void 0;
|
|
831
|
+
// src/error-messages.ts
|
|
832
|
+
/** @internal The built-in English messages, where no class has its own (listed in the guide). */
|
|
833
|
+
const builtInMessages = {
|
|
834
|
+
blank: "can't be blank",
|
|
835
|
+
present: "must be blank",
|
|
836
|
+
invalid: "is invalid",
|
|
837
|
+
required: "must exist",
|
|
838
|
+
inclusion: "is not included in the list",
|
|
839
|
+
exclusion: "is reserved",
|
|
840
|
+
accepted: "must be accepted",
|
|
841
|
+
confirmation: "doesn't match %{attribute}",
|
|
842
|
+
taken: "has already been taken",
|
|
843
|
+
tooShort: {
|
|
844
|
+
one: "is too short (minimum is 1 character)",
|
|
845
|
+
other: "is too short (minimum is %{count} characters)"
|
|
846
|
+
},
|
|
847
|
+
tooLong: {
|
|
848
|
+
one: "is too long (maximum is 1 character)",
|
|
849
|
+
other: "is too long (maximum is %{count} characters)"
|
|
850
|
+
},
|
|
851
|
+
wrongLength: {
|
|
852
|
+
one: "is the wrong length (should be 1 character)",
|
|
853
|
+
other: "is the wrong length (should be %{count} characters)"
|
|
854
|
+
},
|
|
855
|
+
notANumber: "is not a number",
|
|
856
|
+
notAnInteger: "must be an integer",
|
|
857
|
+
greaterThan: "must be greater than %{count}",
|
|
858
|
+
greaterThanOrEqualTo: "must be greater than or equal to %{count}",
|
|
859
|
+
lessThan: "must be less than %{count}",
|
|
860
|
+
lessThanOrEqualTo: "must be less than or equal to %{count}",
|
|
861
|
+
equalTo: "must be equal to %{count}",
|
|
862
|
+
otherThan: "must be other than %{count}",
|
|
863
|
+
passwordTooLong: "is too long",
|
|
864
|
+
restrictDependentDestroy: {
|
|
865
|
+
hasOne: "Cannot delete record because a dependent %{record} exists",
|
|
866
|
+
hasMany: "Cannot delete record because dependent %{record} exist"
|
|
867
|
+
}
|
|
868
|
+
};
|
|
869
|
+
const plurals = new Intl.PluralRules("en");
|
|
870
|
+
/** `object[key]` when it's the object's own, so `toString` is never a message. */
|
|
871
|
+
function ownValue(object, key) {
|
|
872
|
+
return object !== void 0 && Object.hasOwn(object, key) ? object[key] : void 0;
|
|
907
873
|
}
|
|
908
874
|
/** One class's `errorMessages` calls as one: a later call's message wins, type by type. */
|
|
909
875
|
function mergedCalls(calls) {
|
|
@@ -928,7 +894,7 @@ function catalogOf(model) {
|
|
|
928
894
|
if (isSealed(model)) catalogs.set(model, catalog);
|
|
929
895
|
return catalog;
|
|
930
896
|
}
|
|
931
|
-
/** The message for a type: for the attribute, then the class's own, nearest class first
|
|
897
|
+
/** The message for a type: for the attribute, then the class's own, nearest class first. */
|
|
932
898
|
function templateFor(model, attribute, type) {
|
|
933
899
|
if (type === "attributes") return void 0;
|
|
934
900
|
for (const messages of catalogOf(model).messages) {
|
|
@@ -952,7 +918,7 @@ function humanAttributeName(model, attribute) {
|
|
|
952
918
|
return catalogOf(model).names.get(attribute) ?? inWords(attribute);
|
|
953
919
|
}
|
|
954
920
|
/** An attribute's value as `%{value}` shows it. */
|
|
955
|
-
function shownValue(source, attribute) {
|
|
921
|
+
function shownValue$1(source, attribute) {
|
|
956
922
|
if (attribute === "base") return "";
|
|
957
923
|
const value = source.read(attribute);
|
|
958
924
|
if (value === null || value === void 0) return "";
|
|
@@ -967,9 +933,9 @@ function messageOf(source, entry) {
|
|
|
967
933
|
const text = messageText(templateFor(model, entry.attribute, entry.type), entry);
|
|
968
934
|
if (text === void 0) throw missingMessage(model, entry);
|
|
969
935
|
return text.replace(/%\{(\w+)\}/g, (placeholder, name) => {
|
|
970
|
-
if (name === "attribute") return humanAttributeName(model, entry.attribute);
|
|
936
|
+
if (name === "attribute") return String(ownValue(entry.values, name) ?? humanAttributeName(model, entry.attribute));
|
|
971
937
|
if (name === "model") return inWords(model.modelName);
|
|
972
|
-
if (name === "value") return shownValue(source, entry.attribute);
|
|
938
|
+
if (name === "value") return shownValue$1(source, entry.attribute);
|
|
973
939
|
return String(ownValue(entry.values, name) ?? placeholder);
|
|
974
940
|
});
|
|
975
941
|
}
|
|
@@ -1251,6 +1217,91 @@ var PendingAutosaves = class {
|
|
|
1251
1217
|
this.#belongsTo.clear();
|
|
1252
1218
|
}
|
|
1253
1219
|
};
|
|
1220
|
+
// src/metadata.ts
|
|
1221
|
+
/** A spec written out: a type alone (a name, or a custom type) as `{ type }`. */
|
|
1222
|
+
function specObjectOf(spec) {
|
|
1223
|
+
return typeof spec === "string" || isCustomType(spec) ? { type: spec } : spec;
|
|
1224
|
+
}
|
|
1225
|
+
/** Resolves an attribute's spec into its type, column and default. */
|
|
1226
|
+
function define(name, spec) {
|
|
1227
|
+
if (typeof spec === "string") return {
|
|
1228
|
+
type: spec,
|
|
1229
|
+
column: underscore(name)
|
|
1230
|
+
};
|
|
1231
|
+
if (isCustomType(spec)) return {
|
|
1232
|
+
...resolvedType(spec),
|
|
1233
|
+
column: underscore(name)
|
|
1234
|
+
};
|
|
1235
|
+
if (spec.virtual === true) return defineVirtual(name, spec);
|
|
1236
|
+
return {
|
|
1237
|
+
...resolvedType(spec.type),
|
|
1238
|
+
column: spec.column ?? underscore(name),
|
|
1239
|
+
...copiedKeys(spec)
|
|
1240
|
+
};
|
|
1241
|
+
}
|
|
1242
|
+
/**
|
|
1243
|
+
* A virtual attribute's definition (#356): no column (`""`, unless one was given, which a Model's
|
|
1244
|
+
* check refuses), and non-null only with a default.
|
|
1245
|
+
*/
|
|
1246
|
+
function defineVirtual(name, spec) {
|
|
1247
|
+
const problem = virtualNullProblem(name, spec);
|
|
1248
|
+
if (problem !== void 0) throw new InvalidModel(problem);
|
|
1249
|
+
return {
|
|
1250
|
+
...resolvedType(spec.type),
|
|
1251
|
+
column: spec.column ?? "",
|
|
1252
|
+
...copiedKeys(spec)
|
|
1253
|
+
};
|
|
1254
|
+
}
|
|
1255
|
+
/** A virtual attribute declared non-null with no default, which would read as null (#356). */
|
|
1256
|
+
function virtualNullProblem(where, spec) {
|
|
1257
|
+
return spec.null === false && spec.default === void 0 ? `${where} is virtual and null: false, so it needs a default` : void 0;
|
|
1258
|
+
}
|
|
1259
|
+
/** A spec's type as a definition holds it: a custom type as the type it's stored as, and itself. */
|
|
1260
|
+
function resolvedType(type) {
|
|
1261
|
+
return isCustomType(type) ? {
|
|
1262
|
+
type: type.storedAs,
|
|
1263
|
+
customType: type
|
|
1264
|
+
} : { type };
|
|
1265
|
+
}
|
|
1266
|
+
/** Looks up a declared attribute, or the one an alias names; throws `UnknownAttribute` for any other name. */
|
|
1267
|
+
function attributeOf(model, name) {
|
|
1268
|
+
const attribute = model.attributeDefinitions.get(attributeName(model, name));
|
|
1269
|
+
if (attribute === void 0) throw new UnknownAttribute(`${model.name} has no attribute "${name}"`);
|
|
1270
|
+
return attribute;
|
|
1271
|
+
}
|
|
1272
|
+
/**
|
|
1273
|
+
* Looks up an attribute a query reads or writes as a column: `UnknownAttribute` for a name the
|
|
1274
|
+
* Model doesn't have, or a virtual attribute, which has none (#356).
|
|
1275
|
+
*/
|
|
1276
|
+
function columnOf(model, name) {
|
|
1277
|
+
const attribute = attributeOf(model, name);
|
|
1278
|
+
if (attribute.virtual === true) throw new UnknownAttribute(`${model.name}.${name} is a virtual attribute, which has no column to query`);
|
|
1279
|
+
return attribute;
|
|
1280
|
+
}
|
|
1281
|
+
/** The attribute names mapped to `column` (usually one; none if the column isn't declared). */
|
|
1282
|
+
function attributesForColumn(model, column) {
|
|
1283
|
+
return [...model.attributeDefinitions].filter(([, definition]) => definition.column === column).map(([name]) => name);
|
|
1284
|
+
}
|
|
1285
|
+
/** `undefined` would silently store NULL, so writing it throws `TypeError` (use `null`). */
|
|
1286
|
+
function requireDefined(model, name, value) {
|
|
1287
|
+
if (value === void 0) throw new TypeError(`${model.name}: got undefined for "${name}"; use null to store NULL`);
|
|
1288
|
+
}
|
|
1289
|
+
/**
|
|
1290
|
+
* The initial values of every attribute not in `given` that has one, made now: each one's
|
|
1291
|
+
* `default`, for a generated id, the Model's `generateId(name)`, and for a secure token generated
|
|
1292
|
+
* as a record is built, a new token (#355).
|
|
1293
|
+
*/
|
|
1294
|
+
function initialValues(model, given = {}) {
|
|
1295
|
+
return [...model.attributeDefinitions].filter(([name, definition]) => !(name in given) && hasInitialValue(definition)).map(([name, definition]) => [name, initialValue(model, name, definition)]);
|
|
1296
|
+
}
|
|
1297
|
+
function initialValue(model, name, definition) {
|
|
1298
|
+
if (definition.generateId) return model.generateId(name);
|
|
1299
|
+
return isTokenOnInitialize(definition) ? tokenFor(definition) : definition.default();
|
|
1300
|
+
}
|
|
1301
|
+
/** Whether an attribute gets a value when none is given: from its `default`, `generateId`, or a token. */
|
|
1302
|
+
function hasInitialValue(definition) {
|
|
1303
|
+
return definition.generateId === true || definition.default !== void 0 || isTokenOnInitialize(definition);
|
|
1304
|
+
}
|
|
1254
1305
|
// src/record-state.ts
|
|
1255
1306
|
/** @internal The hidden slot where a Record keeps its `RecordState`. */
|
|
1256
1307
|
const state = Symbol("state");
|
|
@@ -1286,7 +1337,9 @@ var RecordState = class {
|
|
|
1286
1337
|
autosaves = new PendingAutosaves();
|
|
1287
1338
|
/** Destroyed when its owner is saved through an `autosave: true` association (#37). */
|
|
1288
1339
|
isMarkedForDestruction = false;
|
|
1289
|
-
/** Whether
|
|
1340
|
+
/** Whether the save being prepared sends a locked UPDATE, which sets the row's version (#357). */
|
|
1341
|
+
isSavingVersion = false;
|
|
1342
|
+
/** Whether its last save created it (#351). */
|
|
1290
1343
|
isPreviouslyNew = false;
|
|
1291
1344
|
/** The contexts it's being validated in, while it is (#51). */
|
|
1292
1345
|
validationContexts = [];
|
|
@@ -1347,19 +1400,34 @@ var RecordState = class {
|
|
|
1347
1400
|
const { name, primaryKey } = this.#model;
|
|
1348
1401
|
if (this.#lifecycle === "persisted" && !this.#isInSnapshot(primaryKey)) throw new MissingAttribute(`${name} record has no primary key loaded (it came from select(...).distinct()); it can't ${action}`);
|
|
1349
1402
|
}
|
|
1403
|
+
/** Whether `name` is one of the Model's attributes and loaded: not left out of `select(...)`. */
|
|
1404
|
+
hasAttribute(given) {
|
|
1405
|
+
const name = attributeName(this.#model, given);
|
|
1406
|
+
return this.#model.attributeDefinitions.has(name) && Object.hasOwn(this.#values, name);
|
|
1407
|
+
}
|
|
1350
1408
|
/** An attribute's value; `MissingAttribute` if it wasn't loaded (left out of `select`). */
|
|
1351
|
-
read(
|
|
1409
|
+
read(given) {
|
|
1410
|
+
const name = attributeName(this.#model, given);
|
|
1352
1411
|
this.#requireAttribute(name);
|
|
1353
1412
|
if (!Object.hasOwn(this.#values, name)) throw new MissingAttribute(`${this.#model.name} record has no "${name}" loaded; it was left out of select(...)`);
|
|
1354
1413
|
return this.#values[name];
|
|
1355
1414
|
}
|
|
1356
1415
|
/**
|
|
1357
1416
|
* Assigns one attribute. `undefined` throws `TypeError`, because it would silently store NULL
|
|
1358
|
-
* (use `null` for that); a destroyed record is read-only.
|
|
1417
|
+
* (use `null` for that); a destroyed record is read-only. A secure password's assignment
|
|
1418
|
+
* changes its digest only to clear it.
|
|
1359
1419
|
*/
|
|
1360
|
-
write(
|
|
1420
|
+
write(given, value) {
|
|
1361
1421
|
this.#requireNotDestroyed("be changed");
|
|
1362
|
-
this.#
|
|
1422
|
+
const name = attributeName(this.#model, given);
|
|
1423
|
+
const assigned = this.#attribute(name).assigned(value);
|
|
1424
|
+
const digest = digestOf(this.#model.attributeDefinitions, name);
|
|
1425
|
+
if (digest !== void 0 && assigned === "") return;
|
|
1426
|
+
if (digest !== void 0 && assigned === null) {
|
|
1427
|
+
this.#store(digest, null);
|
|
1428
|
+
if (this.#lifecycle === "persisted") this.#snapshot.set(name, null);
|
|
1429
|
+
}
|
|
1430
|
+
this.#store(name, assigned);
|
|
1363
1431
|
}
|
|
1364
1432
|
/**
|
|
1365
1433
|
* Writes a key copied from another record through `association`, cast as a condition's value
|
|
@@ -1382,13 +1450,15 @@ var RecordState = class {
|
|
|
1382
1450
|
}
|
|
1383
1451
|
}
|
|
1384
1452
|
/** A new record: every attribute reads as null until assigned, and initial values are made now. */
|
|
1385
|
-
build(attributes) {
|
|
1453
|
+
build(attributes, kept = {}) {
|
|
1386
1454
|
for (const name of this.#model.attributeDefinitions.keys()) this.#values[name] = null;
|
|
1387
1455
|
for (const [name, value] of initialValues(this.#model)) {
|
|
1388
1456
|
this.write(name, value);
|
|
1389
1457
|
this.#initialValues.set(name, this.#storedForm(name));
|
|
1390
1458
|
}
|
|
1459
|
+
for (const [name, value] of Object.entries(kept)) this.#store(name, value);
|
|
1391
1460
|
this.assign(attributes);
|
|
1461
|
+
generateTokens(this.#model.attributeDefinitions, this, "initialize");
|
|
1392
1462
|
}
|
|
1393
1463
|
/**
|
|
1394
1464
|
* Points this record at `value` through `association`'s foreign key, keeping it loaded for its
|
|
@@ -1409,238 +1479,937 @@ var RecordState = class {
|
|
|
1409
1479
|
this.associations.clearAll();
|
|
1410
1480
|
this.autosaves.clearAll();
|
|
1411
1481
|
}
|
|
1412
|
-
/**
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1482
|
+
/**
|
|
1483
|
+
* Loads a D1 row; the record becomes persisted and clean. Its virtual attributes, which no row
|
|
1484
|
+
* holds, start at their defaults, on a load or `reload` (#356); an insert's re-read
|
|
1485
|
+
* row keeps the values it was saved with (`keepVirtual`).
|
|
1486
|
+
*/
|
|
1487
|
+
loadRow(row, { keepVirtual = false } = {}) {
|
|
1488
|
+
let loadedCount = 0;
|
|
1489
|
+
for (const [name, definition] of this.#model.attributeDefinitions) {
|
|
1490
|
+
if (definition.virtual === true) {
|
|
1491
|
+
if (!keepVirtual) this.#values[name] = this.#virtualDefault(name, definition);
|
|
1492
|
+
continue;
|
|
1493
|
+
}
|
|
1494
|
+
const { column } = definition;
|
|
1495
|
+
if (!(column in row)) continue;
|
|
1496
|
+
this.#values[name] = this.#attribute(name).read(row[column]);
|
|
1497
|
+
loadedCount++;
|
|
1498
|
+
}
|
|
1499
|
+
this.#markSaved(row, loadedCount);
|
|
1500
|
+
}
|
|
1501
|
+
/** A virtual attribute's value on a loaded record: its default, cast and normalized, or null (#356). */
|
|
1502
|
+
#virtualDefault(name, definition) {
|
|
1503
|
+
return definition.default === void 0 ? null : this.#attribute(name).assigned(definition.default());
|
|
1504
|
+
}
|
|
1505
|
+
/** The loaded attributes as a plain object (the record's own values, not copies). */
|
|
1506
|
+
attributes() {
|
|
1507
|
+
return { ...this.#values };
|
|
1508
|
+
}
|
|
1509
|
+
/**
|
|
1510
|
+
* A new record's assigned attributes that differ from their initial values (a declared default
|
|
1511
|
+
* or generated id, else null), so its changes run from its defaults (#41); or a persisted
|
|
1512
|
+
* one's that differ from the Snapshot. Both compare stored forms.
|
|
1513
|
+
*/
|
|
1514
|
+
changedNames() {
|
|
1515
|
+
if (this.#lifecycle === "new") return [...this.#assigned].filter((name) => !isSameCell(this.#storedForm(name), this.#initialOf(name)));
|
|
1516
|
+
return Object.keys(this.#values).filter((name) => !this.#isInSnapshot(name) || !isSameCell(this.#snapshotOf(name), this.#storedForm(name)));
|
|
1517
|
+
}
|
|
1518
|
+
/** `{ attribute: [before, after] }`; both are copies, never the record's own objects. */
|
|
1519
|
+
changes() {
|
|
1520
|
+
const changes = {};
|
|
1521
|
+
for (const name of this.changedNames()) changes[name] = [this.#valueBefore(name), this.#copyOf(name)];
|
|
1522
|
+
return changes;
|
|
1523
|
+
}
|
|
1524
|
+
/** `changes()`, with `undefined` before an attribute the record never loaded (a partial record's). */
|
|
1525
|
+
changesSinceLoad() {
|
|
1526
|
+
return Object.fromEntries(Object.entries(this.changes()).map(([name, [before, after]]) => [name, [this.#isInSnapshot(name) ? before : void 0, after]]));
|
|
1527
|
+
}
|
|
1528
|
+
/** The changes the last successful save wrote (copies). */
|
|
1529
|
+
savedChanges() {
|
|
1530
|
+
return { ...this.#savedChanges };
|
|
1531
|
+
}
|
|
1532
|
+
/**
|
|
1533
|
+
* An attribute's value as last loaded or saved (a copy). A new record's is its initial
|
|
1534
|
+
* value (a default or generated id), or null, which `attributeWas` returns.
|
|
1535
|
+
*/
|
|
1536
|
+
valueInDatabase(given) {
|
|
1537
|
+
const name = attributeName(this.#model, given);
|
|
1538
|
+
this.read(name);
|
|
1539
|
+
return this.#valueBefore(name);
|
|
1540
|
+
}
|
|
1541
|
+
/**
|
|
1542
|
+
* Whether the attribute has an unsaved change, optionally `from` and `to` given values
|
|
1543
|
+
* (compared as stored, so dates by time and json by content).
|
|
1544
|
+
*/
|
|
1545
|
+
isAttributeChanged(given, options = {}) {
|
|
1546
|
+
const name = attributeName(this.#model, given);
|
|
1547
|
+
this.read(name);
|
|
1548
|
+
if (!this.changedNames().includes(name)) return false;
|
|
1549
|
+
return this.#isMatching(name, this.valueInDatabase(name), this.#values[name], options);
|
|
1550
|
+
}
|
|
1551
|
+
/** The last save's change to the attribute, or an alias's, `[before, after]`, if it changed it. */
|
|
1552
|
+
savedChangeOf(given) {
|
|
1553
|
+
const name = attributeName(this.#model, given);
|
|
1554
|
+
this.read(name);
|
|
1555
|
+
return this.#savedChanges[name];
|
|
1556
|
+
}
|
|
1557
|
+
/** Whether the last save changed the attribute, optionally `from` and `to` given values. */
|
|
1558
|
+
hasSavedChangeTo(given, options = {}) {
|
|
1559
|
+
const name = attributeName(this.#model, given);
|
|
1560
|
+
this.read(name);
|
|
1561
|
+
const change = this.#savedChanges[name];
|
|
1562
|
+
return change !== void 0 && this.#isMatching(name, change[0], change[1], options);
|
|
1563
|
+
}
|
|
1564
|
+
/** Puts unsaved changes back: to the Snapshot, or to a new record's initial values (or null). */
|
|
1565
|
+
restore(given = this.changedNames()) {
|
|
1566
|
+
this.#requireNotDestroyed("be changed");
|
|
1567
|
+
for (const name of given.map((each) => attributeName(this.#model, each))) {
|
|
1568
|
+
const attribute = this.#attribute(name);
|
|
1569
|
+
if (this.#lifecycle !== "new") {
|
|
1570
|
+
if (this.#isInSnapshot(name)) this.#values[name] = this.#snapshotValue(name);
|
|
1571
|
+
} else if (this.#initialValues.has(name)) this.#values[name] = attribute.read(this.#initialValues.get(name));
|
|
1572
|
+
else {
|
|
1573
|
+
this.#values[name] = null;
|
|
1574
|
+
this.#assigned.delete(name);
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
#isMatching(name, before, after, options) {
|
|
1579
|
+
const isSame = (a, b) => this.#attribute(name).isSame(a, b);
|
|
1580
|
+
return (!("from" in options) || isSame(options.from, before)) && (!("to" in options) || isSame(options.to, after));
|
|
1581
|
+
}
|
|
1582
|
+
/** The attributes an insert writes: the assigned ones, so column defaults apply to the rest. */
|
|
1583
|
+
insertAssignments() {
|
|
1584
|
+
return this.#assignmentsOf([...this.#assigned]);
|
|
1585
|
+
}
|
|
1586
|
+
/** The attributes an update writes: the changed ones. */
|
|
1587
|
+
updateAssignments() {
|
|
1588
|
+
return this.#assignmentsOf(this.changedNames());
|
|
1589
|
+
}
|
|
1590
|
+
/** The primary key as stored in D1: the row's key before any unsaved change to it. */
|
|
1591
|
+
get storedKey() {
|
|
1592
|
+
return this.#snapshotOf(this.#model.primaryKey);
|
|
1593
|
+
}
|
|
1594
|
+
/** The stored primary key as a JavaScript value, e.g. to find the row again. */
|
|
1595
|
+
get storedKeyValue() {
|
|
1596
|
+
return this.#attribute(this.#model.primaryKey).read(this.storedKey);
|
|
1597
|
+
}
|
|
1598
|
+
/**
|
|
1599
|
+
* After an insert: load what D1 stored. `savedChanges` is the changes the insert wrote, and
|
|
1600
|
+
* what the write or the database filled in (a generated key, timestamps, a column default),
|
|
1601
|
+
* each from its value before: a declared default the record kept isn't one (#41).
|
|
1602
|
+
*/
|
|
1603
|
+
commitInsert(row) {
|
|
1604
|
+
const written = new Set(this.changedNames());
|
|
1605
|
+
const before = new Map(Object.keys(this.#values).map((name) => [name, {
|
|
1606
|
+
stored: this.#storedForm(name),
|
|
1607
|
+
value: this.#valueBefore(name)
|
|
1608
|
+
}]));
|
|
1609
|
+
if (row === void 0) {
|
|
1610
|
+
this.#settle();
|
|
1611
|
+
this.#markSaved();
|
|
1612
|
+
} else this.loadRow(row, { keepVirtual: true });
|
|
1613
|
+
this.#savedChanges = Object.fromEntries([...before].filter(([name, { stored }]) => written.has(name) || !isSameCell(this.#storedForm(name), stored)).map(([name, { value }]) => [name, [value, this.#copyOf(name)]]));
|
|
1614
|
+
this.isPreviouslyNew = true;
|
|
1615
|
+
}
|
|
1616
|
+
/**
|
|
1617
|
+
* After an update: apply values the write added (timestamps), then record the save. Every
|
|
1618
|
+
* attribute holds what was stored (a `unixSeconds` Date has no milliseconds, a `json` NaN is
|
|
1619
|
+
* null), as an insert's re-read row gives (#73, #163), including one assigned a value equal
|
|
1620
|
+
* as stored, which wasn't a change.
|
|
1621
|
+
*/
|
|
1622
|
+
commitUpdate(added) {
|
|
1623
|
+
for (const [name, value] of added) this.#values[name] = value;
|
|
1624
|
+
this.#settle();
|
|
1625
|
+
this.#savedChanges = this.changes();
|
|
1626
|
+
this.#markSaved();
|
|
1627
|
+
this.isPreviouslyNew = false;
|
|
1628
|
+
}
|
|
1629
|
+
/**
|
|
1630
|
+
* After a write straight to the row (`updateColumns`, #351): these attributes hold what was
|
|
1631
|
+
* stored, or what `row` returned for them, and have no unsaved change. The rest, and
|
|
1632
|
+
* `savedChanges`, are as they were.
|
|
1633
|
+
*/
|
|
1634
|
+
commitColumns(given, row = {}) {
|
|
1635
|
+
for (const name of given.map((each) => attributeName(this.#model, each))) {
|
|
1636
|
+
const { column } = this.#definition(name);
|
|
1637
|
+
const attribute = this.#attribute(name);
|
|
1638
|
+
this.#values[name] = column in row ? attribute.read(row[column]) : this.#copyOf(name);
|
|
1639
|
+
this.#snapshot.set(name, this.#storedForm(name));
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
/**
|
|
1643
|
+
* After a touch (#50): as `commitColumns`, and `savedChanges` holds only the touched
|
|
1644
|
+
* attributes' changes. The record's other changes stay unsaved.
|
|
1645
|
+
*/
|
|
1646
|
+
commitTouch(given) {
|
|
1647
|
+
const names = given.map((each) => attributeName(this.#model, each));
|
|
1648
|
+
const changes = this.changes();
|
|
1649
|
+
this.commitColumns(names);
|
|
1650
|
+
this.#savedChanges = Object.fromEntries(names.filter((name) => Object.hasOwn(changes, name)).map((name) => [name, changes[name]]));
|
|
1651
|
+
}
|
|
1652
|
+
/** A save with nothing to write: nothing changes but `savedChanges`. */
|
|
1653
|
+
commitClean() {
|
|
1654
|
+
this.#savedChanges = {};
|
|
1655
|
+
this.isPreviouslyNew = false;
|
|
1656
|
+
}
|
|
1657
|
+
markDestroyed() {
|
|
1658
|
+
this.#lifecycle = "destroyed";
|
|
1659
|
+
this.isPreviouslyNew = false;
|
|
1660
|
+
}
|
|
1661
|
+
/** A destroyed record is a read-only snapshot. (A keyless record may change in memory.) */
|
|
1662
|
+
#requireNotDestroyed(action) {
|
|
1663
|
+
if (this.#lifecycle === "destroyed") throw new RecordDestroyed(`${this.#model.name} record was destroyed; it can't ${action}`);
|
|
1664
|
+
}
|
|
1665
|
+
/** An unknown name is UnknownAttribute, even one every object inherits (`constructor`, #84). */
|
|
1666
|
+
#requireAttribute(name) {
|
|
1667
|
+
this.#definition(name);
|
|
1668
|
+
}
|
|
1669
|
+
#definition(name) {
|
|
1670
|
+
return attributeOf(this.#model, name);
|
|
1671
|
+
}
|
|
1672
|
+
/** The resolved attribute, so a refusal names the Model and attribute. */
|
|
1673
|
+
#attribute(name) {
|
|
1674
|
+
return attributeFor(this.#model, name);
|
|
1675
|
+
}
|
|
1676
|
+
/** A new record's initial value as stored: its declared default or generated id, else null. */
|
|
1677
|
+
#initialOf(name) {
|
|
1678
|
+
return this.#initialValues.has(name) ? this.#initialValues.get(name) : this.#attribute(name).write(null);
|
|
1679
|
+
}
|
|
1680
|
+
/** The value before the unsaved change: as last loaded or saved, or a new record's initial one. */
|
|
1681
|
+
#valueBefore(name) {
|
|
1682
|
+
if (this.#isInSnapshot(name)) return this.#snapshotValue(name);
|
|
1683
|
+
return this.#attribute(name).read(this.#initialOf(name));
|
|
1684
|
+
}
|
|
1685
|
+
/** An attribute's current value in its stored form, for comparing with the Snapshot. */
|
|
1686
|
+
#storedForm(name) {
|
|
1687
|
+
return this.#attribute(name).write(this.#values[name]);
|
|
1688
|
+
}
|
|
1689
|
+
/** A copy of an attribute's current value, read back from its stored form. */
|
|
1690
|
+
#copyOf(name) {
|
|
1691
|
+
return this.#attribute(name).copy(this.#values[name]);
|
|
1692
|
+
}
|
|
1693
|
+
/** Every loaded attribute becomes what D1 holds for it: its value, written and read back. */
|
|
1694
|
+
#settle() {
|
|
1695
|
+
for (const name of Object.keys(this.#values)) this.#values[name] = this.#copyOf(name);
|
|
1696
|
+
}
|
|
1697
|
+
/** The columns among `names` and their values: a virtual attribute has no column (#356). */
|
|
1698
|
+
#assignmentsOf(names) {
|
|
1699
|
+
return names.filter((name) => this.#definition(name).virtual !== true).map((name) => [name, this.#values[name]]);
|
|
1700
|
+
}
|
|
1701
|
+
/**
|
|
1702
|
+
* The current values become the Snapshot: persisted and clean. After a load, the entries for
|
|
1703
|
+
* `row`'s cells (`loadedCount` of the values) are made only when first used, so a record that's
|
|
1704
|
+
* only read never writes them (#91).
|
|
1705
|
+
*/
|
|
1706
|
+
#markSaved(row, loadedCount = 0) {
|
|
1707
|
+
this.#snapshot.clear();
|
|
1708
|
+
this.#snapshotRow = row;
|
|
1709
|
+
const names = Object.keys(this.#values);
|
|
1710
|
+
if (names.length !== loadedCount) {
|
|
1711
|
+
for (const name of names) if (!this.#isInRow(name)) this.#snapshot.set(name, this.#storedForm(name));
|
|
1712
|
+
}
|
|
1713
|
+
this.#lifecycle = "persisted";
|
|
1714
|
+
this.#assigned.clear();
|
|
1715
|
+
}
|
|
1716
|
+
/** Whether the Snapshot has `name`: it was loaded or saved. */
|
|
1717
|
+
#isInSnapshot(name) {
|
|
1718
|
+
return this.#snapshot.has(name) || this.#isInRow(name);
|
|
1719
|
+
}
|
|
1720
|
+
/** `name`'s Snapshot entry, its stored form, made from the loaded row's cell on first use. */
|
|
1721
|
+
#snapshotOf(name) {
|
|
1722
|
+
if (this.#snapshot.has(name) || !this.#isInRow(name)) return this.#snapshot.get(name);
|
|
1723
|
+
const attribute = this.#attribute(name);
|
|
1724
|
+
const stored = attribute.write(attribute.read(this.#snapshotRow[this.#definition(name).column]));
|
|
1725
|
+
this.#snapshot.set(name, stored);
|
|
1726
|
+
return stored;
|
|
1727
|
+
}
|
|
1728
|
+
/** `name`'s value as loaded or saved: a fresh copy, read back from its Snapshot entry. */
|
|
1729
|
+
#snapshotValue(name) {
|
|
1730
|
+
return this.#attribute(name).read(this.#snapshotOf(name));
|
|
1422
1731
|
}
|
|
1423
|
-
/**
|
|
1424
|
-
|
|
1425
|
-
|
|
1732
|
+
/** Whether the row the Snapshot was loaded from has a cell for `name`. */
|
|
1733
|
+
#isInRow(name) {
|
|
1734
|
+
const { column, virtual } = this.#definition(name);
|
|
1735
|
+
return this.#snapshotRow !== void 0 && virtual !== true && column in this.#snapshotRow;
|
|
1426
1736
|
}
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1737
|
+
};
|
|
1738
|
+
// src/secure-passwords.ts
|
|
1739
|
+
/** Whether a declared attribute is a secure password: an object with `securePassword` and no type. */
|
|
1740
|
+
function isSecurePasswordDeclaration(declared) {
|
|
1741
|
+
return typeof declared === "object" && declared !== null && "securePassword" in declared && !("type" in declared);
|
|
1742
|
+
}
|
|
1743
|
+
/** The names of the attributes a secure password adds besides itself. */
|
|
1744
|
+
function companionsOf(name) {
|
|
1745
|
+
return [`${name}Confirmation`, `${name}Challenge`];
|
|
1746
|
+
}
|
|
1747
|
+
/**
|
|
1748
|
+
* The attributes that hold a secret, which `toJSON()` leaves out and every filter hides, whatever
|
|
1749
|
+
* `hiddenAttributes` and `filterAttributes` say: each secure password, its confirmation, its
|
|
1750
|
+
* challenge and its digest, and each secure token.
|
|
1751
|
+
*/
|
|
1752
|
+
function secretAttributeNames(definitions) {
|
|
1753
|
+
let names = secretNames.get(definitions);
|
|
1754
|
+
if (names === void 0) {
|
|
1755
|
+
names = secretsIn(definitions);
|
|
1756
|
+
secretNames.set(definitions, names);
|
|
1435
1757
|
}
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1758
|
+
return names;
|
|
1759
|
+
}
|
|
1760
|
+
/**
|
|
1761
|
+
* Each Model's secret attributes, by its attributes' definitions, which don't change once made.
|
|
1762
|
+
* Module-level, but not request state (ADR-0003): derived only from the classes.
|
|
1763
|
+
*/
|
|
1764
|
+
const secretNames = /* @__PURE__ */ new WeakMap();
|
|
1765
|
+
function secretsIn(definitions) {
|
|
1766
|
+
const passwords = securePasswordsOf(definitions).flatMap(({ name, digest }) => [
|
|
1767
|
+
name,
|
|
1768
|
+
...companionsOf(name),
|
|
1769
|
+
digest
|
|
1770
|
+
]);
|
|
1771
|
+
const tokens = [...definitions].filter(([, { secureToken }]) => secureToken !== void 0);
|
|
1772
|
+
return /* @__PURE__ */ new Set([...passwords, ...tokens.map(([name]) => name)]);
|
|
1773
|
+
}
|
|
1774
|
+
/**
|
|
1775
|
+
* The declared attributes with each secure password replaced by the virtual attributes it adds;
|
|
1776
|
+
* `where` names the Model in an error. One declared with another key, or alongside an attribute
|
|
1777
|
+
* it adds, is an `InvalidModel`.
|
|
1778
|
+
*/
|
|
1779
|
+
function withSecurePasswords(where, declared) {
|
|
1780
|
+
const expanded = {};
|
|
1781
|
+
for (const [name, each] of Object.entries(declared)) {
|
|
1782
|
+
if (!isSecurePasswordDeclaration(each)) {
|
|
1783
|
+
expanded[name] = each;
|
|
1784
|
+
continue;
|
|
1785
|
+
}
|
|
1786
|
+
if (Object.keys(each).length !== 1 || !isSecurePasswordOption(each.securePassword)) throw new InvalidModel(`${where}${name}: a secure password is { securePassword: true }, or { securePassword: { algorithm?, validations? } }`);
|
|
1787
|
+
expanded[name] = {
|
|
1788
|
+
type: "string",
|
|
1789
|
+
virtual: true,
|
|
1790
|
+
securePassword: each.securePassword
|
|
1791
|
+
};
|
|
1792
|
+
for (const companion of companionsOf(name)) {
|
|
1793
|
+
if (Object.hasOwn(declared, companion)) throw new InvalidModel(`${where}${companion} is declared by the secure password ${name}, so leave it out`);
|
|
1794
|
+
expanded[companion] = {
|
|
1795
|
+
type: "string",
|
|
1796
|
+
virtual: true
|
|
1797
|
+
};
|
|
1798
|
+
}
|
|
1441
1799
|
}
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1800
|
+
return expanded;
|
|
1801
|
+
}
|
|
1802
|
+
/** How long a reset token lasts unless `expiresIn` says. */
|
|
1803
|
+
const RESET_TOKEN_EXPIRES_IN = { minutes: 15 };
|
|
1804
|
+
function resetTokenExpiryOf(option) {
|
|
1805
|
+
if (option === false) return void 0;
|
|
1806
|
+
return (option === true ? void 0 : option?.expiresIn) ?? RESET_TOKEN_EXPIRES_IN;
|
|
1807
|
+
}
|
|
1808
|
+
/**
|
|
1809
|
+
* The tokens each secure password with a reset token has (#517): `passwordReset` for
|
|
1810
|
+
* `password`, lasting its `expiresIn`, which stop finding their record once its digest changes.
|
|
1811
|
+
*/
|
|
1812
|
+
function resetTokenDefinitions(definitions) {
|
|
1813
|
+
return securePasswordsOf(definitions).flatMap(({ name, digest, resetTokenExpiresIn }) => resetTokenExpiresIn === void 0 ? [] : [{
|
|
1814
|
+
purpose: resetPurposeOf(name),
|
|
1815
|
+
expiresIn: resetTokenExpiresIn,
|
|
1816
|
+
dependsOn: (record) => record[state].read(digest)
|
|
1817
|
+
}]);
|
|
1818
|
+
}
|
|
1819
|
+
/** A Model's secure passwords, from its attributes' definitions. */
|
|
1820
|
+
function securePasswordsOf(definitions) {
|
|
1821
|
+
return [...definitions].flatMap(([name, { securePassword }]) => {
|
|
1822
|
+
if (securePassword === void 0) return [];
|
|
1823
|
+
const options = securePassword === true ? {} : securePassword;
|
|
1824
|
+
return [{
|
|
1825
|
+
name,
|
|
1826
|
+
digest: digestOf(definitions, name),
|
|
1827
|
+
challenge: companionsOf(name)[1],
|
|
1828
|
+
algorithm: options.algorithm ?? pbkdf2Sha256,
|
|
1829
|
+
isValidated: options.validations !== false,
|
|
1830
|
+
resetTokenExpiresIn: resetTokenExpiryOf(options.resetToken)
|
|
1831
|
+
}];
|
|
1832
|
+
});
|
|
1833
|
+
}
|
|
1834
|
+
/**
|
|
1835
|
+
* Whether `given` is the password a record's digest was made from: never for a value that isn't a
|
|
1836
|
+
* string. Without a digest, the password is hashed anyway, so the time taken doesn't say whether the record has one.
|
|
1837
|
+
*/
|
|
1838
|
+
async function isPasswordOf({ digest, algorithm }, record, given) {
|
|
1839
|
+
if (typeof given !== "string") return false;
|
|
1840
|
+
const stored = record[state].read(digest);
|
|
1841
|
+
if (isPresent(stored)) return algorithm.verify(given, stored);
|
|
1842
|
+
await algorithm.hash(given);
|
|
1843
|
+
return false;
|
|
1844
|
+
}
|
|
1845
|
+
/**
|
|
1846
|
+
* Defines each secure password's methods on a Model's prototype: `authenticatePassword`, and
|
|
1847
|
+
* `authenticate` for `password`, resolving to the record when the password is the one its
|
|
1848
|
+
* digest was made from, and `false` when it isn't, or there's no digest.
|
|
1849
|
+
*/
|
|
1850
|
+
function defineSecurePasswordMethods(prototype, definitions) {
|
|
1851
|
+
for (const password of securePasswordsOf(definitions)) {
|
|
1852
|
+
async function authenticate(given) {
|
|
1853
|
+
return await isPasswordOf(password, this, given) ? this : false;
|
|
1854
|
+
}
|
|
1855
|
+
const { name } = password;
|
|
1856
|
+
const names = [`authenticate${capitalized(name)}`, ...name === "password" ? ["authenticate"] : []];
|
|
1857
|
+
for (const method of names) Object.defineProperty(prototype, method, {
|
|
1858
|
+
value: authenticate,
|
|
1859
|
+
configurable: true,
|
|
1860
|
+
writable: true
|
|
1861
|
+
});
|
|
1862
|
+
if (password.resetTokenExpiresIn !== void 0) defineResetToken(prototype, name);
|
|
1445
1863
|
}
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1864
|
+
}
|
|
1865
|
+
/** The purpose a secure password's reset tokens are for: `passwordReset` for `password`. */
|
|
1866
|
+
function resetPurposeOf(name) {
|
|
1867
|
+
return `${name}Reset`;
|
|
1868
|
+
}
|
|
1869
|
+
/** `passwordResetToken()` on a Model's prototype: a token for `passwordReset`. */
|
|
1870
|
+
function defineResetToken(prototype, name) {
|
|
1871
|
+
function resetToken() {
|
|
1872
|
+
return this.generateTokenFor(resetPurposeOf(name));
|
|
1449
1873
|
}
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1874
|
+
Object.defineProperty(prototype, `${name}ResetToken`, {
|
|
1875
|
+
value: resetToken,
|
|
1876
|
+
configurable: true,
|
|
1877
|
+
writable: true
|
|
1878
|
+
});
|
|
1879
|
+
}
|
|
1880
|
+
/** The digest's attribute, when `name` is a secure password: `passwordDigest` for `password`. */
|
|
1881
|
+
function digestOf(definitions, name) {
|
|
1882
|
+
return definitions.get(name)?.securePassword === void 0 ? void 0 : `${name}Digest`;
|
|
1883
|
+
}
|
|
1884
|
+
/**
|
|
1885
|
+
* Hashes each secure password changed since the record was loaded or saved into its digest,
|
|
1886
|
+
* as the record is saved; `""` and null leave the digest to their assignment. A save runs it
|
|
1887
|
+
* before and after its before-callbacks, so a password one assigns is hashed too, and one it
|
|
1888
|
+
* already hashed, into the digest the record holds, isn't hashed again.
|
|
1889
|
+
*/
|
|
1890
|
+
async function hashPasswords(definitions, record) {
|
|
1891
|
+
for (const password of securePasswordsOf(definitions)) {
|
|
1892
|
+
const waiting = waitingPassword(password, record);
|
|
1893
|
+
if (waiting === void 0 || isHashedAlready(record, password, waiting)) continue;
|
|
1894
|
+
const digest = await password.algorithm.hash(waiting);
|
|
1895
|
+
record.write(password.digest, digest);
|
|
1896
|
+
hashedOf(record).set(password.name, {
|
|
1897
|
+
password: waiting,
|
|
1898
|
+
digest
|
|
1899
|
+
});
|
|
1457
1900
|
}
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1901
|
+
}
|
|
1902
|
+
/**
|
|
1903
|
+
* Each record's passwords as last hashed, with the digests they made, so a save doesn't hash one
|
|
1904
|
+
* again. Module-level, but not request state (ADR-0003): keyed by the record itself.
|
|
1905
|
+
*/
|
|
1906
|
+
const hashed = /* @__PURE__ */ new WeakMap();
|
|
1907
|
+
function hashedOf(record) {
|
|
1908
|
+
let byName = hashed.get(record);
|
|
1909
|
+
if (byName === void 0) {
|
|
1910
|
+
byName = /* @__PURE__ */ new Map();
|
|
1911
|
+
hashed.set(record, byName);
|
|
1466
1912
|
}
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1913
|
+
return byName;
|
|
1914
|
+
}
|
|
1915
|
+
/** Whether `password` was hashed into the digest the record holds now. */
|
|
1916
|
+
function isHashedAlready(record, { name, digest }, password) {
|
|
1917
|
+
const last = hashed.get(record)?.get(name);
|
|
1918
|
+
return last !== void 0 && last.password === password && last.digest === record.read(digest);
|
|
1919
|
+
}
|
|
1920
|
+
/**
|
|
1921
|
+
* The failures of each validated secure password, in order: blank while it has no digest and no
|
|
1922
|
+
* password waiting to be hashed; its challenge, when given, invalid unless it's the password the
|
|
1923
|
+
* digest as last saved was made from; and too long past its algorithm's `maxBytes`, in UTF-8.
|
|
1924
|
+
*/
|
|
1925
|
+
async function passwordFailures(definitions, values) {
|
|
1926
|
+
const failures = [];
|
|
1927
|
+
for (const password of securePasswordsOf(definitions)) {
|
|
1928
|
+
if (!password.isValidated) continue;
|
|
1929
|
+
const waiting = waitingPassword(password, values);
|
|
1930
|
+
if (waiting === void 0 && !isPresent(values.read(password.digest))) failures.push({
|
|
1931
|
+
attribute: password.name,
|
|
1932
|
+
type: "blank"
|
|
1933
|
+
});
|
|
1934
|
+
if (!await isChallengeMet(password, values)) failures.push({
|
|
1935
|
+
attribute: password.challenge,
|
|
1936
|
+
type: "invalid"
|
|
1937
|
+
});
|
|
1938
|
+
const { maxBytes } = password.algorithm;
|
|
1939
|
+
if (maxBytes !== void 0 && new TextEncoder().encode(waiting).length > maxBytes) failures.push({
|
|
1940
|
+
attribute: password.name,
|
|
1941
|
+
type: "passwordTooLong"
|
|
1942
|
+
});
|
|
1472
1943
|
}
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1944
|
+
return failures;
|
|
1945
|
+
}
|
|
1946
|
+
/**
|
|
1947
|
+
* The password a save hashes, if any: one assigned since the record was loaded or saved, or
|
|
1948
|
+
* since null cleared its digest.
|
|
1949
|
+
*/
|
|
1950
|
+
function waitingPassword({ name }, values) {
|
|
1951
|
+
const password = values.read(name);
|
|
1952
|
+
if (typeof password !== "string" || password === "") return void 0;
|
|
1953
|
+
return values.isAttributeChanged(name) ? password : void 0;
|
|
1954
|
+
}
|
|
1955
|
+
/** Whether a digest is there to check a password against: a string that isn't blank. */
|
|
1956
|
+
function isPresent(digest) {
|
|
1957
|
+
return typeof digest === "string" && digest.trim() !== "";
|
|
1958
|
+
}
|
|
1959
|
+
/** Whether a challenge, if given, is the password the digest as last saved was made from. */
|
|
1960
|
+
async function isChallengeMet({ challenge: attribute, digest, algorithm }, values) {
|
|
1961
|
+
const challenge = values.read(attribute);
|
|
1962
|
+
if (typeof challenge !== "string") return true;
|
|
1963
|
+
const saved = values.valueInDatabase(digest);
|
|
1964
|
+
return isPresent(saved) && await algorithm.verify(challenge, saved);
|
|
1965
|
+
}
|
|
1966
|
+
/**
|
|
1967
|
+
* The `confirmation` rule of each validated secure password: its confirmation, when given, must
|
|
1968
|
+
* match it.
|
|
1969
|
+
*/
|
|
1970
|
+
function passwordConfirmations(definitions) {
|
|
1971
|
+
return securePasswordsOf(definitions).filter(({ isValidated }) => isValidated).map(({ name }) => ({
|
|
1972
|
+
attribute: name,
|
|
1973
|
+
options: {
|
|
1974
|
+
confirmation: true,
|
|
1975
|
+
allowNull: true
|
|
1485
1976
|
}
|
|
1977
|
+
}));
|
|
1978
|
+
}
|
|
1979
|
+
/**
|
|
1980
|
+
* A secure password's digest must be a string attribute with a column: `passwordDigest` for
|
|
1981
|
+
* `password`; `InvalidModel` names the attribute it needs, after `where` (`User.`, or nothing).
|
|
1982
|
+
*/
|
|
1983
|
+
function rejectMissingDigests(where, definitions) {
|
|
1984
|
+
for (const { name, digest } of securePasswordsOf(definitions)) {
|
|
1985
|
+
const definition = definitions.get(digest);
|
|
1986
|
+
if (definition === void 0 || definition.virtual === true || definition.type !== "string") throw new InvalidModel(`${where}${name} is a secure password, so it needs a string attribute ${digest} with a column to keep its digest in`);
|
|
1486
1987
|
}
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1988
|
+
}
|
|
1989
|
+
/**
|
|
1990
|
+
* The record the attributes that aren't secure passwords find, if each secure password given is
|
|
1991
|
+
* its own; null otherwise, or for a blank password, which finds nothing. When none is found, each
|
|
1992
|
+
* password is hashed anyway, so the time it takes doesn't say whether a record exists.
|
|
1993
|
+
*/
|
|
1994
|
+
async function authenticateBy(model, attributes) {
|
|
1995
|
+
const { passwords, identifiers } = splitPasswords(model, attributes);
|
|
1996
|
+
if (passwords.some(([, value]) => typeof value !== "string" || value === "")) return null;
|
|
1997
|
+
const record = await model.findBy(identifiers);
|
|
1998
|
+
if (record === null) {
|
|
1999
|
+
for (const [{ algorithm }, value] of passwords) await algorithm.hash(value);
|
|
2000
|
+
return null;
|
|
2001
|
+
}
|
|
2002
|
+
let matches = 0;
|
|
2003
|
+
for (const [password, value] of passwords) if (await isPasswordOf(password, record, value)) matches += 1;
|
|
2004
|
+
return matches === passwords.length ? record : null;
|
|
2005
|
+
}
|
|
2006
|
+
/**
|
|
2007
|
+
* `authenticateBy`'s attributes: its secure passwords, with their values, and the rest, which
|
|
2008
|
+
* find the record. Either missing is a `TypeError`.
|
|
2009
|
+
*/
|
|
2010
|
+
function splitPasswords(model, attributes) {
|
|
2011
|
+
const all = securePasswordsOf(model.attributeDefinitions);
|
|
2012
|
+
const passwords = all.flatMap((password) => Object.hasOwn(attributes, password.name) ? [[password, attributes[password.name]]] : []);
|
|
2013
|
+
const identifiers = Object.fromEntries(Object.entries(attributes).filter(([name]) => !all.some((each) => each.name === name)));
|
|
2014
|
+
if (passwords.length === 0) {
|
|
2015
|
+
const names = all.map(({ name }) => name).join(", ") || "none declared";
|
|
2016
|
+
throw new TypeError(`${model.name}.authenticateBy needs a secure password: ${names}`);
|
|
2017
|
+
}
|
|
2018
|
+
if (Object.keys(identifiers).length === 0) throw new TypeError(`${model.name}.authenticateBy needs an attribute to find the record by`);
|
|
2019
|
+
return {
|
|
2020
|
+
passwords,
|
|
2021
|
+
identifiers
|
|
2022
|
+
};
|
|
2023
|
+
}
|
|
2024
|
+
// src/filtering.ts
|
|
2025
|
+
/** What a listener sees in place of a filtered attribute's value (#83). */
|
|
2026
|
+
const FILTERED = "[FILTERED]";
|
|
2027
|
+
/**
|
|
2028
|
+
* The default filter list, of common secret and personal names: an attribute whose snake_case name
|
|
2029
|
+
* holds one of these, in any case, is filtered (`passwordDigest`, `apiKey`, `resetToken`, `email`).
|
|
2030
|
+
*/
|
|
2031
|
+
const defaultFilterAttributes = [
|
|
2032
|
+
"passw",
|
|
2033
|
+
"email",
|
|
2034
|
+
"secret",
|
|
2035
|
+
"token",
|
|
2036
|
+
"_key",
|
|
2037
|
+
"crypt",
|
|
2038
|
+
"salt",
|
|
2039
|
+
"certificate",
|
|
2040
|
+
"otp",
|
|
2041
|
+
"ssn",
|
|
2042
|
+
"cvv",
|
|
2043
|
+
"cvc"
|
|
2044
|
+
];
|
|
2045
|
+
/**
|
|
2046
|
+
* Whether an attribute's values are hidden from listeners: a secure password's or a secure
|
|
2047
|
+
* token's always (#355); any other when its snake_case name, or an alias's,
|
|
2048
|
+
* holds a string entry lowercased, or read in snake_case (`"apiKey"` as `api_key`, #397), or a
|
|
2049
|
+
* RegExp entry matches the name or its snake_case form.
|
|
2050
|
+
*/
|
|
2051
|
+
function isFiltered(model, given) {
|
|
2052
|
+
const attribute = attributeName(model, given);
|
|
2053
|
+
if (secretAttributeNames(model.attributeDefinitions).has(attribute)) return true;
|
|
2054
|
+
return [attribute, ...[...model.attributeAliases].filter(([, name]) => name === attribute).map(([alias]) => alias)].some((name) => isNameFiltered(model, name));
|
|
2055
|
+
}
|
|
2056
|
+
/** Whether one name matches an entry of `model`'s `filterAttributes`. */
|
|
2057
|
+
function isNameFiltered(model, attribute) {
|
|
2058
|
+
const name = underscore(attribute);
|
|
2059
|
+
return model.filterAttributes.some((entry) => typeof entry === "string" ? name.includes(entry.toLowerCase()) || name.includes(underscore(entry)) : attribute.search(entry) !== -1 || name.search(entry) !== -1);
|
|
2060
|
+
}
|
|
2061
|
+
/** The values of `attributes` that `model` filters, so a message can tell not to show them. */
|
|
2062
|
+
function filteredValues(model, attributes) {
|
|
2063
|
+
return Object.entries(attributes).filter(([name]) => isFiltered(model, name)).map(([, value]) => value);
|
|
2064
|
+
}
|
|
2065
|
+
/** A bound value D1 gets as `value`, and listeners see as `shown`. */
|
|
2066
|
+
var Filtered = class {
|
|
2067
|
+
value;
|
|
2068
|
+
shown;
|
|
2069
|
+
constructor(value, shown = FILTERED) {
|
|
2070
|
+
this.value = value;
|
|
2071
|
+
this.shown = shown;
|
|
1490
2072
|
}
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
2073
|
+
};
|
|
2074
|
+
/** A primary key as an error shows it: "[FILTERED]" when the key is a filtered attribute. */
|
|
2075
|
+
function shownKey(model, key) {
|
|
2076
|
+
return isFiltered(model, model.primaryKey) ? FILTERED : String(key);
|
|
2077
|
+
}
|
|
2078
|
+
/** The value D1 binds. */
|
|
2079
|
+
function boundValue(param) {
|
|
2080
|
+
return param instanceof Filtered ? param.value : param;
|
|
2081
|
+
}
|
|
2082
|
+
/** The value listeners see. */
|
|
2083
|
+
function shownValue(param) {
|
|
2084
|
+
return param instanceof Filtered ? param.shown : param;
|
|
2085
|
+
}
|
|
2086
|
+
// src/thenables.ts
|
|
2087
|
+
/**
|
|
2088
|
+
* Throws `TypeError` with `message` if `result` is a promise or another thenable, which the code
|
|
2089
|
+
* that ran it can't await. Its rejection, if it has one, is handled here, so the `TypeError` is
|
|
2090
|
+
* the only error.
|
|
2091
|
+
*/
|
|
2092
|
+
function refuseThenable(result, message) {
|
|
2093
|
+
if (!isThenable(result)) return;
|
|
2094
|
+
Promise.resolve(result).catch(() => {});
|
|
2095
|
+
throw new TypeError(message);
|
|
2096
|
+
}
|
|
2097
|
+
/** Whether `value` is a Promise or another thenable, as an async function returns. */
|
|
2098
|
+
function isThenable(value) {
|
|
2099
|
+
return typeof value?.then === "function";
|
|
2100
|
+
}
|
|
2101
|
+
// src/normalization.ts
|
|
2102
|
+
/** The normalizations declared for one of `model`'s attributes, a parent class's first. */
|
|
2103
|
+
function normalizationsOf(model, attribute) {
|
|
2104
|
+
return declared(model, "normalizations").filter((each) => each.attribute === attribute);
|
|
2105
|
+
}
|
|
2106
|
+
/** Refuses a normalization of a name that isn't one of `model`'s attributes. */
|
|
2107
|
+
function checkNormalizedName(model, attribute) {
|
|
2108
|
+
if (model.attributeDefinitions.has(attribute)) return;
|
|
2109
|
+
throw new InvalidModel(`${model.name} normalizes "${attribute}", which isn't one of its attributes`);
|
|
2110
|
+
}
|
|
2111
|
+
// src/lock-version.ts
|
|
2112
|
+
/** The attribute whose presence, as an integer, turns locking on. */
|
|
2113
|
+
const lockVersion = "lockVersion";
|
|
2114
|
+
/** Whether the Model's records lock: it has an integer `lockVersion`. */
|
|
2115
|
+
function isLocking(model) {
|
|
2116
|
+
return model.attributeDefinitions.get(lockVersion)?.type === "integer";
|
|
2117
|
+
}
|
|
2118
|
+
/** Whether `name` is the Model's lock version, which a NULL in its row reads as 0. */
|
|
2119
|
+
function isLockVersion(model, name) {
|
|
2120
|
+
return name === "lockVersion" && isLocking(model);
|
|
2121
|
+
}
|
|
2122
|
+
// src/attribute.ts
|
|
2123
|
+
/** What `condition()` and `conditionCell()` give for a value that can't match anything. */
|
|
2124
|
+
const noMatch = uncastable;
|
|
2125
|
+
/**
|
|
2126
|
+
* One attribute's value path, resolved once per Model class by `attributeFor` (#163). Which
|
|
2127
|
+
* Model and attribute a refusal names, whether the attribute is filtered, and how its type is
|
|
2128
|
+
* stored are known here, so a caller only says what the value is for.
|
|
2129
|
+
*/
|
|
2130
|
+
var Attribute = class {
|
|
2131
|
+
#model;
|
|
2132
|
+
name;
|
|
2133
|
+
#definition;
|
|
2134
|
+
/** @internal Use `attributeFor`. */
|
|
2135
|
+
constructor(model, name) {
|
|
2136
|
+
this.#model = model;
|
|
2137
|
+
this.name = name;
|
|
2138
|
+
this.#definition = attributeOf(model, name);
|
|
1494
2139
|
}
|
|
1495
|
-
/**
|
|
1496
|
-
|
|
1497
|
-
return this.#
|
|
2140
|
+
/** Its column; `UnknownAttribute` for a virtual attribute, which has none (#356). */
|
|
2141
|
+
get column() {
|
|
2142
|
+
return columnOf(this.#model, this.name).column;
|
|
1498
2143
|
}
|
|
1499
|
-
/**
|
|
1500
|
-
get
|
|
1501
|
-
return this.#
|
|
2144
|
+
/** Whether it's a `string` attribute, which D1 compares as text, not by number. */
|
|
2145
|
+
get isText() {
|
|
2146
|
+
return this.#definition.type === "string";
|
|
1502
2147
|
}
|
|
1503
|
-
/**
|
|
1504
|
-
get
|
|
1505
|
-
return this.#
|
|
2148
|
+
/** Whether it's a `binary` attribute, whose cells are bytes, which JSON can't hold (#20). */
|
|
2149
|
+
get isBinary() {
|
|
2150
|
+
return this.#definition.type === "binary";
|
|
1506
2151
|
}
|
|
1507
|
-
/**
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
* each from its value before: a declared default the record kept isn't one (#41).
|
|
1511
|
-
*/
|
|
1512
|
-
commitInsert(row) {
|
|
1513
|
-
const written = new Set(this.changedNames());
|
|
1514
|
-
const before = new Map(Object.keys(this.#values).map((name) => [name, {
|
|
1515
|
-
stored: this.#storedForm(name),
|
|
1516
|
-
value: this.#valueBefore(name)
|
|
1517
|
-
}]));
|
|
1518
|
-
if (row === void 0) {
|
|
1519
|
-
this.#settle();
|
|
1520
|
-
this.#markSaved();
|
|
1521
|
-
} else this.loadRow(row);
|
|
1522
|
-
this.#savedChanges = Object.fromEntries([...before].filter(([name, { stored }]) => written.has(name) || !isSameCell(this.#storedForm(name), stored)).map(([name, { value }]) => [name, [value, this.#copyOf(name)]]));
|
|
1523
|
-
this.isPreviouslyNew = true;
|
|
2152
|
+
/** Whether it's a `json` attribute, whose stored text is JSON itself. */
|
|
2153
|
+
get isJson() {
|
|
2154
|
+
return this.#definition.type === "json";
|
|
1524
2155
|
}
|
|
1525
2156
|
/**
|
|
1526
|
-
*
|
|
1527
|
-
*
|
|
1528
|
-
*
|
|
1529
|
-
*
|
|
2157
|
+
* An assigned value (a setter, `build`, `update`, `insert`, `permit`) as the attribute's type:
|
|
2158
|
+
* only what's unambiguous for it (#81). `undefined` throws, as it would store NULL silently;
|
|
2159
|
+
* what can't be cast throws `TypeError` naming the Model and attribute, showing the value
|
|
2160
|
+
* unless the attribute is filtered (#83).
|
|
1530
2161
|
*/
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
this.#
|
|
1534
|
-
|
|
1535
|
-
this.#
|
|
1536
|
-
|
|
2162
|
+
cast(value) {
|
|
2163
|
+
requireDefined(this.#model, this.name, value);
|
|
2164
|
+
const cast = this.#convertOrRefuse(value, () => castValue(this.#definition, value));
|
|
2165
|
+
if (cast === uncastable && this.#isValidatedEnum()) return value;
|
|
2166
|
+
return this.#orRefuse(cast, value);
|
|
2167
|
+
}
|
|
2168
|
+
/** An assigned value cast, then normalized (#354): what a record keeps for it. */
|
|
2169
|
+
assigned(value) {
|
|
2170
|
+
return this.normalize(this.cast(value));
|
|
1537
2171
|
}
|
|
1538
2172
|
/**
|
|
1539
|
-
*
|
|
1540
|
-
*
|
|
1541
|
-
*
|
|
2173
|
+
* An already cast value through each of the attribute's normalizations, in order (#354): null
|
|
2174
|
+
* only through those declared `applyToNull`. Each result is cast again, so it's a value of the
|
|
2175
|
+
* attribute's type, whatever plain JavaScript returns; a promise is refused.
|
|
1542
2176
|
*/
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
2177
|
+
normalize(value) {
|
|
2178
|
+
return this.#normalized(value, (result) => this.cast(result));
|
|
2179
|
+
}
|
|
2180
|
+
/**
|
|
2181
|
+
* A condition's value cast as a condition's, then normalized as an assigned value is (#354), each
|
|
2182
|
+
* result cast again as a condition's, so a decimal's precision limits neither. A value that
|
|
2183
|
+
* can't be cast is kept as it was given, so it still matches nothing, and an error that names it
|
|
2184
|
+
* names what was given; a result that can't be cast throws, as assigning it would.
|
|
2185
|
+
*/
|
|
2186
|
+
normalizedCondition(value) {
|
|
2187
|
+
const cast = this.condition(value);
|
|
2188
|
+
if (cast === noMatch) return value;
|
|
2189
|
+
return this.#normalized(cast, (result) => this.#conditionResult(result));
|
|
2190
|
+
}
|
|
2191
|
+
/** A normalization's result as a condition's value; `TypeError` where assigning it would be. */
|
|
2192
|
+
#conditionResult(result) {
|
|
2193
|
+
const cast = this.condition(result);
|
|
2194
|
+
if (cast !== noMatch) return cast;
|
|
2195
|
+
this.cast(result);
|
|
2196
|
+
return result;
|
|
2197
|
+
}
|
|
2198
|
+
/** `value` through each normalization, each result cast by `recast`. */
|
|
2199
|
+
#normalized(value, recast) {
|
|
2200
|
+
let normalized = value;
|
|
2201
|
+
for (const { with: normalize, applyToNull } of normalizationsOf(this.#model, this.name)) {
|
|
2202
|
+
if (normalized === null && !applyToNull) continue;
|
|
2203
|
+
const result = normalize(normalized);
|
|
2204
|
+
refuseThenable(result, `${this.#model.name} normalizes "${this.name}" with a function that returned a promise; a normalization runs synchronously`);
|
|
2205
|
+
normalized = recast(result);
|
|
1549
2206
|
}
|
|
2207
|
+
return normalized;
|
|
2208
|
+
}
|
|
2209
|
+
/** Whether the attribute has a normalization, so its conditions need normalizing (#354). */
|
|
2210
|
+
get hasNormalization() {
|
|
2211
|
+
return normalizationsOf(this.#model, this.name).length > 0;
|
|
2212
|
+
}
|
|
2213
|
+
/** Whether it's an enum declared `validate: true`, which keeps an unknown value it's given. */
|
|
2214
|
+
#isValidatedEnum() {
|
|
2215
|
+
const { enum: values, validate = false } = this.#definition;
|
|
2216
|
+
return values !== void 0 && validate !== false;
|
|
1550
2217
|
}
|
|
1551
2218
|
/**
|
|
1552
|
-
*
|
|
1553
|
-
*
|
|
2219
|
+
* A key copied from another record or inherited from a condition: cast as a condition's, but
|
|
2220
|
+
* one that can't be cast throws, naming the association it came through.
|
|
1554
2221
|
*/
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
this
|
|
1558
|
-
this.#savedChanges = Object.fromEntries(names.filter((name) => Object.hasOwn(changes, name)).map((name) => [name, changes[name]]));
|
|
2222
|
+
key(value, association) {
|
|
2223
|
+
requireDefined(this.#model, this.name, value);
|
|
2224
|
+
return this.#orRefuse(castKey(this.#definition, value), value, association);
|
|
1559
2225
|
}
|
|
1560
|
-
/**
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
2226
|
+
/**
|
|
2227
|
+
* A condition's value (`where`, `find`, a preload) as the attribute's type, or `noMatch`: a
|
|
2228
|
+
* number also matches a string attribute as its digits, and a value that can't be cast
|
|
2229
|
+
* matches nothing, so a value from a URL is never an error.
|
|
2230
|
+
*/
|
|
2231
|
+
condition(value) {
|
|
2232
|
+
return castCondition(this.#definition, value);
|
|
1564
2233
|
}
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
2234
|
+
/** A condition's value in the form D1 stores, or `noMatch`. */
|
|
2235
|
+
conditionCell(value) {
|
|
2236
|
+
const cast = this.condition(value);
|
|
2237
|
+
return cast === noMatch ? noMatch : this.write(cast);
|
|
1568
2238
|
}
|
|
1569
|
-
/**
|
|
1570
|
-
|
|
1571
|
-
|
|
2239
|
+
/**
|
|
2240
|
+
* An already cast value in the form D1 stores. A `json` value changed in place into one JSON
|
|
2241
|
+
* can't write throws `TypeError` naming the attribute, as assigning it would (#146).
|
|
2242
|
+
*/
|
|
2243
|
+
write(value) {
|
|
2244
|
+
let stored;
|
|
2245
|
+
try {
|
|
2246
|
+
stored = writeValue(this.#definition, value);
|
|
2247
|
+
} catch (error) {
|
|
2248
|
+
if (this.#definition.customType !== void 0) throw this.#refusal(value, void 0, error);
|
|
2249
|
+
if (this.#definition.type !== "json") throw error;
|
|
2250
|
+
throw this.#refusal(value);
|
|
2251
|
+
}
|
|
2252
|
+
if (stored === void 0) throw this.#refusal(value);
|
|
2253
|
+
return stored;
|
|
1572
2254
|
}
|
|
1573
|
-
/** An
|
|
1574
|
-
|
|
1575
|
-
this
|
|
2255
|
+
/** An assigned value cast, then in the form D1 stores. */
|
|
2256
|
+
store(value) {
|
|
2257
|
+
return this.write(this.cast(value));
|
|
1576
2258
|
}
|
|
1577
|
-
#
|
|
1578
|
-
|
|
2259
|
+
/** An assigned value cast and normalized (#354), then in the form D1 stores. */
|
|
2260
|
+
storeNormalized(value) {
|
|
2261
|
+
return this.write(this.assigned(value));
|
|
1579
2262
|
}
|
|
1580
|
-
/**
|
|
1581
|
-
|
|
1582
|
-
|
|
2263
|
+
/**
|
|
2264
|
+
* A cell D1 returned as the attribute's value. One that isn't (text in a Unix time column, or
|
|
2265
|
+
* past the range of a `Date`; a json cell that isn't JSON) throws `TypeError` naming the
|
|
2266
|
+
* attribute, with the cell hidden if it's filtered, not the parser's own error (#73, #146).
|
|
2267
|
+
*/
|
|
2268
|
+
read(cell) {
|
|
2269
|
+
if (cell === null && isLockVersion(this.#model, this.name)) return 0;
|
|
2270
|
+
const value = this.#convertOrRefuse(cell, () => readValue(this.#definition, cell));
|
|
2271
|
+
if (value === uncastable) throw this.#refusal(cell);
|
|
2272
|
+
return value;
|
|
1583
2273
|
}
|
|
1584
|
-
/** A
|
|
1585
|
-
|
|
1586
|
-
return this
|
|
2274
|
+
/** A copy of a value: written as D1 stores it, then read back. */
|
|
2275
|
+
copy(value) {
|
|
2276
|
+
return this.read(this.write(value));
|
|
1587
2277
|
}
|
|
1588
|
-
/**
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
2278
|
+
/**
|
|
2279
|
+
* Whether two values are the same as stored (dates by time, json and bytes by content). Each is
|
|
2280
|
+
* cast as a condition's value first, so `isAttributeChanged`'s `from` and `to` compare as
|
|
2281
|
+
* conditions do, and one that can't be cast is the same as nothing (#20).
|
|
2282
|
+
*/
|
|
2283
|
+
isSame(a, b) {
|
|
2284
|
+
const [x, y] = [this.#comparable(a), this.#comparable(b)];
|
|
2285
|
+
if (x === noMatch || y === noMatch) return false;
|
|
2286
|
+
return isSameCell(writeValue(this.#definition, x), writeValue(this.#definition, y));
|
|
1592
2287
|
}
|
|
1593
|
-
/**
|
|
1594
|
-
|
|
1595
|
-
|
|
2288
|
+
/**
|
|
2289
|
+
* A value to compare, cast as a condition's: `null` stays `null`, and a validated enum's
|
|
2290
|
+
* unknown value, which a record may hold, stays as it is (#340).
|
|
2291
|
+
*/
|
|
2292
|
+
#comparable(value) {
|
|
2293
|
+
if (value === null || value === void 0) return value ?? null;
|
|
2294
|
+
const cast = this.condition(value);
|
|
2295
|
+
return cast === noMatch && this.#isValidatedEnum() ? value : cast;
|
|
1596
2296
|
}
|
|
1597
|
-
/**
|
|
1598
|
-
|
|
1599
|
-
|
|
2297
|
+
/** An assigned value, cast and written, bound hidden from `onQuery` if filtered (#83). */
|
|
2298
|
+
bind(params, value) {
|
|
2299
|
+
this.bindCells(params, this.store(value));
|
|
1600
2300
|
}
|
|
1601
|
-
/**
|
|
1602
|
-
|
|
1603
|
-
|
|
2301
|
+
/**
|
|
2302
|
+
* Binds cells (as D1 holds them) as the attribute's, each hidden from `onQuery` listeners when
|
|
2303
|
+
* the attribute is filtered (#83); D1 still gets the real values. Filtering is asked at the
|
|
2304
|
+
* time, since `filterAttributes` is a static a Model may set after this was resolved.
|
|
2305
|
+
*/
|
|
2306
|
+
bindCells(params, ...cells) {
|
|
2307
|
+
const hidden = this.#isHidden();
|
|
2308
|
+
for (const cell of cells) params.push(hidden ? new Filtered(cell) : cell);
|
|
1604
2309
|
}
|
|
1605
|
-
#
|
|
1606
|
-
|
|
2310
|
+
#orRefuse(cast, value, association) {
|
|
2311
|
+
if (cast === uncastable) throw this.#refusal(value, association);
|
|
2312
|
+
return cast;
|
|
1607
2313
|
}
|
|
1608
2314
|
/**
|
|
1609
|
-
*
|
|
1610
|
-
*
|
|
1611
|
-
* only read never writes them (#91).
|
|
2315
|
+
* `convert`'s result. What a custom type's own function throws for `value` is refused as any
|
|
2316
|
+
* value its type can't hold, with the type's error as the cause (#20).
|
|
1612
2317
|
*/
|
|
1613
|
-
#
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
2318
|
+
#convertOrRefuse(value, convert) {
|
|
2319
|
+
try {
|
|
2320
|
+
return convert();
|
|
2321
|
+
} catch (error) {
|
|
2322
|
+
if (this.#definition.customType === void 0) throw error;
|
|
2323
|
+
throw this.#refusal(value, void 0, error);
|
|
1619
2324
|
}
|
|
1620
|
-
this.#lifecycle = "persisted";
|
|
1621
|
-
this.#assigned.clear();
|
|
1622
2325
|
}
|
|
1623
|
-
/** Whether the
|
|
1624
|
-
#
|
|
1625
|
-
return this.#
|
|
2326
|
+
/** Whether the attribute's values are hidden from listeners and errors (#83). */
|
|
2327
|
+
#isHidden() {
|
|
2328
|
+
return isFiltered(this.#model, this.name);
|
|
1626
2329
|
}
|
|
1627
|
-
/**
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
2330
|
+
/**
|
|
2331
|
+
* "Sample: "no" isn't a boolean for "enabled"", the value hidden for a filtered attribute. Also
|
|
2332
|
+
* what a stored value that can't be read says: a Unix time that isn't one (#73), or a json
|
|
2333
|
+
* cell that isn't JSON (#146). A custom type's own error is its cause, unless the attribute is
|
|
2334
|
+
* filtered: the error may show the value (#20).
|
|
2335
|
+
*/
|
|
2336
|
+
#refusal(value, association, cause) {
|
|
2337
|
+
const hidden = this.#isHidden();
|
|
2338
|
+
const text = hidden ? FILTERED : shown(value);
|
|
2339
|
+
const from = association === void 0 ? "" : `, the key of ${association}`;
|
|
2340
|
+
return new TypeError(`${this.#model.name}: ${text} isn't ${this.#described()} for "${this.name}"${from}`, hidden || cause === void 0 ? void 0 : { cause });
|
|
1634
2341
|
}
|
|
1635
|
-
/**
|
|
1636
|
-
#
|
|
1637
|
-
|
|
2342
|
+
/** What a value of the attribute is, as a refusal says it: `a boolean`, `one of "draft", "published"`. */
|
|
2343
|
+
#described() {
|
|
2344
|
+
const { type, enum: values, customType } = this.#definition;
|
|
2345
|
+
if (values !== void 0) return `one of ${listedNames(values)}`;
|
|
2346
|
+
if (customType !== void 0) return "a valid value";
|
|
2347
|
+
return valueNames[type] ?? withArticle(type);
|
|
1638
2348
|
}
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
2349
|
+
};
|
|
2350
|
+
const resolved = /* @__PURE__ */ new WeakMap();
|
|
2351
|
+
/**
|
|
2352
|
+
* The resolved attribute of a Model, remembered per class (derived from the class, ADR-0003):
|
|
2353
|
+
* `UnknownAttribute` for a name it doesn't have.
|
|
2354
|
+
*/
|
|
2355
|
+
function attributeFor(model, given) {
|
|
2356
|
+
const name = attributeName(model, given);
|
|
2357
|
+
let attributes = resolved.get(model);
|
|
2358
|
+
if (attributes === void 0) {
|
|
2359
|
+
attributes = /* @__PURE__ */ new Map();
|
|
2360
|
+
resolved.set(model, attributes);
|
|
2361
|
+
}
|
|
2362
|
+
let attribute = attributes.get(name);
|
|
2363
|
+
if (attribute === void 0) {
|
|
2364
|
+
attribute = new Attribute(model, name);
|
|
2365
|
+
attributes.set(name, attribute);
|
|
1642
2366
|
}
|
|
2367
|
+
return attribute;
|
|
2368
|
+
}
|
|
2369
|
+
/**
|
|
2370
|
+
* The values a record built from a Relation inherits from its conditions, cast as keys are: a
|
|
2371
|
+
* hasMany's foreign key names its association (`link`) when it can't be cast.
|
|
2372
|
+
*/
|
|
2373
|
+
function castInherited(model, inherited, link) {
|
|
2374
|
+
return Object.fromEntries(Object.entries(inherited).map(([attribute, value]) => {
|
|
2375
|
+
const association = attribute === link?.attribute ? link.association : void 0;
|
|
2376
|
+
return [attribute, attributeFor(model, attribute).key(value, association)];
|
|
2377
|
+
}));
|
|
2378
|
+
}
|
|
2379
|
+
/** A word with `a` or `an` before it, as a message reads it: `an integer`, `a string`. */
|
|
2380
|
+
function withArticle(word) {
|
|
2381
|
+
return `${/^[aeiou]/.test(word) ? "an" : "a"} ${word}`;
|
|
2382
|
+
}
|
|
2383
|
+
/** How much of a value an error shows: it came from outside, and errors are often logged. */
|
|
2384
|
+
const SHOWN_LENGTH = 60;
|
|
2385
|
+
/** What a value of an attribute type is called in a refusal, where `a`/`an` and its name isn't it. */
|
|
2386
|
+
const valueNames = {
|
|
2387
|
+
json: "a JSON value",
|
|
2388
|
+
binary: "binary data"
|
|
1643
2389
|
};
|
|
2390
|
+
/** A value as an error shows it: JSON where it has one, numbers as written, and at most 60 characters. */
|
|
2391
|
+
function shown(value) {
|
|
2392
|
+
const text = textOf(value);
|
|
2393
|
+
return text.length > SHOWN_LENGTH ? `${text.slice(0, SHOWN_LENGTH)}…` : text;
|
|
2394
|
+
}
|
|
2395
|
+
function textOf(value) {
|
|
2396
|
+
if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return `<${value.constructor.name} of ${value.byteLength} bytes>`;
|
|
2397
|
+
if (value instanceof Blob) return `<${value.constructor.name} of ${value.size} bytes>`;
|
|
2398
|
+
if (typeof value === "number" || isInvalidDate(value)) return String(value);
|
|
2399
|
+
try {
|
|
2400
|
+
return JSON.stringify(value) ?? String(value);
|
|
2401
|
+
} catch {
|
|
2402
|
+
return plainText(value);
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
/** `String(value)`, or its tag (`[object Array]`) when it has no string form: building the refusal mustn't throw. */
|
|
2406
|
+
function plainText(value) {
|
|
2407
|
+
try {
|
|
2408
|
+
return String(value);
|
|
2409
|
+
} catch {
|
|
2410
|
+
return Object.prototype.toString.call(value);
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
1644
2413
|
// src/enum-methods.ts
|
|
1645
2414
|
/** Each name of every enum attribute, with the methods it gives. */
|
|
1646
2415
|
function enumNames(definitions) {
|
|
@@ -1678,12 +2447,11 @@ function methodPart(word) {
|
|
|
1678
2447
|
const [head = "", ...rest] = word.split("_");
|
|
1679
2448
|
return capitalized(head + rest.map(capitalized).join(""));
|
|
1680
2449
|
}
|
|
1681
|
-
const capitalized = (text) => text.charAt(0).toUpperCase() + text.slice(1);
|
|
1682
2450
|
const uncapitalized = (text) => text.charAt(0).toLowerCase() + text.slice(1);
|
|
1683
2451
|
/**
|
|
1684
2452
|
* Defines each enum attribute's methods on `prototype`: `isPublished()` is `status === "published"`,
|
|
1685
2453
|
* and `saveAsPublished()` is `update({ status: "published" })`, so it saves the record's other
|
|
1686
|
-
* changes too
|
|
2454
|
+
* changes too.
|
|
1687
2455
|
*/
|
|
1688
2456
|
function defineEnumMethods(prototype, definitions) {
|
|
1689
2457
|
for (const { attribute, name, records } of enumNames(definitions)) {
|
|
@@ -1702,7 +2470,7 @@ function defineEnumMethods(prototype, definitions) {
|
|
|
1702
2470
|
}
|
|
1703
2471
|
/**
|
|
1704
2472
|
* Defines each enum attribute's scopes on `model`, as `this.scope(…)` statics: `published()` is
|
|
1705
|
-
* `where({ status: "published" })`, and `notPublished()` is `whereNot(…)
|
|
2473
|
+
* `where({ status: "published" })`, and `notPublished()` is `whereNot(…)`.
|
|
1706
2474
|
*/
|
|
1707
2475
|
function defineEnumStatics(model, definitions) {
|
|
1708
2476
|
const declaring = model;
|
|
@@ -1732,7 +2500,7 @@ const enumScopes = /* @__PURE__ */ new WeakSet();
|
|
|
1732
2500
|
/**
|
|
1733
2501
|
* Why an enum's method names can't be as they are, or undefined: two enums give one name, or one
|
|
1734
2502
|
* takes the name of a record method, an attribute, a Relation method, a Model static, or a static
|
|
1735
|
-
* the Model declares itself.
|
|
2503
|
+
* the Model declares itself. It's refused when the enum is declared.
|
|
1736
2504
|
*/
|
|
1737
2505
|
function enumNameProblem(model, taken, methodsOff = /* @__PURE__ */ new Map()) {
|
|
1738
2506
|
const checks = {
|
|
@@ -1873,6 +2641,7 @@ function methodsOffFixes(model) {
|
|
|
1873
2641
|
}
|
|
1874
2642
|
// src/generated-model.ts
|
|
1875
2643
|
const noAttributes = /* @__PURE__ */ new Map();
|
|
2644
|
+
const noAliases = /* @__PURE__ */ new Map();
|
|
1876
2645
|
/**
|
|
1877
2646
|
* What each generated Model settled on when it was first used, by class (a subclass shares its
|
|
1878
2647
|
* parent's). Until then, they're found again on each read, since a `static {}` block reads them
|
|
@@ -1900,7 +2669,10 @@ function tableOwnerOf(model) {
|
|
|
1900
2669
|
schema
|
|
1901
2670
|
};
|
|
1902
2671
|
}
|
|
1903
|
-
/**
|
|
2672
|
+
/**
|
|
2673
|
+
* The attribute accessors on a prototype, reading and writing a record's values; an alias's
|
|
2674
|
+
* (#509) read and write the attribute it names, which the record resolves.
|
|
2675
|
+
*/
|
|
1904
2676
|
function defineAttributeAccessors(prototype, names) {
|
|
1905
2677
|
for (const name of names) Object.defineProperty(prototype, name, {
|
|
1906
2678
|
get() {
|
|
@@ -1932,12 +2704,16 @@ function find(owner, schema) {
|
|
|
1932
2704
|
rejectUngenerated(name, table, schema);
|
|
1933
2705
|
const tableSchema = Object.hasOwn(schema.tables, table) ? schema.tables[table] : void 0;
|
|
1934
2706
|
if (tableSchema === void 0) throw new InvalidModel(`${owner.name}'s table, ${table}, isn't in the generated schema`);
|
|
1935
|
-
const
|
|
2707
|
+
const declared = withSecurePasswords(`${owner.name}.`, owner.attributes ?? {});
|
|
2708
|
+
const { specs, isIgnoringColumns } = specsFor(owner.name, tableSchema, declared);
|
|
1936
2709
|
const definitions = new Map(Object.entries(specs).map(([name, spec]) => [name, define(name, spec)]));
|
|
2710
|
+
const aliases = aliasesIn(`${owner.name}.`, declared, definitions);
|
|
2711
|
+
rejectMissingDigests(`${owner.name}.`, definitions);
|
|
1937
2712
|
return {
|
|
1938
2713
|
table,
|
|
1939
2714
|
primaryKey: Object.hasOwn(owner, "primaryKey") ? owner.primaryKey : tableSchema.primaryKey,
|
|
1940
2715
|
definitions,
|
|
2716
|
+
aliases,
|
|
1941
2717
|
isIgnoringColumns
|
|
1942
2718
|
};
|
|
1943
2719
|
}
|
|
@@ -1965,9 +2741,11 @@ function settleGenerated(model) {
|
|
|
1965
2741
|
if (found === void 0) {
|
|
1966
2742
|
found = find(owner, place.schema);
|
|
1967
2743
|
bindTable(owner, found.table, { isIgnoringColumns: found.isIgnoringColumns });
|
|
1968
|
-
defineAttributeAccessors(owner.prototype, found.definitions.keys());
|
|
2744
|
+
defineAttributeAccessors(owner.prototype, [...found.definitions.keys(), ...found.aliases.keys()]);
|
|
1969
2745
|
defineEnumMethods(owner.prototype, found.definitions);
|
|
1970
2746
|
defineEnumStatics(owner, found.definitions);
|
|
2747
|
+
defineSecurePasswordMethods(owner.prototype, found.definitions);
|
|
2748
|
+
defineSecureTokenMethods(owner.prototype, found.definitions);
|
|
1971
2749
|
settled.set(owner, found);
|
|
1972
2750
|
}
|
|
1973
2751
|
settled.set(model, found);
|
|
@@ -1995,7 +2773,8 @@ function defineGeneratedStatics(root) {
|
|
|
1995
2773
|
const statics = {
|
|
1996
2774
|
table: (model) => generated(model)?.table ?? "",
|
|
1997
2775
|
primaryKey: (model) => generated(model)?.primaryKey ?? "id",
|
|
1998
|
-
attributeDefinitions: (model) => generated(model)?.definitions ?? noAttributes
|
|
2776
|
+
attributeDefinitions: (model) => generated(model)?.definitions ?? noAttributes,
|
|
2777
|
+
attributeAliases: (model) => generated(model)?.aliases ?? noAliases
|
|
1999
2778
|
};
|
|
2000
2779
|
for (const [name, read] of Object.entries(statics)) Object.defineProperty(root, name, {
|
|
2001
2780
|
configurable: true,
|
|
@@ -2034,8 +2813,14 @@ function checkedOverride(where, spec, override) {
|
|
|
2034
2813
|
/** A table's attribute specs with `overrides` applied; throws `InvalidModel` for a bad one. */
|
|
2035
2814
|
function specsFor(name, table, overrides) {
|
|
2036
2815
|
const changes = /* @__PURE__ */ new Map();
|
|
2037
|
-
|
|
2816
|
+
const virtual = {};
|
|
2817
|
+
const given = Object.entries(overrides).filter(([, override]) => !isAlias(override));
|
|
2818
|
+
for (const [attribute, override] of given) {
|
|
2038
2819
|
if (override === void 0) continue;
|
|
2820
|
+
if (isVirtual(override)) {
|
|
2821
|
+
virtual[attribute] = virtualSpec(name, attribute, table, override);
|
|
2822
|
+
continue;
|
|
2823
|
+
}
|
|
2039
2824
|
if (!Object.hasOwn(table.attributes, attribute)) throw new InvalidModel(`${name} has no attribute ${attribute} to override`);
|
|
2040
2825
|
if (override === false && attribute === table.primaryKey) throw new InvalidModel(`${name}.${attribute} is the primary key, so it can't be ignored`);
|
|
2041
2826
|
changes.set(attribute, checked(name, attribute, override));
|
|
@@ -2047,8 +2832,27 @@ function specsFor(name, table, overrides) {
|
|
|
2047
2832
|
specs[attribute] = change === void 0 ? spec : checkedOverride(`${name}.${attribute}`, spec, change);
|
|
2048
2833
|
}
|
|
2049
2834
|
return {
|
|
2050
|
-
specs
|
|
2835
|
+
specs: {
|
|
2836
|
+
...specs,
|
|
2837
|
+
...virtual
|
|
2838
|
+
},
|
|
2051
2839
|
isIgnoringColumns: [...changes.values()].includes(false)
|
|
2052
2840
|
};
|
|
2053
2841
|
}
|
|
2054
|
-
|
|
2842
|
+
/** Whether an override declares a virtual attribute (#356): an object with `virtual: true`. */
|
|
2843
|
+
function isVirtual(override) {
|
|
2844
|
+
return typeof override === "object" && override !== null && "virtual" in override && override.virtual === true;
|
|
2845
|
+
}
|
|
2846
|
+
/**
|
|
2847
|
+
* A virtual attribute's spec (#356), checked: not a column's name, a whole spec with its type,
|
|
2848
|
+
* and non-null only with a default, since nothing loads a value for it.
|
|
2849
|
+
*/
|
|
2850
|
+
function virtualSpec(name, attribute, table, spec) {
|
|
2851
|
+
const where = `${name}.${attribute}`;
|
|
2852
|
+
if (Object.hasOwn(table.attributes, attribute)) throw new InvalidModel(`${where} is virtual, but ${name}'s table has a column for it; rename it, or drop virtual`);
|
|
2853
|
+
if (!isSpecOverride(spec) || spec.type === void 0) throw new InvalidModel(`${where}: a virtual attribute is { type, virtual: true, null?, default? }`);
|
|
2854
|
+
const problem = specProblem(where, spec) ?? virtualNullProblem(where, spec);
|
|
2855
|
+
if (problem !== void 0) throw new InvalidModel(problem);
|
|
2856
|
+
return spec;
|
|
2857
|
+
}
|
|
2858
|
+
export { FilteredMark as $, authenticateBy as A, tableize as At, RecordState as B, Filtered as C, isIgnoringColumns as Ct, isFiltered as D, requireModelName as Dt, filteredValues as E, rejectAbstract as Et, rejectMissingDigests as F, columnOf as G, state as H, resetPurposeOf as I, requireDefined as J, define as K, resetTokenDefinitions as L, hashPasswords as M, staticBelow as Mt, passwordConfirmations as N, shownKey as O, requireTableName as Ot, passwordFailures as P, fullMessageOf as Q, secretAttributeNames as R, FILTERED as S, inferTableNames as St, defaultFilterAttributes as T, ownValueSetter as Tt, attributeOf as U, linksOf as V, attributesForColumn as W, addFailure as X, Errors as Y, clearErrors as Z, isLocking as _, declared as _t, isGenerated as a, specProblem as at, isThenable as b, defineModelName as bt, methodsOffFixes as c, generateTokens as ct, enumNameProblem as d, defineType as dt, inspectCustom as et, enumScopeNames as f, aliasesIn as ft, withArticle as g, declare as gt, noMatch as h, withAttributeNames as ht, isBase as i, humanAttributeName as it, defineSecurePasswordMethods as j, ancestors as jt, shownValue as k, tableOwnerModelName as kt, defineEnumMethods as l, expiryAfter as lt, castInherited as m, isAlias as mt, defineGeneratedStatics as n, styled as nt, schemaAdapter as o, defineSecureTokenMethods as ot, attributeFor as p, attributeName as pt, initialValues as q, hasSettledAttributes as r, attributesNamedInMessages as rt, settleGenerated as s, generateSecureToken as st, defineAttributeAccessors as t, printed as tt, defineEnumStatics as u, secondsOf as ut, lockVersion as v, declaredByClass as vt, boundValue as w, modelNameOf as wt, refuseThenable as x, explainMissingTable as xt, checkNormalizedName as y, seal as yt, withSecurePasswords as z };
|