@forestfuture/active-record 0.8.2 → 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-D3nP3g83.mjs → batch-Ca1JtVcK.mjs} +3255 -2527
- 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-CgEQfuyD.mjs → for-adapters-D35a5x3t.mjs} +6 -3
- package/dist/{for-adapters-DAn1wSYz.d.mts → for-adapters-DoyXc8Dq.d.mts} +1 -1
- package/dist/{generated-model-FB7oT7V1.mjs → generated-model-L4WAqgOZ.mjs} +1949 -1149
- package/dist/{epoch-storage-C7186hd1.mjs → identifiers-CzqYL_nC.mjs} +248 -223
- package/dist/{index-BfX3Dgy_.d.mts → index-Fq4gT3c8.d.mts} +115 -96
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +5 -5
- package/dist/metadata-BIUbGJlS.d.mts +363 -0
- package/dist/{plugin-BY2QaRpq.mjs → plugin-BHUP4ssD.mjs} +10 -7
- package/dist/{plugin-IHD0I6Rg.mjs → plugin-BMAJKgj6.mjs} +7 -7
- package/dist/postgresql.d.mts +1 -1
- package/dist/postgresql.mjs +28 -4
- package/dist/{src-DnuvSHF6.mjs → src-fYq-nVHE.mjs} +2 -2
- package/dist/{storage-override-BFC-GSR0.mjs → storage-override-yF2NT5ST.mjs} +1 -1
- package/dist/{validations-DFLjJ203.d.mts → validations-CKPJoSj4.d.mts} +290 -103
- package/llms-full.txt +8280 -4094
- package/package.json +1 -1
- package/skills/active-record/SKILL.md +4 -3
- package/dist/for-adapters-l4rNitkK.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) {
|
|
@@ -238,168 +238,285 @@ function listsOf(lists, model) {
|
|
|
238
238
|
lists.set(model, found);
|
|
239
239
|
return found;
|
|
240
240
|
}
|
|
241
|
-
// src/
|
|
242
|
-
/**
|
|
243
|
-
function
|
|
244
|
-
return
|
|
245
|
-
if (definition.enum === void 0) return [];
|
|
246
|
-
const before = affix(attribute, definition.prefix);
|
|
247
|
-
const after = affix(attribute, definition.suffix);
|
|
248
|
-
return enumEntries(definition.enum).map(([name]) => {
|
|
249
|
-
const stem = `${before}${methodPart(name)}${after}`;
|
|
250
|
-
const records = [
|
|
251
|
-
`is${stem}`,
|
|
252
|
-
`saveAs${stem}`,
|
|
253
|
-
`saveAs${stem}OrThrow`
|
|
254
|
-
];
|
|
255
|
-
const scopes = [uncapitalized(stem), `not${stem}`];
|
|
256
|
-
return {
|
|
257
|
-
attribute,
|
|
258
|
-
name,
|
|
259
|
-
records: definition.instanceMethods === false ? [] : records,
|
|
260
|
-
scopes: definition.scopes === false ? [] : scopes
|
|
261
|
-
};
|
|
262
|
-
});
|
|
263
|
-
});
|
|
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;
|
|
264
245
|
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
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;
|
|
268
258
|
}
|
|
269
|
-
/**
|
|
270
|
-
|
|
271
|
-
|
|
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`;
|
|
272
270
|
}
|
|
273
|
-
/**
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
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
277
|
}
|
|
278
|
-
const capitalized = (text) => text.charAt(0).toUpperCase() + text.slice(1);
|
|
279
|
-
const uncapitalized = (text) => text.charAt(0).toLowerCase() + text.slice(1);
|
|
280
278
|
/**
|
|
281
|
-
*
|
|
282
|
-
*
|
|
283
|
-
* changes too, as Rails' `published!` does.
|
|
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`.
|
|
284
281
|
*/
|
|
285
|
-
function
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
defineMethod(prototype, throwingSetter, function() {
|
|
296
|
-
return this.updateOrThrow({ [attribute]: name });
|
|
297
|
-
});
|
|
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);
|
|
298
292
|
}
|
|
293
|
+
return Object.fromEntries([...givenAs].map(([name, given]) => [name, values[given]]));
|
|
299
294
|
}
|
|
295
|
+
// src/password-algorithm.ts
|
|
300
296
|
/**
|
|
301
|
-
*
|
|
302
|
-
*
|
|
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.
|
|
303
299
|
*/
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
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);
|
|
315
320
|
}
|
|
316
|
-
}
|
|
317
|
-
/** Puts `method` on `target` as `name`, writable as a declared method is, and names it unless told not to. */
|
|
318
|
-
function defineMethod(target, name, method, { named = true } = {}) {
|
|
319
|
-
if (Object.hasOwn(target, name)) return;
|
|
320
|
-
if (named) Object.defineProperty(method, "name", { value: name });
|
|
321
|
-
Object.defineProperty(target, name, {
|
|
322
|
-
value: method,
|
|
323
|
-
writable: true,
|
|
324
|
-
configurable: true
|
|
325
|
-
});
|
|
326
|
-
}
|
|
327
|
-
/** The scope statics `defineEnumStatics` made, so a static a Model declares itself is told apart. */
|
|
328
|
-
const enumScopes = /* @__PURE__ */ new WeakSet();
|
|
321
|
+
};
|
|
329
322
|
/**
|
|
330
|
-
*
|
|
331
|
-
*
|
|
332
|
-
* the Model declares itself. Rails refuses the same when an enum is declared.
|
|
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.
|
|
333
325
|
*/
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
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)
|
|
338
336
|
};
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
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();
|
|
353
367
|
}
|
|
354
368
|
}
|
|
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();
|
|
355
372
|
/**
|
|
356
|
-
*
|
|
357
|
-
*
|
|
358
|
-
*
|
|
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.
|
|
359
376
|
*/
|
|
360
|
-
function
|
|
361
|
-
|
|
362
|
-
const
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
return reserved === void 0 ? void 0 : `${model.name}'s enum ${attribute} gives a scope named "${reserved}", which is a reserved word; ${fix}`;
|
|
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;
|
|
371
387
|
}
|
|
372
|
-
/**
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
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`);
|
|
377
402
|
}
|
|
378
|
-
/** `
|
|
379
|
-
function
|
|
380
|
-
|
|
381
|
-
return fix === void 0 ? "" : `, or leave ${attribute}'s methods off (remove ${fix})`;
|
|
403
|
+
/** Whether `value` is a type `defineType` made. */
|
|
404
|
+
function isCustomType(value) {
|
|
405
|
+
return typeof value === "object" && value !== null && defined.has(value);
|
|
382
406
|
}
|
|
383
|
-
|
|
384
|
-
const
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
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)}`;
|
|
389
487
|
}
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
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));
|
|
394
498
|
}
|
|
395
499
|
}
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
if (
|
|
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
|
+
});
|
|
403
520
|
}
|
|
404
521
|
}
|
|
405
522
|
// src/spec-keys.ts
|
|
@@ -489,8 +606,75 @@ const rules = {
|
|
|
489
606
|
isGiven: isGivenUnless(false),
|
|
490
607
|
requires: "enum",
|
|
491
608
|
onRetype: "drop"
|
|
492
|
-
}
|
|
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()
|
|
493
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
|
+
}
|
|
494
678
|
/** The rule for a decimal's precision or scale: a whole number of digits. */
|
|
495
679
|
function decimalDigits(describedAs) {
|
|
496
680
|
return {
|
|
@@ -644,1171 +828,1751 @@ function copiedKeys(spec) {
|
|
|
644
828
|
const copied = entries.filter(([key, rule]) => rule.copiedToDefinition !== false && givenValue(spec, key) !== void 0).map(([key]) => [key, spec[key]]);
|
|
645
829
|
return Object.fromEntries(copied);
|
|
646
830
|
}
|
|
647
|
-
// src/
|
|
648
|
-
/**
|
|
649
|
-
const
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
}
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
}
|
|
685
|
-
|
|
686
|
-
/**
|
|
687
|
-
function
|
|
688
|
-
return
|
|
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;
|
|
689
873
|
}
|
|
690
|
-
/**
|
|
691
|
-
function
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
if (isCustomType(spec)) return {
|
|
697
|
-
...resolvedType(spec),
|
|
698
|
-
column: underscore(name)
|
|
874
|
+
/** One class's `errorMessages` calls as one: a later call's message wins, type by type. */
|
|
875
|
+
function mergedCalls(calls) {
|
|
876
|
+
const attributes = {};
|
|
877
|
+
for (const call of calls) for (const [name, types] of Object.entries(call.attributes ?? {})) attributes[name] = {
|
|
878
|
+
...attributes[name],
|
|
879
|
+
...types
|
|
699
880
|
};
|
|
700
|
-
return {
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
881
|
+
return Object.assign({}, ...calls, { attributes });
|
|
882
|
+
}
|
|
883
|
+
const catalogs = /* @__PURE__ */ new WeakMap();
|
|
884
|
+
/** A Model's catalog, built once it's sealed; before that, built afresh, as declarations can still come. */
|
|
885
|
+
function catalogOf(model) {
|
|
886
|
+
const kept = catalogs.get(model);
|
|
887
|
+
if (kept !== void 0) return kept;
|
|
888
|
+
const names = /* @__PURE__ */ new Map();
|
|
889
|
+
for (const { values } of declaredByClass(model, "humanAttributeNames").toReversed()) for (const value of values) for (const [attribute, name] of Object.entries(value)) names.set(attribute, name);
|
|
890
|
+
const catalog = {
|
|
891
|
+
messages: [...declaredByClass(model, "errorMessages").map(({ values }) => mergedCalls(values)), builtInMessages],
|
|
892
|
+
names
|
|
704
893
|
};
|
|
894
|
+
if (isSealed(model)) catalogs.set(model, catalog);
|
|
895
|
+
return catalog;
|
|
705
896
|
}
|
|
706
|
-
/**
|
|
707
|
-
function
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
897
|
+
/** The message for a type: for the attribute, then the class's own, nearest class first. */
|
|
898
|
+
function templateFor(model, attribute, type) {
|
|
899
|
+
if (type === "attributes") return void 0;
|
|
900
|
+
for (const messages of catalogOf(model).messages) {
|
|
901
|
+
const found = ownValue(ownValue(messages.attributes, attribute), type) ?? ownValue(messages, type);
|
|
902
|
+
if (found !== void 0) return found;
|
|
903
|
+
}
|
|
712
904
|
}
|
|
713
|
-
/**
|
|
714
|
-
function
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
return
|
|
905
|
+
/** The text of a message: the form the entry names, or else the plural form for `count`. */
|
|
906
|
+
function messageText(template, entry) {
|
|
907
|
+
if (template === void 0 || typeof template === "string") return template;
|
|
908
|
+
const { count } = entry.values;
|
|
909
|
+
return ownValue(template, entry.form ?? (typeof count === "number" ? plurals.select(count) : "other")) ?? template.other;
|
|
718
910
|
}
|
|
719
|
-
/**
|
|
720
|
-
function
|
|
721
|
-
|
|
911
|
+
/** "createdAt" → "Created at" */
|
|
912
|
+
function inWords(name) {
|
|
913
|
+
const words = underscore(name).replaceAll(/[_.]/g, " ");
|
|
914
|
+
return words.charAt(0).toUpperCase() + words.slice(1);
|
|
722
915
|
}
|
|
723
|
-
/**
|
|
724
|
-
function
|
|
725
|
-
|
|
916
|
+
/** An attribute's name as messages show it: a class's `humanAttributeNames`, or "Created at". */
|
|
917
|
+
function humanAttributeName(model, attribute) {
|
|
918
|
+
return catalogOf(model).names.get(attribute) ?? inWords(attribute);
|
|
726
919
|
}
|
|
727
|
-
/**
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
920
|
+
/** An attribute's value as `%{value}` shows it. */
|
|
921
|
+
function shownValue$1(source, attribute) {
|
|
922
|
+
if (attribute === "base") return "";
|
|
923
|
+
const value = source.read(attribute);
|
|
924
|
+
if (value === null || value === void 0) return "";
|
|
925
|
+
if (isFiltered(source.model, attribute)) return FILTERED;
|
|
926
|
+
if (value instanceof Date) return value.toISOString();
|
|
927
|
+
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
733
928
|
}
|
|
734
|
-
/**
|
|
735
|
-
function
|
|
736
|
-
|
|
929
|
+
/** An entry's message: given, or looked up now, with its `%{name}` placeholders filled in. */
|
|
930
|
+
function messageOf(source, entry) {
|
|
931
|
+
if (entry.message !== void 0) return entry.message;
|
|
932
|
+
const { model } = source;
|
|
933
|
+
const text = messageText(templateFor(model, entry.attribute, entry.type), entry);
|
|
934
|
+
if (text === void 0) throw missingMessage(model, entry);
|
|
935
|
+
return text.replace(/%\{(\w+)\}/g, (placeholder, name) => {
|
|
936
|
+
if (name === "attribute") return String(ownValue(entry.values, name) ?? humanAttributeName(model, entry.attribute));
|
|
937
|
+
if (name === "model") return inWords(model.modelName);
|
|
938
|
+
if (name === "value") return shownValue$1(source, entry.attribute);
|
|
939
|
+
return String(ownValue(entry.values, name) ?? placeholder);
|
|
940
|
+
});
|
|
737
941
|
}
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
const
|
|
741
|
-
|
|
742
|
-
* Rails' default `filter_parameters` for a new app: an attribute whose snake_case name holds
|
|
743
|
-
* one of these, in any case, is filtered (`passwordDigest`, `apiKey`, `resetToken`, `email`).
|
|
744
|
-
*/
|
|
745
|
-
const defaultFilterAttributes = [
|
|
746
|
-
"passw",
|
|
747
|
-
"email",
|
|
748
|
-
"secret",
|
|
749
|
-
"token",
|
|
750
|
-
"_key",
|
|
751
|
-
"crypt",
|
|
752
|
-
"salt",
|
|
753
|
-
"certificate",
|
|
754
|
-
"otp",
|
|
755
|
-
"ssn",
|
|
756
|
-
"cvv",
|
|
757
|
-
"cvc"
|
|
758
|
-
];
|
|
759
|
-
/**
|
|
760
|
-
* Whether `attribute`'s values are hidden from listeners: its snake_case name holds a string
|
|
761
|
-
* entry lowercased, or read in snake_case (`"apiKey"` as `api_key`, #397), or a RegExp entry
|
|
762
|
-
* matches the attribute or its snake_case name.
|
|
763
|
-
*/
|
|
764
|
-
function isFiltered(model, attribute) {
|
|
765
|
-
const name = underscore(attribute);
|
|
766
|
-
return model.filterAttributes.some((entry) => typeof entry === "string" ? name.includes(entry.toLowerCase()) || name.includes(underscore(entry)) : attribute.search(entry) !== -1 || name.search(entry) !== -1);
|
|
942
|
+
/** The error for a type no class has a message for. */
|
|
943
|
+
function missingMessage(model, entry) {
|
|
944
|
+
const where = `${model.name}'s errorMessages, or a class it extends`;
|
|
945
|
+
return /* @__PURE__ */ new TypeError(`No message for the error "${entry.type}" on "${entry.attribute}": add one to ${where}, as ${entry.type} or attributes.${entry.attribute}.${entry.type}`);
|
|
767
946
|
}
|
|
768
|
-
/** The
|
|
769
|
-
function
|
|
770
|
-
return
|
|
947
|
+
/** The attributes each class names in its `errorMessages` or `humanAttributeNames`, nearest class first. */
|
|
948
|
+
function attributesNamedInMessages(model) {
|
|
949
|
+
return [...declaredByClass(model, "errorMessages").map(({ from, values }) => ({
|
|
950
|
+
from,
|
|
951
|
+
declaration: "errorMessages",
|
|
952
|
+
names: values.flatMap((value) => Object.keys(value.attributes ?? {}))
|
|
953
|
+
})), ...declaredByClass(model, "humanAttributeNames").map(({ from, values }) => ({
|
|
954
|
+
from,
|
|
955
|
+
declaration: "humanAttributeNames",
|
|
956
|
+
names: values.flatMap((value) => Object.keys(value))
|
|
957
|
+
}))];
|
|
771
958
|
}
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
959
|
+
// src/inspect-support.ts
|
|
960
|
+
/** Node and workerd call a value's inspector under this registered symbol. */
|
|
961
|
+
const inspectCustom = Symbol.for("nodejs.util.inspect.custom");
|
|
962
|
+
/** Text in the color of a special value, or plain when colors are off. */
|
|
963
|
+
function styled(options, text) {
|
|
964
|
+
return options.stylize ? options.stylize(text, "special") : text;
|
|
965
|
+
}
|
|
966
|
+
/** A filtered value's stand-in: prints unquoted, so it isn't taken for a string, as a special value. */
|
|
967
|
+
var FilteredMark = class {
|
|
968
|
+
#changed;
|
|
969
|
+
constructor(changed) {
|
|
970
|
+
this.#changed = changed;
|
|
971
|
+
}
|
|
972
|
+
[inspectCustom](_depth, options) {
|
|
973
|
+
return styled(options, FILTERED) + (this.#changed ? " (changed)" : "");
|
|
779
974
|
}
|
|
780
975
|
};
|
|
781
|
-
/** A primary key as an error shows it: "[FILTERED]" when the key is a filtered attribute. */
|
|
782
|
-
function shownKey(model, key) {
|
|
783
|
-
return isFiltered(model, model.primaryKey) ? FILTERED : String(key);
|
|
784
|
-
}
|
|
785
|
-
/** The value D1 binds. */
|
|
786
|
-
function boundValue(param) {
|
|
787
|
-
return param instanceof Filtered ? param.value : param;
|
|
788
|
-
}
|
|
789
|
-
/** The value listeners see. */
|
|
790
|
-
function shownValue$1(param) {
|
|
791
|
-
return param instanceof Filtered ? param.shown : param;
|
|
792
|
-
}
|
|
793
|
-
// src/attribute.ts
|
|
794
|
-
/** What `condition()` and `conditionCell()` give for a value that can't match anything. */
|
|
795
|
-
const noMatch = uncastable;
|
|
796
976
|
/**
|
|
797
|
-
*
|
|
798
|
-
*
|
|
799
|
-
* stored are known here, so a caller only says what the value is for.
|
|
977
|
+
* `label` and the runtime's own `inspect` of `body`, which is built only when there is depth left;
|
|
978
|
+
* otherwise `[name]`, as Node prints any class instance nested too deep.
|
|
800
979
|
*/
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
980
|
+
function printed(label, name, body, { depth, options, inspect }) {
|
|
981
|
+
if (depth < 0) return styled(options, `[${name}]`);
|
|
982
|
+
return `${label} ${inspect(body(), {
|
|
983
|
+
...options,
|
|
984
|
+
depth
|
|
985
|
+
})}`;
|
|
986
|
+
}
|
|
987
|
+
// src/errors-collection.ts
|
|
988
|
+
/** @internal The library's key for emptying an errors collection. */
|
|
989
|
+
const clearErrors = Symbol("clearErrors");
|
|
990
|
+
/** @internal The library's key for adding a failure it found, with an optional message to use as it is. */
|
|
991
|
+
const addFailure = Symbol("addFailure");
|
|
992
|
+
/** @internal The library's key for a failure's full message, without adding it (`strict`). */
|
|
993
|
+
const fullMessageOf = Symbol("fullMessageOf");
|
|
994
|
+
/** A record's validation errors: `record.errors`. Cleared at the start of each validation run. */
|
|
995
|
+
var Errors = class {
|
|
996
|
+
#entries = [];
|
|
997
|
+
#source;
|
|
998
|
+
/** @internal Made by the library for each record. */
|
|
999
|
+
constructor(source) {
|
|
1000
|
+
this.#source = source;
|
|
820
1001
|
}
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
1002
|
+
add(attribute, message, options = {}) {
|
|
1003
|
+
if (typeof message === "string") {
|
|
1004
|
+
this.#entries.push({
|
|
1005
|
+
attribute,
|
|
1006
|
+
type: options.type ?? "invalid",
|
|
1007
|
+
values: {},
|
|
1008
|
+
message
|
|
1009
|
+
});
|
|
1010
|
+
return;
|
|
1011
|
+
}
|
|
1012
|
+
const { type, ...values } = message;
|
|
1013
|
+
if (typeof type !== "string") throw new TypeError("errors.add needs a message or a type");
|
|
1014
|
+
const entry = {
|
|
1015
|
+
attribute,
|
|
1016
|
+
type,
|
|
1017
|
+
values
|
|
1018
|
+
};
|
|
1019
|
+
messageOf(this.#source, entry);
|
|
1020
|
+
this.#entries.push(entry);
|
|
824
1021
|
}
|
|
825
|
-
/**
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
* what can't be cast throws `TypeError` naming the Model and attribute, showing the value
|
|
829
|
-
* unless the attribute is filtered (#83).
|
|
830
|
-
*/
|
|
831
|
-
cast(value) {
|
|
832
|
-
requireDefined(this.#model, this.name, value);
|
|
833
|
-
const cast = this.#convertOrRefuse(value, () => castValue(this.#definition, value));
|
|
834
|
-
if (cast === uncastable && this.#isValidatedEnum()) return value;
|
|
835
|
-
return this.#orRefuse(cast, value);
|
|
1022
|
+
/** The messages for one attribute (always an array). */
|
|
1023
|
+
get(attribute) {
|
|
1024
|
+
return this.#entries.filter((entry) => entry.attribute === attribute).map((entry) => messageOf(this.#source, entry));
|
|
836
1025
|
}
|
|
837
|
-
/**
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
return values !== void 0 && validate !== false;
|
|
1026
|
+
/** Every message with its attribute's human name first: "Email can't be blank". */
|
|
1027
|
+
fullMessages() {
|
|
1028
|
+
return this.#entries.map((entry) => this.#fullMessage(entry));
|
|
841
1029
|
}
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
key(value, association) {
|
|
847
|
-
requireDefined(this.#model, this.name, value);
|
|
848
|
-
return this.#orRefuse(castKey(this.#definition, value), value, association);
|
|
1030
|
+
#fullMessage(entry) {
|
|
1031
|
+
const message = messageOf(this.#source, entry);
|
|
1032
|
+
if (entry.attribute === "base") return message;
|
|
1033
|
+
return `${humanAttributeName(this.#source.model, entry.attribute)} ${message}`;
|
|
849
1034
|
}
|
|
850
|
-
/**
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
1035
|
+
/** Every error as `{ attribute, type, message }`, with its `values` when it has some (copies). */
|
|
1036
|
+
toArray() {
|
|
1037
|
+
return this.#entries.map((entry) => {
|
|
1038
|
+
const { attribute, type, values } = entry;
|
|
1039
|
+
const error = {
|
|
1040
|
+
attribute,
|
|
1041
|
+
type,
|
|
1042
|
+
message: messageOf(this.#source, entry)
|
|
1043
|
+
};
|
|
1044
|
+
return Object.keys(values).length === 0 ? error : {
|
|
1045
|
+
...error,
|
|
1046
|
+
values: { ...values }
|
|
1047
|
+
};
|
|
1048
|
+
});
|
|
857
1049
|
}
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
const cast = this.condition(value);
|
|
861
|
-
return cast === noMatch ? noMatch : this.write(cast);
|
|
1050
|
+
isEmpty() {
|
|
1051
|
+
return this.#entries.length === 0;
|
|
862
1052
|
}
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
* can't write throws `TypeError` naming the attribute, as assigning it would (#146).
|
|
866
|
-
*/
|
|
867
|
-
write(value) {
|
|
868
|
-
let stored;
|
|
869
|
-
try {
|
|
870
|
-
stored = writeValue(this.#definition, value);
|
|
871
|
-
} catch (error) {
|
|
872
|
-
if (this.#definition.customType !== void 0) throw this.#refusal(value, void 0, error);
|
|
873
|
-
if (this.#definition.type !== "json") throw error;
|
|
874
|
-
throw this.#refusal(value);
|
|
875
|
-
}
|
|
876
|
-
if (stored === void 0) throw this.#refusal(value);
|
|
877
|
-
return stored;
|
|
1053
|
+
get size() {
|
|
1054
|
+
return this.#entries.length;
|
|
878
1055
|
}
|
|
879
|
-
/**
|
|
880
|
-
|
|
881
|
-
return
|
|
1056
|
+
/** `Errors [ { attribute, type, message }, … ]`, so a console shows what `#entries` holds (#104). */
|
|
1057
|
+
[inspectCustom](depth, options, inspect) {
|
|
1058
|
+
return printed("Errors", "Errors", () => this.toArray(), {
|
|
1059
|
+
depth,
|
|
1060
|
+
options,
|
|
1061
|
+
inspect
|
|
1062
|
+
});
|
|
882
1063
|
}
|
|
883
|
-
/**
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
return
|
|
1064
|
+
/** @internal Adds an error the library found, such as a validator's, returning its message. */
|
|
1065
|
+
[addFailure](attribute, { values = {}, ...failure }) {
|
|
1066
|
+
const entry = {
|
|
1067
|
+
attribute,
|
|
1068
|
+
values,
|
|
1069
|
+
...failure
|
|
1070
|
+
};
|
|
1071
|
+
this.#entries.push(entry);
|
|
1072
|
+
return messageOf(this.#source, entry);
|
|
892
1073
|
}
|
|
893
|
-
/** A
|
|
894
|
-
|
|
895
|
-
return this
|
|
1074
|
+
/** @internal A failure's full message, as `fullMessages()` would give it, without adding it. */
|
|
1075
|
+
[fullMessageOf](attribute, { values = {}, ...failure }) {
|
|
1076
|
+
return this.#fullMessage({
|
|
1077
|
+
attribute,
|
|
1078
|
+
values,
|
|
1079
|
+
...failure
|
|
1080
|
+
});
|
|
896
1081
|
}
|
|
897
|
-
/**
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
* Rails' do, and one that can't be cast is the same as nothing (#20).
|
|
901
|
-
*/
|
|
902
|
-
isSame(a, b) {
|
|
903
|
-
const [x, y] = [this.#comparable(a), this.#comparable(b)];
|
|
904
|
-
if (x === noMatch || y === noMatch) return false;
|
|
905
|
-
return isSameCell(writeValue(this.#definition, x), writeValue(this.#definition, y));
|
|
1082
|
+
/** @internal Called at the start of each validation run. */
|
|
1083
|
+
[clearErrors]() {
|
|
1084
|
+
this.#entries = [];
|
|
906
1085
|
}
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
1086
|
+
};
|
|
1087
|
+
// src/loaded-associations.ts
|
|
1088
|
+
/**
|
|
1089
|
+
* The associations one record has loaded (preloaded, read, or set by a write): a record, an
|
|
1090
|
+
* array of records, or null. Each stays loaded while the owner's attribute still holds the key
|
|
1091
|
+
* it was loaded for, and a load overtaken by a change to its association isn't kept.
|
|
1092
|
+
*/
|
|
1093
|
+
var LoadedAssociations = class {
|
|
1094
|
+
/** The owner's attribute value now, which an entry's key is checked against. */
|
|
1095
|
+
#keyOf;
|
|
1096
|
+
#entries = /* @__PURE__ */ new Map();
|
|
1097
|
+
/** Counted when an association changes, by name and record-wide, so a stale load isn't kept. */
|
|
1098
|
+
#loadsDiscarded = /* @__PURE__ */ new Map();
|
|
1099
|
+
#allLoadsDiscarded = 0;
|
|
1100
|
+
constructor(keyOf) {
|
|
1101
|
+
this.#keyOf = keyOf;
|
|
915
1102
|
}
|
|
916
|
-
/**
|
|
917
|
-
|
|
918
|
-
|
|
1103
|
+
/** The loaded association, if it was loaded for the key the owner holds now. */
|
|
1104
|
+
get(name) {
|
|
1105
|
+
const entry = this.#entries.get(name);
|
|
1106
|
+
if (entry === void 0 || !isSameKey(this.#key(entry.attribute), entry.key)) return void 0;
|
|
1107
|
+
return entry;
|
|
919
1108
|
}
|
|
920
1109
|
/**
|
|
921
|
-
*
|
|
922
|
-
*
|
|
923
|
-
* time, since `filterAttributes` is a static a Model may set after this was resolved.
|
|
1110
|
+
* Sets the association to what a write or preload made it, for the key `attribute` holds now;
|
|
1111
|
+
* loads of it already sent won't be kept.
|
|
924
1112
|
*/
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
1113
|
+
set(name, attribute, value) {
|
|
1114
|
+
this.#entries.set(name, {
|
|
1115
|
+
attribute,
|
|
1116
|
+
key: this.#key(attribute),
|
|
1117
|
+
value
|
|
1118
|
+
});
|
|
1119
|
+
this.#discardPendingLoads(name);
|
|
932
1120
|
}
|
|
933
1121
|
/**
|
|
934
|
-
*
|
|
935
|
-
*
|
|
1122
|
+
* Starts a load of the association, before its query is sent, for the key its query was built
|
|
1123
|
+
* for (the attributes' values now, unless it's given): the function it returns keeps the loaded value only if nothing changed the association
|
|
1124
|
+
* meanwhile (#181).
|
|
936
1125
|
*/
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
1126
|
+
startLoad(name, attribute, key = this.#key(attribute)) {
|
|
1127
|
+
const generation = this.#generation(name);
|
|
1128
|
+
return (value) => {
|
|
1129
|
+
if (this.#generation(name) === generation) this.#entries.set(name, {
|
|
1130
|
+
attribute,
|
|
1131
|
+
key,
|
|
1132
|
+
value
|
|
1133
|
+
});
|
|
1134
|
+
};
|
|
944
1135
|
}
|
|
945
|
-
/**
|
|
946
|
-
|
|
947
|
-
|
|
1136
|
+
/** Forgets the association; loads of it already sent won't be kept. */
|
|
1137
|
+
clear(name) {
|
|
1138
|
+
this.#entries.delete(name);
|
|
1139
|
+
this.#discardPendingLoads(name);
|
|
1140
|
+
}
|
|
1141
|
+
/** Forgets every association (`reload()`); loads already sent won't be kept. */
|
|
1142
|
+
clearAll() {
|
|
1143
|
+
this.#entries.clear();
|
|
1144
|
+
this.#allLoadsDiscarded += 1;
|
|
1145
|
+
}
|
|
1146
|
+
#key(attribute) {
|
|
1147
|
+
if (typeof attribute !== "string") return attribute.map((each) => this.#keyOf(each) ?? null);
|
|
1148
|
+
return this.#keyOf(attribute) ?? null;
|
|
1149
|
+
}
|
|
1150
|
+
#discardPendingLoads(name) {
|
|
1151
|
+
this.#loadsDiscarded.set(name, (this.#loadsDiscarded.get(name) ?? 0) + 1);
|
|
948
1152
|
}
|
|
949
1153
|
/**
|
|
950
|
-
*
|
|
951
|
-
*
|
|
952
|
-
* cell that isn't JSON (#146). A custom type's own error is its cause, unless the attribute is
|
|
953
|
-
* filtered: the error may show the value (#20).
|
|
1154
|
+
* Changes with each change to the association, so a load can tell whether it's still current.
|
|
1155
|
+
* The two counts are summed, so `clearAll()` makes every name stale without touching the map.
|
|
954
1156
|
*/
|
|
955
|
-
#
|
|
956
|
-
|
|
957
|
-
const text = hidden ? FILTERED : shown(value);
|
|
958
|
-
const from = association === void 0 ? "" : `, the key of ${association}`;
|
|
959
|
-
return new TypeError(`${this.#model.name}: ${text} isn't ${this.#described()} for "${this.name}"${from}`, hidden || cause === void 0 ? void 0 : { cause });
|
|
960
|
-
}
|
|
961
|
-
/** What a value of the attribute is, as a refusal says it: `a boolean`, `one of "draft", "published"`. */
|
|
962
|
-
#described() {
|
|
963
|
-
const { type, enum: values, customType } = this.#definition;
|
|
964
|
-
if (values !== void 0) return `one of ${listedNames(values)}`;
|
|
965
|
-
if (customType !== void 0) return "a valid value";
|
|
966
|
-
return valueNames[type] ?? withArticle(type);
|
|
1157
|
+
#generation(name) {
|
|
1158
|
+
return this.#allLoadsDiscarded + (this.#loadsDiscarded.get(name) ?? 0);
|
|
967
1159
|
}
|
|
968
1160
|
};
|
|
969
|
-
|
|
1161
|
+
/** Whether two keys are the same: one value, or each of a list's (#60). */
|
|
1162
|
+
function isSameKey(now, loaded) {
|
|
1163
|
+
if (!Array.isArray(now) || !Array.isArray(loaded)) return Object.is(now, loaded);
|
|
1164
|
+
return now.every((each, index) => Object.is(each, loaded[index]));
|
|
1165
|
+
}
|
|
1166
|
+
// src/pending-autosaves.ts
|
|
970
1167
|
/**
|
|
971
|
-
* The
|
|
972
|
-
*
|
|
1168
|
+
* The records saving one record may also save: those built through its hasMany and hasOne
|
|
1169
|
+
* associations or pushed onto a hasMany, after it (`autosavesOf` says which), and the new ones
|
|
1170
|
+
* its belongsTo associations point at, before it.
|
|
973
1171
|
*/
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
1172
|
+
var PendingAutosaves = class {
|
|
1173
|
+
#built = /* @__PURE__ */ new Map();
|
|
1174
|
+
#belongsTo = /* @__PURE__ */ new Map();
|
|
1175
|
+
/** A record built through one of this record's hasMany or hasOne associations. */
|
|
1176
|
+
addBuilt(name, record) {
|
|
1177
|
+
this.#built.set(name, [...this.#built.get(name) ?? [], record]);
|
|
979
1178
|
}
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
1179
|
+
/** Takes `records` out of those built through the association (`delete`, `destroy`). */
|
|
1180
|
+
removeBuilt(name, records) {
|
|
1181
|
+
const kept = this.built(name).filter((record) => !records.includes(record));
|
|
1182
|
+
this.#built.set(name, kept);
|
|
984
1183
|
}
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
* The values a record built from a Relation inherits from its conditions, cast as keys are: a
|
|
989
|
-
* hasMany's foreign key names its association (`link`) when it can't be cast.
|
|
990
|
-
*/
|
|
991
|
-
function castInherited(model, inherited, link) {
|
|
992
|
-
return Object.fromEntries(Object.entries(inherited).map(([attribute, value]) => {
|
|
993
|
-
const association = attribute === link?.attribute ? link.association : void 0;
|
|
994
|
-
return [attribute, attributeFor(model, attribute).key(value, association)];
|
|
995
|
-
}));
|
|
996
|
-
}
|
|
997
|
-
/** A word with `a` or `an` before it, as a message reads it: `an integer`, `a string`. */
|
|
998
|
-
function withArticle(word) {
|
|
999
|
-
return `${/^[aeiou]/.test(word) ? "an" : "a"} ${word}`;
|
|
1000
|
-
}
|
|
1001
|
-
/** How much of a value an error shows: it came from outside, and errors are often logged. */
|
|
1002
|
-
const SHOWN_LENGTH = 60;
|
|
1003
|
-
/** What a value of an attribute type is called in a refusal, where `a`/`an` and its name isn't it. */
|
|
1004
|
-
const valueNames = {
|
|
1005
|
-
json: "a JSON value",
|
|
1006
|
-
binary: "binary data"
|
|
1007
|
-
};
|
|
1008
|
-
/** A value as an error shows it: JSON where it has one, numbers as written, and at most 60 characters. */
|
|
1009
|
-
function shown(value) {
|
|
1010
|
-
const text = textOf(value);
|
|
1011
|
-
return text.length > SHOWN_LENGTH ? `${text.slice(0, SHOWN_LENGTH)}…` : text;
|
|
1012
|
-
}
|
|
1013
|
-
function textOf(value) {
|
|
1014
|
-
if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return `<${value.constructor.name} of ${value.byteLength} bytes>`;
|
|
1015
|
-
if (value instanceof Blob) return `<${value.constructor.name} of ${value.size} bytes>`;
|
|
1016
|
-
if (typeof value === "number" || isInvalidDate(value)) return String(value);
|
|
1017
|
-
try {
|
|
1018
|
-
return JSON.stringify(value) ?? String(value);
|
|
1019
|
-
} catch {
|
|
1020
|
-
return plainText(value);
|
|
1184
|
+
/** A hasOne's one record to save with this record, replacing any before it. */
|
|
1185
|
+
setBuilt(name, record) {
|
|
1186
|
+
this.#built.set(name, [record]);
|
|
1021
1187
|
}
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
try {
|
|
1026
|
-
return String(value);
|
|
1027
|
-
} catch {
|
|
1028
|
-
return Object.prototype.toString.call(value);
|
|
1188
|
+
/** The records built through the association, in the order they were built. */
|
|
1189
|
+
built(name) {
|
|
1190
|
+
return this.#built.get(name) ?? [];
|
|
1029
1191
|
}
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
greaterThan: "must be greater than %{count}",
|
|
1057
|
-
greaterThanOrEqualTo: "must be greater than or equal to %{count}",
|
|
1058
|
-
lessThan: "must be less than %{count}",
|
|
1059
|
-
lessThanOrEqualTo: "must be less than or equal to %{count}",
|
|
1060
|
-
equalTo: "must be equal to %{count}",
|
|
1061
|
-
otherThan: "must be other than %{count}",
|
|
1062
|
-
restrictDependentDestroy: {
|
|
1063
|
-
hasOne: "Cannot delete record because a dependent %{record} exists",
|
|
1064
|
-
hasMany: "Cannot delete record because dependent %{record} exist"
|
|
1192
|
+
/** Every association's built records, by association name. */
|
|
1193
|
+
allBuilt() {
|
|
1194
|
+
return [...this.#built];
|
|
1195
|
+
}
|
|
1196
|
+
/** A new record a belongsTo points at, saved first when this record is; undefined clears it. */
|
|
1197
|
+
setBelongsTo(name, record) {
|
|
1198
|
+
if (record === void 0) this.#belongsTo.delete(name);
|
|
1199
|
+
else this.#belongsTo.set(name, record);
|
|
1200
|
+
}
|
|
1201
|
+
/** The new records this record's belongsTo associations point at, by association name. */
|
|
1202
|
+
allBelongsTo() {
|
|
1203
|
+
return [...this.#belongsTo];
|
|
1204
|
+
}
|
|
1205
|
+
/** Whether there are none: saving the record saves no other record with it. */
|
|
1206
|
+
isEmpty() {
|
|
1207
|
+
return [...this.#built.values()].every((records) => records.length === 0) && this.#belongsTo.size === 0;
|
|
1208
|
+
}
|
|
1209
|
+
/** Forgets what was built through the association or set on it (`reloadAssociation`). */
|
|
1210
|
+
clear(name) {
|
|
1211
|
+
this.#built.delete(name);
|
|
1212
|
+
this.#belongsTo.delete(name);
|
|
1213
|
+
}
|
|
1214
|
+
/** Forgets every association's (`reload()`). */
|
|
1215
|
+
clearAll() {
|
|
1216
|
+
this.#built.clear();
|
|
1217
|
+
this.#belongsTo.clear();
|
|
1065
1218
|
}
|
|
1066
1219
|
};
|
|
1067
|
-
|
|
1068
|
-
/**
|
|
1069
|
-
function
|
|
1070
|
-
return
|
|
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;
|
|
1071
1224
|
}
|
|
1072
|
-
/**
|
|
1073
|
-
function
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
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)
|
|
1078
1240
|
};
|
|
1079
|
-
return Object.assign({}, ...calls, { attributes });
|
|
1080
1241
|
}
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
const
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
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)
|
|
1091
1253
|
};
|
|
1092
|
-
if (isSealed(model)) catalogs.set(model, catalog);
|
|
1093
|
-
return catalog;
|
|
1094
1254
|
}
|
|
1095
|
-
/**
|
|
1096
|
-
function
|
|
1097
|
-
|
|
1098
|
-
for (const messages of catalogOf(model).messages) {
|
|
1099
|
-
const found = ownValue(ownValue(messages.attributes, attribute), type) ?? ownValue(messages, type);
|
|
1100
|
-
if (found !== void 0) return found;
|
|
1101
|
-
}
|
|
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;
|
|
1102
1258
|
}
|
|
1103
|
-
/**
|
|
1104
|
-
function
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
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 };
|
|
1108
1265
|
}
|
|
1109
|
-
/**
|
|
1110
|
-
function
|
|
1111
|
-
const
|
|
1112
|
-
|
|
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;
|
|
1113
1271
|
}
|
|
1114
|
-
/**
|
|
1115
|
-
|
|
1116
|
-
|
|
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;
|
|
1117
1280
|
}
|
|
1118
|
-
/**
|
|
1119
|
-
function
|
|
1120
|
-
|
|
1121
|
-
const value = source.read(attribute);
|
|
1122
|
-
if (value === null || value === void 0) return "";
|
|
1123
|
-
if (isFiltered(source.model, attribute)) return FILTERED;
|
|
1124
|
-
if (value instanceof Date) return value.toISOString();
|
|
1125
|
-
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
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);
|
|
1126
1284
|
}
|
|
1127
|
-
/**
|
|
1128
|
-
function
|
|
1129
|
-
if (
|
|
1130
|
-
const { model } = source;
|
|
1131
|
-
const text = messageText(templateFor(model, entry.attribute, entry.type), entry);
|
|
1132
|
-
if (text === void 0) throw missingMessage(model, entry);
|
|
1133
|
-
return text.replace(/%\{(\w+)\}/g, (placeholder, name) => {
|
|
1134
|
-
if (name === "attribute") return humanAttributeName(model, entry.attribute);
|
|
1135
|
-
if (name === "model") return inWords(model.modelName);
|
|
1136
|
-
if (name === "value") return shownValue(source, entry.attribute);
|
|
1137
|
-
return String(ownValue(entry.values, name) ?? placeholder);
|
|
1138
|
-
});
|
|
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`);
|
|
1139
1288
|
}
|
|
1140
|
-
/**
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
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)]);
|
|
1144
1296
|
}
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
return
|
|
1148
|
-
from,
|
|
1149
|
-
declaration: "errorMessages",
|
|
1150
|
-
names: values.flatMap((value) => Object.keys(value.attributes ?? {}))
|
|
1151
|
-
})), ...declaredByClass(model, "humanAttributeNames").map(({ from, values }) => ({
|
|
1152
|
-
from,
|
|
1153
|
-
declaration: "humanAttributeNames",
|
|
1154
|
-
names: values.flatMap((value) => Object.keys(value))
|
|
1155
|
-
}))];
|
|
1297
|
+
function initialValue(model, name, definition) {
|
|
1298
|
+
if (definition.generateId) return model.generateId(name);
|
|
1299
|
+
return isTokenOnInitialize(definition) ? tokenFor(definition) : definition.default();
|
|
1156
1300
|
}
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
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
|
+
}
|
|
1305
|
+
// src/record-state.ts
|
|
1306
|
+
/** @internal The hidden slot where a Record keeps its `RecordState`. */
|
|
1307
|
+
const state = Symbol("state");
|
|
1308
|
+
/** Each record's link to its database (its `RecordState`), for pinning it to one (#93). */
|
|
1309
|
+
function linksOf(records) {
|
|
1310
|
+
return [...records].map((record) => record[state]);
|
|
1163
1311
|
}
|
|
1164
|
-
/** A filtered value's stand-in: prints unquoted, so it isn't taken for a string, as a special value. */
|
|
1165
|
-
var FilteredMark = class {
|
|
1166
|
-
#changed;
|
|
1167
|
-
constructor(changed) {
|
|
1168
|
-
this.#changed = changed;
|
|
1169
|
-
}
|
|
1170
|
-
[inspectCustom](_depth, options) {
|
|
1171
|
-
return styled(options, FILTERED) + (this.#changed ? " (changed)" : "");
|
|
1172
|
-
}
|
|
1173
|
-
};
|
|
1174
1312
|
/**
|
|
1175
|
-
*
|
|
1176
|
-
*
|
|
1313
|
+
* Everything one Record knows about itself: its attribute values, lifecycle, the attributes
|
|
1314
|
+
* assigned since it was built, its Snapshot (each loaded attribute's stored form as last loaded
|
|
1315
|
+
* or saved), the changes its last save wrote, and the Database it belongs to.
|
|
1316
|
+
*
|
|
1317
|
+
* This is the only module that reads or writes those fields. Every rule about them (unloaded
|
|
1318
|
+
* attributes, undefined values, destroyed records, change detection) is enforced here.
|
|
1177
1319
|
*/
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
/**
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
/**
|
|
1197
|
-
|
|
1198
|
-
|
|
1320
|
+
var RecordState = class {
|
|
1321
|
+
#model;
|
|
1322
|
+
#executor;
|
|
1323
|
+
#lifecycle = "new";
|
|
1324
|
+
#values = {};
|
|
1325
|
+
#assigned = /* @__PURE__ */ new Set();
|
|
1326
|
+
#snapshot = /* @__PURE__ */ new Map();
|
|
1327
|
+
/** The row the Snapshot was loaded from: its entries for the row's cells are made on first use (#91). */
|
|
1328
|
+
#snapshotRow;
|
|
1329
|
+
/** A new record's initial values in stored form, which `restore` returns attributes to. */
|
|
1330
|
+
#initialValues = /* @__PURE__ */ new Map();
|
|
1331
|
+
#savedChanges = {};
|
|
1332
|
+
#errors;
|
|
1333
|
+
#abortReason;
|
|
1334
|
+
/** The associations it has loaded, each kept while its key is current. */
|
|
1335
|
+
associations = new LoadedAssociations((attribute) => this.#values[attribute]);
|
|
1336
|
+
/** The new records saving it also saves, built through or pointed at by its associations. */
|
|
1337
|
+
autosaves = new PendingAutosaves();
|
|
1338
|
+
/** Destroyed when its owner is saved through an `autosave: true` association (#37). */
|
|
1339
|
+
isMarkedForDestruction = false;
|
|
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). */
|
|
1343
|
+
isPreviouslyNew = false;
|
|
1344
|
+
/** The contexts it's being validated in, while it is (#51). */
|
|
1345
|
+
validationContexts = [];
|
|
1346
|
+
constructor(model) {
|
|
1347
|
+
this.#model = model;
|
|
1348
|
+
const read = (name) => Object.hasOwn(this.#values, name) ? this.#values[name] : null;
|
|
1349
|
+
this.#errors = new Errors({
|
|
1350
|
+
model,
|
|
1351
|
+
read
|
|
1352
|
+
});
|
|
1199
1353
|
}
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1354
|
+
/** The record's validation errors, filled by the last validation run. */
|
|
1355
|
+
get errors() {
|
|
1356
|
+
return this.#errors;
|
|
1357
|
+
}
|
|
1358
|
+
/** Why a callback last refused a save or destroy; cleared at the start of each run. */
|
|
1359
|
+
get abortReason() {
|
|
1360
|
+
return this.#abortReason;
|
|
1361
|
+
}
|
|
1362
|
+
set abortReason(reason) {
|
|
1363
|
+
this.#abortReason = reason;
|
|
1364
|
+
}
|
|
1365
|
+
/** Not yet saved: built, or created but not persisted. */
|
|
1366
|
+
get isNew() {
|
|
1367
|
+
return this.#lifecycle === "new";
|
|
1368
|
+
}
|
|
1369
|
+
/** Backed by a row: loaded, or saved successfully. */
|
|
1370
|
+
get isPersisted() {
|
|
1371
|
+
return this.#lifecycle === "persisted";
|
|
1372
|
+
}
|
|
1373
|
+
/** Deleted by this instance: a read-only snapshot of the row. */
|
|
1374
|
+
get isDestroyed() {
|
|
1375
|
+
return this.#lifecycle === "destroyed";
|
|
1376
|
+
}
|
|
1377
|
+
/** Records belong to the Database they were built or loaded through (ADR-0003). */
|
|
1378
|
+
belongTo(executor) {
|
|
1379
|
+
this.#executor = executor;
|
|
1380
|
+
}
|
|
1381
|
+
/** The record's Database; `NoDatabase` for a record constructed directly (`new User()`). */
|
|
1382
|
+
get executor() {
|
|
1383
|
+
if (this.#executor === void 0) {
|
|
1384
|
+
const { name } = this.#model;
|
|
1385
|
+
throw new NoDatabase(`${name} record has no Database; build or load records through db.model(${name})`);
|
|
1209
1386
|
}
|
|
1210
|
-
|
|
1211
|
-
if (typeof type !== "string") throw new TypeError("errors.add needs a message or a type");
|
|
1212
|
-
const entry = {
|
|
1213
|
-
attribute,
|
|
1214
|
-
type,
|
|
1215
|
-
values
|
|
1216
|
-
};
|
|
1217
|
-
messageOf(this.#source, entry);
|
|
1218
|
-
this.#entries.push(entry);
|
|
1387
|
+
return this.#executor;
|
|
1219
1388
|
}
|
|
1220
|
-
/**
|
|
1221
|
-
|
|
1222
|
-
|
|
1389
|
+
/**
|
|
1390
|
+
* Refuses to use a record as a live one when it can't be: a destroyed record is a read-only
|
|
1391
|
+
* snapshot, and a persisted record without its primary key (from `select(...).distinct()`)
|
|
1392
|
+
* has no identity to write by.
|
|
1393
|
+
*/
|
|
1394
|
+
requireLive(action) {
|
|
1395
|
+
this.#requireNotDestroyed(action);
|
|
1396
|
+
this.requireKey(action);
|
|
1223
1397
|
}
|
|
1224
|
-
/**
|
|
1225
|
-
|
|
1226
|
-
|
|
1398
|
+
/** A persisted record needs its primary key to be found by; one from `distinct()` has none. */
|
|
1399
|
+
requireKey(action) {
|
|
1400
|
+
const { name, primaryKey } = this.#model;
|
|
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}`);
|
|
1227
1402
|
}
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
return
|
|
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);
|
|
1232
1407
|
}
|
|
1233
|
-
/**
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
type,
|
|
1240
|
-
message: messageOf(this.#source, entry)
|
|
1241
|
-
};
|
|
1242
|
-
return Object.keys(values).length === 0 ? error : {
|
|
1243
|
-
...error,
|
|
1244
|
-
values: { ...values }
|
|
1245
|
-
};
|
|
1246
|
-
});
|
|
1408
|
+
/** An attribute's value; `MissingAttribute` if it wasn't loaded (left out of `select`). */
|
|
1409
|
+
read(given) {
|
|
1410
|
+
const name = attributeName(this.#model, given);
|
|
1411
|
+
this.#requireAttribute(name);
|
|
1412
|
+
if (!Object.hasOwn(this.#values, name)) throw new MissingAttribute(`${this.#model.name} record has no "${name}" loaded; it was left out of select(...)`);
|
|
1413
|
+
return this.#values[name];
|
|
1247
1414
|
}
|
|
1248
|
-
|
|
1249
|
-
|
|
1415
|
+
/**
|
|
1416
|
+
* Assigns one attribute. `undefined` throws `TypeError`, because it would silently store NULL
|
|
1417
|
+
* (use `null` for that); a destroyed record is read-only. A secure password's assignment
|
|
1418
|
+
* changes its digest only to clear it.
|
|
1419
|
+
*/
|
|
1420
|
+
write(given, value) {
|
|
1421
|
+
this.#requireNotDestroyed("be changed");
|
|
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);
|
|
1250
1431
|
}
|
|
1251
|
-
|
|
1252
|
-
|
|
1432
|
+
/**
|
|
1433
|
+
* Writes a key copied from another record through `association`, cast as a condition's value
|
|
1434
|
+
* is (#94): an integer key into a text foreign key becomes its digits.
|
|
1435
|
+
*/
|
|
1436
|
+
writeKey(name, value, association) {
|
|
1437
|
+
this.#requireNotDestroyed("be changed");
|
|
1438
|
+
this.#store(name, this.#attribute(name).key(value, association));
|
|
1253
1439
|
}
|
|
1254
|
-
/**
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
options,
|
|
1259
|
-
inspect
|
|
1260
|
-
});
|
|
1440
|
+
/** Stores an attribute's already-cast value, as assigned. */
|
|
1441
|
+
#store(name, value) {
|
|
1442
|
+
this.#values[name] = value;
|
|
1443
|
+
this.#assigned.add(name);
|
|
1261
1444
|
}
|
|
1262
|
-
/**
|
|
1263
|
-
|
|
1264
|
-
const
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1445
|
+
/** Assigns several attributes; unknown names throw `UnknownAttribute`. */
|
|
1446
|
+
assign(attributes) {
|
|
1447
|
+
for (const [name, value] of Object.entries(attributes)) {
|
|
1448
|
+
attributeOf(this.#model, name);
|
|
1449
|
+
this.write(name, value);
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
/** A new record: every attribute reads as null until assigned, and initial values are made now. */
|
|
1453
|
+
build(attributes, kept = {}) {
|
|
1454
|
+
for (const name of this.#model.attributeDefinitions.keys()) this.#values[name] = null;
|
|
1455
|
+
for (const [name, value] of initialValues(this.#model)) {
|
|
1456
|
+
this.write(name, value);
|
|
1457
|
+
this.#initialValues.set(name, this.#storedForm(name));
|
|
1458
|
+
}
|
|
1459
|
+
for (const [name, value] of Object.entries(kept)) this.#store(name, value);
|
|
1460
|
+
this.assign(attributes);
|
|
1461
|
+
generateTokens(this.#model.attributeDefinitions, this, "initialize");
|
|
1462
|
+
}
|
|
1463
|
+
/**
|
|
1464
|
+
* Points this record at `value` through `association`'s foreign key, keeping it loaded for its
|
|
1465
|
+
* key attributes (a polymorphic belongsTo's type is written before, by its `set`; #60).
|
|
1466
|
+
*/
|
|
1467
|
+
pointAt(association, key, value) {
|
|
1468
|
+
const { name, ownerAttribute, keyAttributes } = association;
|
|
1469
|
+
this.writeKey(ownerAttribute, key, name);
|
|
1470
|
+
this.associations.set(name, keyAttributes, value);
|
|
1471
|
+
}
|
|
1472
|
+
/** Forgets an association: what's loaded and its autosaves (`reloadAssociation`). */
|
|
1473
|
+
resetAssociation(name) {
|
|
1474
|
+
this.associations.clear(name);
|
|
1475
|
+
this.autosaves.clear(name);
|
|
1476
|
+
}
|
|
1477
|
+
/** Forgets every association, loaded and autosaved (`reload()`). */
|
|
1478
|
+
clearAssociations() {
|
|
1479
|
+
this.associations.clearAll();
|
|
1480
|
+
this.autosaves.clearAll();
|
|
1481
|
+
}
|
|
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
|
+
}
|
|
1271
1577
|
}
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
return
|
|
1275
|
-
attribute,
|
|
1276
|
-
values,
|
|
1277
|
-
...failure
|
|
1278
|
-
});
|
|
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));
|
|
1279
1581
|
}
|
|
1280
|
-
/**
|
|
1281
|
-
|
|
1282
|
-
this.#
|
|
1582
|
+
/** The attributes an insert writes: the assigned ones, so column defaults apply to the rest. */
|
|
1583
|
+
insertAssignments() {
|
|
1584
|
+
return this.#assignmentsOf([...this.#assigned]);
|
|
1283
1585
|
}
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
* The associations one record has loaded (preloaded, read, or set by a write): a record, an
|
|
1288
|
-
* array of records, or null. Each stays loaded while the owner's attribute still holds the key
|
|
1289
|
-
* it was loaded for, and a load overtaken by a change to its association isn't kept.
|
|
1290
|
-
*/
|
|
1291
|
-
var LoadedAssociations = class {
|
|
1292
|
-
/** The owner's attribute value now, which an entry's key is checked against. */
|
|
1293
|
-
#keyOf;
|
|
1294
|
-
#entries = /* @__PURE__ */ new Map();
|
|
1295
|
-
/** Counted when an association changes, by name and record-wide, so a stale load isn't kept. */
|
|
1296
|
-
#loadsDiscarded = /* @__PURE__ */ new Map();
|
|
1297
|
-
#allLoadsDiscarded = 0;
|
|
1298
|
-
constructor(keyOf) {
|
|
1299
|
-
this.#keyOf = keyOf;
|
|
1586
|
+
/** The attributes an update writes: the changed ones. */
|
|
1587
|
+
updateAssignments() {
|
|
1588
|
+
return this.#assignmentsOf(this.changedNames());
|
|
1300
1589
|
}
|
|
1301
|
-
/** The
|
|
1302
|
-
get(
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
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);
|
|
1306
1597
|
}
|
|
1307
1598
|
/**
|
|
1308
|
-
*
|
|
1309
|
-
*
|
|
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).
|
|
1310
1602
|
*/
|
|
1311
|
-
|
|
1312
|
-
this
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
value
|
|
1316
|
-
});
|
|
1317
|
-
|
|
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;
|
|
1318
1615
|
}
|
|
1319
1616
|
/**
|
|
1320
|
-
*
|
|
1321
|
-
*
|
|
1322
|
-
*
|
|
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.
|
|
1323
1621
|
*/
|
|
1324
|
-
|
|
1325
|
-
const
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
value
|
|
1331
|
-
});
|
|
1332
|
-
};
|
|
1333
|
-
}
|
|
1334
|
-
/** Forgets the association; loads of it already sent won't be kept. */
|
|
1335
|
-
clear(name) {
|
|
1336
|
-
this.#entries.delete(name);
|
|
1337
|
-
this.#discardPendingLoads(name);
|
|
1338
|
-
}
|
|
1339
|
-
/** Forgets every association (`reload()`); loads already sent won't be kept. */
|
|
1340
|
-
clearAll() {
|
|
1341
|
-
this.#entries.clear();
|
|
1342
|
-
this.#allLoadsDiscarded += 1;
|
|
1343
|
-
}
|
|
1344
|
-
#key(attribute) {
|
|
1345
|
-
if (typeof attribute !== "string") return attribute.map((each) => this.#keyOf(each) ?? null);
|
|
1346
|
-
return this.#keyOf(attribute) ?? null;
|
|
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;
|
|
1347
1628
|
}
|
|
1348
|
-
|
|
1349
|
-
|
|
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
|
+
}
|
|
1350
1641
|
}
|
|
1351
1642
|
/**
|
|
1352
|
-
*
|
|
1353
|
-
*
|
|
1643
|
+
* After a touch (#50): as `commitColumns`, and `savedChanges` holds only the touched
|
|
1644
|
+
* attributes' changes. The record's other changes stay unsaved.
|
|
1354
1645
|
*/
|
|
1355
|
-
|
|
1356
|
-
|
|
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]]));
|
|
1357
1651
|
}
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
return now.every((each, index) => Object.is(each, loaded[index]));
|
|
1363
|
-
}
|
|
1364
|
-
// src/pending-autosaves.ts
|
|
1365
|
-
/**
|
|
1366
|
-
* The records saving one record may also save: those built through its hasMany and hasOne
|
|
1367
|
-
* associations or pushed onto a hasMany, after it (`autosavesOf` says which), and the new ones
|
|
1368
|
-
* its belongsTo associations point at, before it.
|
|
1369
|
-
*/
|
|
1370
|
-
var PendingAutosaves = class {
|
|
1371
|
-
#built = /* @__PURE__ */ new Map();
|
|
1372
|
-
#belongsTo = /* @__PURE__ */ new Map();
|
|
1373
|
-
/** A record built through one of this record's hasMany or hasOne associations. */
|
|
1374
|
-
addBuilt(name, record) {
|
|
1375
|
-
this.#built.set(name, [...this.#built.get(name) ?? [], record]);
|
|
1652
|
+
/** A save with nothing to write: nothing changes but `savedChanges`. */
|
|
1653
|
+
commitClean() {
|
|
1654
|
+
this.#savedChanges = {};
|
|
1655
|
+
this.isPreviouslyNew = false;
|
|
1376
1656
|
}
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
this.#built.set(name, kept);
|
|
1657
|
+
markDestroyed() {
|
|
1658
|
+
this.#lifecycle = "destroyed";
|
|
1659
|
+
this.isPreviouslyNew = false;
|
|
1381
1660
|
}
|
|
1382
|
-
/** A
|
|
1383
|
-
|
|
1384
|
-
this.#
|
|
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}`);
|
|
1385
1664
|
}
|
|
1386
|
-
/**
|
|
1387
|
-
|
|
1388
|
-
|
|
1665
|
+
/** An unknown name is UnknownAttribute, even one every object inherits (`constructor`, #84). */
|
|
1666
|
+
#requireAttribute(name) {
|
|
1667
|
+
this.#definition(name);
|
|
1389
1668
|
}
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
return [...this.#built];
|
|
1669
|
+
#definition(name) {
|
|
1670
|
+
return attributeOf(this.#model, name);
|
|
1393
1671
|
}
|
|
1394
|
-
/**
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
else this.#belongsTo.set(name, record);
|
|
1672
|
+
/** The resolved attribute, so a refusal names the Model and attribute. */
|
|
1673
|
+
#attribute(name) {
|
|
1674
|
+
return attributeFor(this.#model, name);
|
|
1398
1675
|
}
|
|
1399
|
-
/**
|
|
1400
|
-
|
|
1401
|
-
return
|
|
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);
|
|
1402
1679
|
}
|
|
1403
|
-
/**
|
|
1404
|
-
|
|
1405
|
-
|
|
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));
|
|
1406
1684
|
}
|
|
1407
|
-
/**
|
|
1408
|
-
|
|
1409
|
-
this.#
|
|
1410
|
-
this.#belongsTo.delete(name);
|
|
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]);
|
|
1411
1688
|
}
|
|
1412
|
-
/**
|
|
1413
|
-
|
|
1414
|
-
this.#
|
|
1415
|
-
this.#belongsTo.clear();
|
|
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]);
|
|
1416
1692
|
}
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
const state = Symbol("state");
|
|
1421
|
-
/** Each record's link to its database (its `RecordState`), for pinning it to one (#93). */
|
|
1422
|
-
function linksOf(records) {
|
|
1423
|
-
return [...records].map((record) => record[state]);
|
|
1424
|
-
}
|
|
1425
|
-
/**
|
|
1426
|
-
* Everything one Record knows about itself: its attribute values, lifecycle, the attributes
|
|
1427
|
-
* assigned since it was built, its Snapshot (each loaded attribute's stored form as last loaded
|
|
1428
|
-
* or saved), the changes its last save wrote, and the Database it belongs to.
|
|
1429
|
-
*
|
|
1430
|
-
* This is the only module that reads or writes those fields. Every rule about them (unloaded
|
|
1431
|
-
* attributes, undefined values, destroyed records, change detection) is enforced here.
|
|
1432
|
-
*/
|
|
1433
|
-
var RecordState = class {
|
|
1434
|
-
#model;
|
|
1435
|
-
#executor;
|
|
1436
|
-
#lifecycle = "new";
|
|
1437
|
-
#values = {};
|
|
1438
|
-
#assigned = /* @__PURE__ */ new Set();
|
|
1439
|
-
#snapshot = /* @__PURE__ */ new Map();
|
|
1440
|
-
/** The row the Snapshot was loaded from: its entries for the row's cells are made on first use (#91). */
|
|
1441
|
-
#snapshotRow;
|
|
1442
|
-
/** A new record's initial values in stored form, which `restore` returns attributes to. */
|
|
1443
|
-
#initialValues = /* @__PURE__ */ new Map();
|
|
1444
|
-
#savedChanges = {};
|
|
1445
|
-
#errors;
|
|
1446
|
-
#abortReason;
|
|
1447
|
-
/** The associations it has loaded, each kept while its key is current. */
|
|
1448
|
-
associations = new LoadedAssociations((attribute) => this.#values[attribute]);
|
|
1449
|
-
/** The new records saving it also saves, built through or pointed at by its associations. */
|
|
1450
|
-
autosaves = new PendingAutosaves();
|
|
1451
|
-
/** Destroyed when its owner is saved through an `autosave: true` association (#37). */
|
|
1452
|
-
isMarkedForDestruction = false;
|
|
1453
|
-
/** Whether its last save created it, as Rails' `previously_new_record?` (#351). */
|
|
1454
|
-
isPreviouslyNew = false;
|
|
1455
|
-
/** The contexts it's being validated in, while it is (#51). */
|
|
1456
|
-
validationContexts = [];
|
|
1457
|
-
constructor(model) {
|
|
1458
|
-
this.#model = model;
|
|
1459
|
-
const read = (name) => Object.hasOwn(this.#values, name) ? this.#values[name] : null;
|
|
1460
|
-
this.#errors = new Errors({
|
|
1461
|
-
model,
|
|
1462
|
-
read
|
|
1463
|
-
});
|
|
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);
|
|
1464
1696
|
}
|
|
1465
|
-
/** The
|
|
1466
|
-
|
|
1467
|
-
return this.#
|
|
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]]);
|
|
1468
1700
|
}
|
|
1469
|
-
/**
|
|
1470
|
-
|
|
1471
|
-
|
|
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();
|
|
1472
1715
|
}
|
|
1473
|
-
|
|
1474
|
-
|
|
1716
|
+
/** Whether the Snapshot has `name`: it was loaded or saved. */
|
|
1717
|
+
#isInSnapshot(name) {
|
|
1718
|
+
return this.#snapshot.has(name) || this.#isInRow(name);
|
|
1475
1719
|
}
|
|
1476
|
-
/**
|
|
1477
|
-
|
|
1478
|
-
|
|
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;
|
|
1479
1727
|
}
|
|
1480
|
-
/**
|
|
1481
|
-
|
|
1482
|
-
return this.#
|
|
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));
|
|
1483
1731
|
}
|
|
1484
|
-
/**
|
|
1485
|
-
|
|
1486
|
-
|
|
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;
|
|
1487
1736
|
}
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
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);
|
|
1491
1757
|
}
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
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
|
+
};
|
|
1497
1798
|
}
|
|
1498
|
-
return this.#executor;
|
|
1499
1799
|
}
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
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);
|
|
1508
1863
|
}
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
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));
|
|
1513
1873
|
}
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
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
|
+
});
|
|
1517
1900
|
}
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
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);
|
|
1523
1912
|
}
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
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
|
+
});
|
|
1531
1943
|
}
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
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
|
|
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`);
|
|
1539
1987
|
}
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
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;
|
|
1544
2072
|
}
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
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);
|
|
1551
2139
|
}
|
|
1552
|
-
/**
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
for (const [name, value] of initialValues(this.#model)) {
|
|
1556
|
-
this.write(name, value);
|
|
1557
|
-
this.#initialValues.set(name, this.#storedForm(name));
|
|
1558
|
-
}
|
|
1559
|
-
this.assign(attributes);
|
|
2140
|
+
/** Its column; `UnknownAttribute` for a virtual attribute, which has none (#356). */
|
|
2141
|
+
get column() {
|
|
2142
|
+
return columnOf(this.#model, this.name).column;
|
|
1560
2143
|
}
|
|
1561
|
-
/**
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
*/
|
|
1565
|
-
pointAt(association, key, value) {
|
|
1566
|
-
const { name, ownerAttribute, keyAttributes } = association;
|
|
1567
|
-
this.writeKey(ownerAttribute, key, name);
|
|
1568
|
-
this.associations.set(name, keyAttributes, value);
|
|
2144
|
+
/** Whether it's a `string` attribute, which D1 compares as text, not by number. */
|
|
2145
|
+
get isText() {
|
|
2146
|
+
return this.#definition.type === "string";
|
|
1569
2147
|
}
|
|
1570
|
-
/**
|
|
1571
|
-
|
|
1572
|
-
this.
|
|
1573
|
-
this.autosaves.clear(name);
|
|
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";
|
|
1574
2151
|
}
|
|
1575
|
-
/**
|
|
1576
|
-
|
|
1577
|
-
this.
|
|
1578
|
-
this.autosaves.clearAll();
|
|
2152
|
+
/** Whether it's a `json` attribute, whose stored text is JSON itself. */
|
|
2153
|
+
get isJson() {
|
|
2154
|
+
return this.#definition.type === "json";
|
|
1579
2155
|
}
|
|
1580
|
-
/**
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
this.#
|
|
2156
|
+
/**
|
|
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).
|
|
2161
|
+
*/
|
|
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);
|
|
1590
2167
|
}
|
|
1591
|
-
/**
|
|
1592
|
-
|
|
1593
|
-
return
|
|
2168
|
+
/** An assigned value cast, then normalized (#354): what a record keeps for it. */
|
|
2169
|
+
assigned(value) {
|
|
2170
|
+
return this.normalize(this.cast(value));
|
|
1594
2171
|
}
|
|
1595
2172
|
/**
|
|
1596
|
-
*
|
|
1597
|
-
*
|
|
1598
|
-
*
|
|
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.
|
|
1599
2176
|
*/
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
return Object.keys(this.#values).filter((name) => !this.#isInSnapshot(name) || !isSameCell(this.#snapshotOf(name), this.#storedForm(name)));
|
|
2177
|
+
normalize(value) {
|
|
2178
|
+
return this.#normalized(value, (result) => this.cast(result));
|
|
1603
2179
|
}
|
|
1604
|
-
/**
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
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);
|
|
2206
|
+
}
|
|
2207
|
+
return normalized;
|
|
1609
2208
|
}
|
|
1610
|
-
/**
|
|
1611
|
-
|
|
1612
|
-
return
|
|
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;
|
|
1613
2212
|
}
|
|
1614
|
-
/**
|
|
1615
|
-
|
|
1616
|
-
|
|
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;
|
|
1617
2217
|
}
|
|
1618
2218
|
/**
|
|
1619
|
-
*
|
|
1620
|
-
*
|
|
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.
|
|
1621
2221
|
*/
|
|
1622
|
-
|
|
1623
|
-
this.
|
|
1624
|
-
return this.#
|
|
2222
|
+
key(value, association) {
|
|
2223
|
+
requireDefined(this.#model, this.name, value);
|
|
2224
|
+
return this.#orRefuse(castKey(this.#definition, value), value, association);
|
|
1625
2225
|
}
|
|
1626
2226
|
/**
|
|
1627
|
-
*
|
|
1628
|
-
*
|
|
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.
|
|
1629
2230
|
*/
|
|
1630
|
-
|
|
1631
|
-
this
|
|
1632
|
-
if (!this.changedNames().includes(name)) return false;
|
|
1633
|
-
return this.#isMatching(name, this.valueInDatabase(name), this.#values[name], options);
|
|
2231
|
+
condition(value) {
|
|
2232
|
+
return castCondition(this.#definition, value);
|
|
1634
2233
|
}
|
|
1635
|
-
/**
|
|
1636
|
-
|
|
1637
|
-
this.
|
|
1638
|
-
|
|
1639
|
-
return change !== void 0 && this.#isMatching(name, change[0], change[1], options);
|
|
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);
|
|
1640
2238
|
}
|
|
1641
|
-
/**
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
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);
|
|
1653
2251
|
}
|
|
2252
|
+
if (stored === void 0) throw this.#refusal(value);
|
|
2253
|
+
return stored;
|
|
1654
2254
|
}
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
return (
|
|
1658
|
-
}
|
|
1659
|
-
/** The attributes an insert writes: the assigned ones, so column defaults apply to the rest. */
|
|
1660
|
-
insertAssignments() {
|
|
1661
|
-
return this.#assignmentsOf([...this.#assigned]);
|
|
1662
|
-
}
|
|
1663
|
-
/** The attributes an update writes: the changed ones. */
|
|
1664
|
-
updateAssignments() {
|
|
1665
|
-
return this.#assignmentsOf(this.changedNames());
|
|
1666
|
-
}
|
|
1667
|
-
/** The primary key as stored in D1: the row's key before any unsaved change to it. */
|
|
1668
|
-
get storedKey() {
|
|
1669
|
-
return this.#snapshotOf(this.#model.primaryKey);
|
|
2255
|
+
/** An assigned value cast, then in the form D1 stores. */
|
|
2256
|
+
store(value) {
|
|
2257
|
+
return this.write(this.cast(value));
|
|
1670
2258
|
}
|
|
1671
|
-
/**
|
|
1672
|
-
|
|
1673
|
-
return this
|
|
2259
|
+
/** An assigned value cast and normalized (#354), then in the form D1 stores. */
|
|
2260
|
+
storeNormalized(value) {
|
|
2261
|
+
return this.write(this.assigned(value));
|
|
1674
2262
|
}
|
|
1675
2263
|
/**
|
|
1676
|
-
*
|
|
1677
|
-
*
|
|
1678
|
-
*
|
|
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).
|
|
1679
2267
|
*/
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
const
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
} else this.loadRow(row);
|
|
1690
|
-
this.#savedChanges = Object.fromEntries([...before].filter(([name, { stored }]) => written.has(name) || !isSameCell(this.#storedForm(name), stored)).map(([name, { value }]) => [name, [value, this.#copyOf(name)]]));
|
|
1691
|
-
this.isPreviouslyNew = true;
|
|
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;
|
|
2273
|
+
}
|
|
2274
|
+
/** A copy of a value: written as D1 stores it, then read back. */
|
|
2275
|
+
copy(value) {
|
|
2276
|
+
return this.read(this.write(value));
|
|
1692
2277
|
}
|
|
1693
2278
|
/**
|
|
1694
|
-
*
|
|
1695
|
-
*
|
|
1696
|
-
*
|
|
1697
|
-
* as stored, which wasn't a change.
|
|
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).
|
|
1698
2282
|
*/
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
this.#
|
|
1703
|
-
this.#markSaved();
|
|
1704
|
-
this.isPreviouslyNew = false;
|
|
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));
|
|
1705
2287
|
}
|
|
1706
2288
|
/**
|
|
1707
|
-
*
|
|
1708
|
-
*
|
|
1709
|
-
* `savedChanges`, are as they were.
|
|
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).
|
|
1710
2291
|
*/
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
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;
|
|
2296
|
+
}
|
|
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));
|
|
1718
2300
|
}
|
|
1719
2301
|
/**
|
|
1720
|
-
*
|
|
1721
|
-
*
|
|
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.
|
|
1722
2305
|
*/
|
|
1723
|
-
|
|
1724
|
-
const
|
|
1725
|
-
|
|
1726
|
-
this.#savedChanges = Object.fromEntries(names.filter((name) => Object.hasOwn(changes, name)).map((name) => [name, changes[name]]));
|
|
1727
|
-
}
|
|
1728
|
-
/** A save with nothing to write: nothing changes but `savedChanges`. */
|
|
1729
|
-
commitClean() {
|
|
1730
|
-
this.#savedChanges = {};
|
|
1731
|
-
this.isPreviouslyNew = false;
|
|
2306
|
+
bindCells(params, ...cells) {
|
|
2307
|
+
const hidden = this.#isHidden();
|
|
2308
|
+
for (const cell of cells) params.push(hidden ? new Filtered(cell) : cell);
|
|
1732
2309
|
}
|
|
1733
|
-
|
|
1734
|
-
this.#
|
|
1735
|
-
|
|
2310
|
+
#orRefuse(cast, value, association) {
|
|
2311
|
+
if (cast === uncastable) throw this.#refusal(value, association);
|
|
2312
|
+
return cast;
|
|
1736
2313
|
}
|
|
1737
|
-
/**
|
|
1738
|
-
|
|
1739
|
-
|
|
2314
|
+
/**
|
|
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).
|
|
2317
|
+
*/
|
|
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);
|
|
2324
|
+
}
|
|
1740
2325
|
}
|
|
1741
|
-
/**
|
|
1742
|
-
#
|
|
1743
|
-
this.#
|
|
2326
|
+
/** Whether the attribute's values are hidden from listeners and errors (#83). */
|
|
2327
|
+
#isHidden() {
|
|
2328
|
+
return isFiltered(this.#model, this.name);
|
|
1744
2329
|
}
|
|
1745
|
-
|
|
1746
|
-
|
|
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 });
|
|
1747
2341
|
}
|
|
1748
|
-
/**
|
|
1749
|
-
#
|
|
1750
|
-
|
|
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);
|
|
1751
2348
|
}
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
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);
|
|
1755
2361
|
}
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
2362
|
+
let attribute = attributes.get(name);
|
|
2363
|
+
if (attribute === void 0) {
|
|
2364
|
+
attribute = new Attribute(model, name);
|
|
2365
|
+
attributes.set(name, attribute);
|
|
1760
2366
|
}
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
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"
|
|
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);
|
|
1764
2403
|
}
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
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);
|
|
1768
2411
|
}
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
2412
|
+
}
|
|
2413
|
+
// src/enum-methods.ts
|
|
2414
|
+
/** Each name of every enum attribute, with the methods it gives. */
|
|
2415
|
+
function enumNames(definitions) {
|
|
2416
|
+
return [...definitions].flatMap(([attribute, definition]) => {
|
|
2417
|
+
if (definition.enum === void 0) return [];
|
|
2418
|
+
const before = affix(attribute, definition.prefix);
|
|
2419
|
+
const after = affix(attribute, definition.suffix);
|
|
2420
|
+
return enumEntries(definition.enum).map(([name]) => {
|
|
2421
|
+
const stem = `${before}${methodPart(name)}${after}`;
|
|
2422
|
+
const records = [
|
|
2423
|
+
`is${stem}`,
|
|
2424
|
+
`saveAs${stem}`,
|
|
2425
|
+
`saveAs${stem}OrThrow`
|
|
2426
|
+
];
|
|
2427
|
+
const scopes = [uncapitalized(stem), `not${stem}`];
|
|
2428
|
+
return {
|
|
2429
|
+
attribute,
|
|
2430
|
+
name,
|
|
2431
|
+
records: definition.instanceMethods === false ? [] : records,
|
|
2432
|
+
scopes: definition.scopes === false ? [] : scopes
|
|
2433
|
+
};
|
|
2434
|
+
});
|
|
2435
|
+
});
|
|
2436
|
+
}
|
|
2437
|
+
function affix(attribute, option) {
|
|
2438
|
+
if (option === true) return methodPart(attribute);
|
|
2439
|
+
return typeof option === "string" ? methodPart(option) : "";
|
|
2440
|
+
}
|
|
2441
|
+
/** The scopes the enums of `definitions` give a Model, as `EnumStatics` types them. */
|
|
2442
|
+
function enumScopeNames(definitions) {
|
|
2443
|
+
return enumNames(definitions).flatMap(({ scopes }) => scopes);
|
|
2444
|
+
}
|
|
2445
|
+
/** How a word reads inside a method's name, as `MethodPart` types it. */
|
|
2446
|
+
function methodPart(word) {
|
|
2447
|
+
const [head = "", ...rest] = word.split("_");
|
|
2448
|
+
return capitalized(head + rest.map(capitalized).join(""));
|
|
2449
|
+
}
|
|
2450
|
+
const uncapitalized = (text) => text.charAt(0).toLowerCase() + text.slice(1);
|
|
2451
|
+
/**
|
|
2452
|
+
* Defines each enum attribute's methods on `prototype`: `isPublished()` is `status === "published"`,
|
|
2453
|
+
* and `saveAsPublished()` is `update({ status: "published" })`, so it saves the record's other
|
|
2454
|
+
* changes too.
|
|
2455
|
+
*/
|
|
2456
|
+
function defineEnumMethods(prototype, definitions) {
|
|
2457
|
+
for (const { attribute, name, records } of enumNames(definitions)) {
|
|
2458
|
+
const [predicate, setter, throwingSetter] = records;
|
|
2459
|
+
if (predicate === void 0) continue;
|
|
2460
|
+
defineMethod(prototype, predicate, function() {
|
|
2461
|
+
return this[attribute] === name;
|
|
2462
|
+
});
|
|
2463
|
+
defineMethod(prototype, setter, function() {
|
|
2464
|
+
return this.update({ [attribute]: name });
|
|
2465
|
+
});
|
|
2466
|
+
defineMethod(prototype, throwingSetter, function() {
|
|
2467
|
+
return this.updateOrThrow({ [attribute]: name });
|
|
2468
|
+
});
|
|
1772
2469
|
}
|
|
1773
|
-
|
|
1774
|
-
|
|
2470
|
+
}
|
|
2471
|
+
/**
|
|
2472
|
+
* Defines each enum attribute's scopes on `model`, as `this.scope(…)` statics: `published()` is
|
|
2473
|
+
* `where({ status: "published" })`, and `notPublished()` is `whereNot(…)`.
|
|
2474
|
+
*/
|
|
2475
|
+
function defineEnumStatics(model, definitions) {
|
|
2476
|
+
const declaring = model;
|
|
2477
|
+
for (const { attribute, name, scopes } of enumNames(definitions)) {
|
|
2478
|
+
const [only, without] = scopes;
|
|
2479
|
+
if (only === void 0) continue;
|
|
2480
|
+
const onlyScope = declaring.scope((q) => q.where({ [attribute]: name }));
|
|
2481
|
+
const withoutScope = declaring.scope((q) => q.whereNot({ [attribute]: name }));
|
|
2482
|
+
enumScopes.add(onlyScope);
|
|
2483
|
+
enumScopes.add(withoutScope);
|
|
2484
|
+
defineMethod(model, only, onlyScope, { named: false });
|
|
2485
|
+
defineMethod(model, without, withoutScope, { named: false });
|
|
1775
2486
|
}
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
2487
|
+
}
|
|
2488
|
+
/** Puts `method` on `target` as `name`, writable as a declared method is, and names it unless told not to. */
|
|
2489
|
+
function defineMethod(target, name, method, { named = true } = {}) {
|
|
2490
|
+
if (Object.hasOwn(target, name)) return;
|
|
2491
|
+
if (named) Object.defineProperty(method, "name", { value: name });
|
|
2492
|
+
Object.defineProperty(target, name, {
|
|
2493
|
+
value: method,
|
|
2494
|
+
writable: true,
|
|
2495
|
+
configurable: true
|
|
2496
|
+
});
|
|
2497
|
+
}
|
|
2498
|
+
/** The scope statics `defineEnumStatics` made, so a static a Model declares itself is told apart. */
|
|
2499
|
+
const enumScopes = /* @__PURE__ */ new WeakSet();
|
|
2500
|
+
/**
|
|
2501
|
+
* Why an enum's method names can't be as they are, or undefined: two enums give one name, or one
|
|
2502
|
+
* takes the name of a record method, an attribute, a Relation method, a Model static, or a static
|
|
2503
|
+
* the Model declares itself. It's refused when the enum is declared.
|
|
2504
|
+
*/
|
|
2505
|
+
function enumNameProblem(model, taken, methodsOff = /* @__PURE__ */ new Map()) {
|
|
2506
|
+
const checks = {
|
|
2507
|
+
...taken,
|
|
2508
|
+
methodsOffFix: (attribute) => methodsOff.get(attribute)
|
|
2509
|
+
};
|
|
2510
|
+
const givenBy = /* @__PURE__ */ new Map();
|
|
2511
|
+
for (const each of enumNames(model.attributeDefinitions)) {
|
|
2512
|
+
const { attribute, records, scopes } = each;
|
|
2513
|
+
for (const method of [...records, ...scopes]) {
|
|
2514
|
+
const other = givenBy.get(method);
|
|
2515
|
+
if (other !== void 0) return repeated(model.name, {
|
|
2516
|
+
first: other,
|
|
2517
|
+
second: attribute,
|
|
2518
|
+
method
|
|
2519
|
+
}, checks);
|
|
2520
|
+
givenBy.set(method, attribute);
|
|
1787
2521
|
}
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
}
|
|
1791
|
-
/** Whether the Snapshot has `name`: it was loaded or saved. */
|
|
1792
|
-
#isInSnapshot(name) {
|
|
1793
|
-
return this.#snapshot.has(name) || this.#isInRow(name);
|
|
2522
|
+
const problem = declarableProblem(model, each, [...records, ...scopes], checks) ?? recordProblem(model, attribute, records, checks) ?? staticProblem(model, attribute, scopes, checks);
|
|
2523
|
+
if (problem !== void 0) return problem;
|
|
1794
2524
|
}
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
2525
|
+
}
|
|
2526
|
+
/**
|
|
2527
|
+
* A method name an enum's name gives that TypeScript can't declare (#340): one that isn't an
|
|
2528
|
+
* identifier (`isIn-progress`), or a scope that's a reserved word (`new`), which the generated
|
|
2529
|
+
* schema couldn't declare as a static.
|
|
2530
|
+
*/
|
|
2531
|
+
function declarableProblem(model, { attribute, name, scopes }, methods, checks) {
|
|
2532
|
+
const fix = remedy(attribute, checks);
|
|
2533
|
+
const undeclarable = methods.find((method) => !isIdentifier(method));
|
|
2534
|
+
if (undeclarable !== void 0) {
|
|
2535
|
+
const kind = scopes.includes(undeclarable) ? "scope" : "method";
|
|
2536
|
+
const suggested = uncapitalized(methodPart(name.split(/[^\p{L}\p{N}_$]+/u).join("_")));
|
|
2537
|
+
const example = isIdentifier(suggested) ? ` ({ ${suggested}: ${JSON.stringify(name)} })` : "";
|
|
2538
|
+
return `${model.name}'s enum ${attribute} gives a ${kind} named "${undeclarable}", which isn't a name TypeScript can declare; name it with letters, digits, _ and $, and map it to the value it's stored as${example}${offFix(attribute, checks)}`;
|
|
1802
2539
|
}
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
2540
|
+
const reserved = methods.find((method) => reservedWords.has(method));
|
|
2541
|
+
return reserved === void 0 ? void 0 : `${model.name}'s enum ${attribute} gives a scope named "${reserved}", which is a reserved word; ${fix}`;
|
|
2542
|
+
}
|
|
2543
|
+
/** Two of an enum's names, or two enums, giving one method name. */
|
|
2544
|
+
function repeated(model, { first, second, method }, checks) {
|
|
2545
|
+
if (first !== second) return `${model}'s enums ${first} and ${second} both give a method named "${method}"; give one a prefix or a suffix${[first, second].map((attribute) => namedOffFix(attribute, checks)).join("")}`;
|
|
2546
|
+
const off = offFix(second, checks);
|
|
2547
|
+
return `${model}'s enum ${first} gives "${method}" for two of its names; ${off === "" ? "rename one" : "map one to a name of your own"}${off}`;
|
|
2548
|
+
}
|
|
2549
|
+
/** `offFix`, naming the enum: for a message about two of them. */
|
|
2550
|
+
function namedOffFix(attribute, checks) {
|
|
2551
|
+
const fix = checks.methodsOffFix(attribute);
|
|
2552
|
+
return fix === void 0 ? "" : `, or leave ${attribute}'s methods off (remove ${fix})`;
|
|
2553
|
+
}
|
|
2554
|
+
/** How to fix an enum whose method name is taken: an affix, or for the database's, its methods off. */
|
|
2555
|
+
const remedy = (attribute, checks) => `give ${attribute} a prefix or a suffix${offFix(attribute, checks)}`;
|
|
2556
|
+
/** For an enum whose names the database gave (#64): leaving its methods off, as they start. */
|
|
2557
|
+
function offFix(attribute, checks) {
|
|
2558
|
+
const fix = checks.methodsOffFix(attribute);
|
|
2559
|
+
return fix === void 0 ? "" : `, or leave its methods off (remove ${fix})`;
|
|
2560
|
+
}
|
|
2561
|
+
function recordProblem(model, attribute, methods, checks) {
|
|
2562
|
+
for (const method of methods) {
|
|
2563
|
+
const what = model.attributeDefinitions.has(method) ? "an attribute" : checks.isRecordName(method) ? "a record method" : void 0;
|
|
2564
|
+
if (what !== void 0) return `${model.name}'s enum ${attribute} gives a method named "${method}", which is the name of ${what}; ${remedy(attribute, checks)}`;
|
|
1806
2565
|
}
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
2566
|
+
}
|
|
2567
|
+
function staticProblem(model, attribute, scopes, checks) {
|
|
2568
|
+
for (const scope of scopes) {
|
|
2569
|
+
const what = scope in Function.prototype ? "a Function method" : checks.isReservedStatic(scope) ? "a Relation method or a Model static" : void 0;
|
|
2570
|
+
if (what !== void 0) return `${model.name}'s enum ${attribute} gives a scope named "${scope}", which is the name of ${what}; ${remedy(attribute, checks)}`;
|
|
2571
|
+
const declared = checks.staticOf(scope);
|
|
2572
|
+
const isEnumScope = typeof declared?.value === "function" && enumScopes.has(declared.value);
|
|
2573
|
+
if (declared !== void 0 && !isEnumScope) return `${model.name} declares "${scope}", which is also the name of a scope its enum ${attribute} gives; rename it, or ${remedy(attribute, checks)}`;
|
|
1810
2574
|
}
|
|
1811
|
-
}
|
|
2575
|
+
}
|
|
1812
2576
|
// src/enum-switch.ts
|
|
1813
2577
|
/** Takes an override's `enum: true` or `false` out of it, so its other changes are checked as any override's. */
|
|
1814
2578
|
function takeEnumSwitch(override) {
|
|
@@ -1877,6 +2641,7 @@ function methodsOffFixes(model) {
|
|
|
1877
2641
|
}
|
|
1878
2642
|
// src/generated-model.ts
|
|
1879
2643
|
const noAttributes = /* @__PURE__ */ new Map();
|
|
2644
|
+
const noAliases = /* @__PURE__ */ new Map();
|
|
1880
2645
|
/**
|
|
1881
2646
|
* What each generated Model settled on when it was first used, by class (a subclass shares its
|
|
1882
2647
|
* parent's). Until then, they're found again on each read, since a `static {}` block reads them
|
|
@@ -1904,7 +2669,10 @@ function tableOwnerOf(model) {
|
|
|
1904
2669
|
schema
|
|
1905
2670
|
};
|
|
1906
2671
|
}
|
|
1907
|
-
/**
|
|
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
|
+
*/
|
|
1908
2676
|
function defineAttributeAccessors(prototype, names) {
|
|
1909
2677
|
for (const name of names) Object.defineProperty(prototype, name, {
|
|
1910
2678
|
get() {
|
|
@@ -1936,12 +2704,16 @@ function find(owner, schema) {
|
|
|
1936
2704
|
rejectUngenerated(name, table, schema);
|
|
1937
2705
|
const tableSchema = Object.hasOwn(schema.tables, table) ? schema.tables[table] : void 0;
|
|
1938
2706
|
if (tableSchema === void 0) throw new InvalidModel(`${owner.name}'s table, ${table}, isn't in the generated schema`);
|
|
1939
|
-
const
|
|
2707
|
+
const declared = withSecurePasswords(`${owner.name}.`, owner.attributes ?? {});
|
|
2708
|
+
const { specs, isIgnoringColumns } = specsFor(owner.name, tableSchema, declared);
|
|
1940
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);
|
|
1941
2712
|
return {
|
|
1942
2713
|
table,
|
|
1943
2714
|
primaryKey: Object.hasOwn(owner, "primaryKey") ? owner.primaryKey : tableSchema.primaryKey,
|
|
1944
2715
|
definitions,
|
|
2716
|
+
aliases,
|
|
1945
2717
|
isIgnoringColumns
|
|
1946
2718
|
};
|
|
1947
2719
|
}
|
|
@@ -1969,9 +2741,11 @@ function settleGenerated(model) {
|
|
|
1969
2741
|
if (found === void 0) {
|
|
1970
2742
|
found = find(owner, place.schema);
|
|
1971
2743
|
bindTable(owner, found.table, { isIgnoringColumns: found.isIgnoringColumns });
|
|
1972
|
-
defineAttributeAccessors(owner.prototype, found.definitions.keys());
|
|
2744
|
+
defineAttributeAccessors(owner.prototype, [...found.definitions.keys(), ...found.aliases.keys()]);
|
|
1973
2745
|
defineEnumMethods(owner.prototype, found.definitions);
|
|
1974
2746
|
defineEnumStatics(owner, found.definitions);
|
|
2747
|
+
defineSecurePasswordMethods(owner.prototype, found.definitions);
|
|
2748
|
+
defineSecureTokenMethods(owner.prototype, found.definitions);
|
|
1975
2749
|
settled.set(owner, found);
|
|
1976
2750
|
}
|
|
1977
2751
|
settled.set(model, found);
|
|
@@ -1999,7 +2773,8 @@ function defineGeneratedStatics(root) {
|
|
|
1999
2773
|
const statics = {
|
|
2000
2774
|
table: (model) => generated(model)?.table ?? "",
|
|
2001
2775
|
primaryKey: (model) => generated(model)?.primaryKey ?? "id",
|
|
2002
|
-
attributeDefinitions: (model) => generated(model)?.definitions ?? noAttributes
|
|
2776
|
+
attributeDefinitions: (model) => generated(model)?.definitions ?? noAttributes,
|
|
2777
|
+
attributeAliases: (model) => generated(model)?.aliases ?? noAliases
|
|
2003
2778
|
};
|
|
2004
2779
|
for (const [name, read] of Object.entries(statics)) Object.defineProperty(root, name, {
|
|
2005
2780
|
configurable: true,
|
|
@@ -2038,8 +2813,14 @@ function checkedOverride(where, spec, override) {
|
|
|
2038
2813
|
/** A table's attribute specs with `overrides` applied; throws `InvalidModel` for a bad one. */
|
|
2039
2814
|
function specsFor(name, table, overrides) {
|
|
2040
2815
|
const changes = /* @__PURE__ */ new Map();
|
|
2041
|
-
|
|
2816
|
+
const virtual = {};
|
|
2817
|
+
const given = Object.entries(overrides).filter(([, override]) => !isAlias(override));
|
|
2818
|
+
for (const [attribute, override] of given) {
|
|
2042
2819
|
if (override === void 0) continue;
|
|
2820
|
+
if (isVirtual(override)) {
|
|
2821
|
+
virtual[attribute] = virtualSpec(name, attribute, table, override);
|
|
2822
|
+
continue;
|
|
2823
|
+
}
|
|
2043
2824
|
if (!Object.hasOwn(table.attributes, attribute)) throw new InvalidModel(`${name} has no attribute ${attribute} to override`);
|
|
2044
2825
|
if (override === false && attribute === table.primaryKey) throw new InvalidModel(`${name}.${attribute} is the primary key, so it can't be ignored`);
|
|
2045
2826
|
changes.set(attribute, checked(name, attribute, override));
|
|
@@ -2051,8 +2832,27 @@ function specsFor(name, table, overrides) {
|
|
|
2051
2832
|
specs[attribute] = change === void 0 ? spec : checkedOverride(`${name}.${attribute}`, spec, change);
|
|
2052
2833
|
}
|
|
2053
2834
|
return {
|
|
2054
|
-
specs
|
|
2835
|
+
specs: {
|
|
2836
|
+
...specs,
|
|
2837
|
+
...virtual
|
|
2838
|
+
},
|
|
2055
2839
|
isIgnoringColumns: [...changes.values()].includes(false)
|
|
2056
2840
|
};
|
|
2057
2841
|
}
|
|
2058
|
-
|
|
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 };
|