@forestfuture/active-record 0.0.0 → 0.7.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/LICENSE +21 -0
- package/README.md +27 -2
- package/config-schema.json +56 -0
- package/dist/adapter-AGKp6wfO.d.mts +1326 -0
- package/dist/adapter.d.mts +3 -0
- package/dist/adapter.mjs +4 -0
- package/dist/batch-BS_WseLf.mjs +4255 -0
- package/dist/cli.d.mts +345 -0
- package/dist/cli.mjs +4 -0
- package/dist/command.d.mts +1 -0
- package/dist/command.mjs +2471 -0
- package/dist/d1.d.mts +68 -0
- package/dist/d1.mjs +0 -0
- package/dist/epoch-storage-o2aoOH7H.mjs +112 -0
- package/dist/for-adapters-Ch6CoHD4.mjs +240 -0
- package/dist/for-adapters-D_Iu0gS_.mjs +33 -0
- package/dist/for-adapters-t3-LukJQ.d.mts +21 -0
- package/dist/generated-model-Cnt0Ot9q.mjs +1857 -0
- package/dist/index-CyCJuM96.d.mts +149 -0
- package/dist/index.d.mts +3 -0
- package/dist/index.mjs +4 -0
- package/dist/plugin-Cyoej7qV.mjs +600 -0
- package/dist/plugin-XOHYndhP.mjs +939 -0
- package/dist/postgresql.d.mts +72 -0
- package/dist/postgresql.mjs +588 -0
- package/dist/src-la_KkjCS.mjs +1 -0
- package/dist/storage-override-CpbkdIqE.mjs +187 -0
- package/llms-full.txt +5033 -0
- package/package.json +65 -4
- package/skills/active-record/SKILL.md +88 -0
|
@@ -0,0 +1,1857 @@
|
|
|
1
|
+
import { a as underscore, n as pluralize, t as epochStorages } from "./epoch-storage-o2aoOH7H.mjs";
|
|
2
|
+
//#region src/errors.ts
|
|
3
|
+
/** Base class for every error the library throws on purpose. */
|
|
4
|
+
var ActiveRecordError = class extends Error {
|
|
5
|
+
name = "ActiveRecordError";
|
|
6
|
+
};
|
|
7
|
+
/** A Model's declaration is invalid, e.g. an association's foreign key isn't an attribute. */
|
|
8
|
+
var InvalidModel = class extends ActiveRecordError {
|
|
9
|
+
name = "InvalidModel";
|
|
10
|
+
};
|
|
11
|
+
/** A key that isn't a declared attribute of the Model. */
|
|
12
|
+
var UnknownAttribute = class extends ActiveRecordError {
|
|
13
|
+
name = "UnknownAttribute";
|
|
14
|
+
};
|
|
15
|
+
/** A record constructed directly (`new User()`) was used for something that needs D1. */
|
|
16
|
+
var NoDatabase = class extends ActiveRecordError {
|
|
17
|
+
name = "NoDatabase";
|
|
18
|
+
};
|
|
19
|
+
/** No record matched a lookup that requires one (`find`, `findByOrThrow`). */
|
|
20
|
+
var RecordNotFound = class extends ActiveRecordError {
|
|
21
|
+
name = "RecordNotFound";
|
|
22
|
+
};
|
|
23
|
+
/** Reading an attribute that wasn't loaded, e.g. one left out of `select(...)`. */
|
|
24
|
+
var MissingAttribute = class extends ActiveRecordError {
|
|
25
|
+
name = "MissingAttribute";
|
|
26
|
+
};
|
|
27
|
+
/** Destroying a record whose `dependent: "restrictWithException"` association still has records. */
|
|
28
|
+
var DeleteRestriction = class extends ActiveRecordError {
|
|
29
|
+
name = "DeleteRestriction";
|
|
30
|
+
};
|
|
31
|
+
/** `last()` can't reverse an order given as an `sql` fragment (Rails' IrreversibleOrderError). */
|
|
32
|
+
var IrreversibleOrder = class extends ActiveRecordError {
|
|
33
|
+
name = "IrreversibleOrder";
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Things that can't be combined: relations in `or`/`merge` (e.g. of different Models),
|
|
37
|
+
* `includes` or a write statement with `distinct()`, or statements of two Databases in a batch.
|
|
38
|
+
*/
|
|
39
|
+
var IncompatibleRelation = class extends ActiveRecordError {
|
|
40
|
+
name = "IncompatibleRelation";
|
|
41
|
+
};
|
|
42
|
+
/** Using a destroyed record as a live one: `save`, `update`, `destroy` or `reload` after `destroy()`. */
|
|
43
|
+
var RecordDestroyed = class extends ActiveRecordError {
|
|
44
|
+
name = "RecordDestroyed";
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* D1 rejected a write because of a database constraint. `table`, `columns` and `attributes`
|
|
48
|
+
* are filled in when D1's message names them. `table` is null only for a batch writing to
|
|
49
|
+
* several tables, when D1 doesn't say which one failed. The original D1 error is the `cause`.
|
|
50
|
+
*/
|
|
51
|
+
var ConstraintViolation = class extends ActiveRecordError {
|
|
52
|
+
name = "ConstraintViolation";
|
|
53
|
+
table;
|
|
54
|
+
columns;
|
|
55
|
+
attributes;
|
|
56
|
+
constructor(message, details) {
|
|
57
|
+
super(message, { cause: details.cause });
|
|
58
|
+
this.table = details.table;
|
|
59
|
+
this.columns = details.columns;
|
|
60
|
+
this.attributes = details.attributes;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
/** A UNIQUE constraint failed, e.g. another request won the race after validation passed. */
|
|
64
|
+
var RecordNotUnique = class extends ConstraintViolation {
|
|
65
|
+
name = "RecordNotUnique";
|
|
66
|
+
};
|
|
67
|
+
/** A FOREIGN KEY constraint failed. SQLite's message doesn't name the column. */
|
|
68
|
+
var InvalidForeignKey = class extends ConstraintViolation {
|
|
69
|
+
name = "InvalidForeignKey";
|
|
70
|
+
};
|
|
71
|
+
/** A NOT NULL constraint failed. */
|
|
72
|
+
var NotNullViolation = class extends ConstraintViolation {
|
|
73
|
+
name = "NotNullViolation";
|
|
74
|
+
};
|
|
75
|
+
/** A CHECK constraint failed. */
|
|
76
|
+
var CheckViolation = class extends ConstraintViolation {
|
|
77
|
+
name = "CheckViolation";
|
|
78
|
+
};
|
|
79
|
+
/** A `…OrThrow` save was refused because the record is invalid; `record.errors` says why. */
|
|
80
|
+
var RecordInvalid = class extends ActiveRecordError {
|
|
81
|
+
name = "RecordInvalid";
|
|
82
|
+
record;
|
|
83
|
+
constructor(record) {
|
|
84
|
+
super(`Validation failed: ${record.errors.fullMessages().join(", ")}`);
|
|
85
|
+
this.record = record;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Thrown by a callback to refuse a save or destroy: `throw abort("Account is suspended")`.
|
|
90
|
+
* Only this exact class halts a lifecycle; returning `false` never does.
|
|
91
|
+
*/
|
|
92
|
+
var CallbackAbort = class extends ActiveRecordError {
|
|
93
|
+
name = "CallbackAbort";
|
|
94
|
+
reason;
|
|
95
|
+
constructor(reason) {
|
|
96
|
+
super(reason);
|
|
97
|
+
this.reason = reason;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
/** Makes the sentinel a pre-write callback throws to refuse: `throw abort("reason")`. */
|
|
101
|
+
function abort(reason = "Aborted by a callback") {
|
|
102
|
+
return new CallbackAbort(reason);
|
|
103
|
+
}
|
|
104
|
+
/** A `…OrThrow` save was refused by a callback's `abort(reason)`. */
|
|
105
|
+
var RecordNotSaved = class extends ActiveRecordError {
|
|
106
|
+
name = "RecordNotSaved";
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* `abort()` was thrown from an after-write callback (`afterSave`, `afterCreate`, `afterUpdate`,
|
|
110
|
+
* `afterDestroy`). That's a mistake: the save or destroy already succeeded and nothing rolls back.
|
|
111
|
+
*/
|
|
112
|
+
var AbortAfterPersistence = class extends ActiveRecordError {
|
|
113
|
+
name = "AbortAfterPersistence";
|
|
114
|
+
callback;
|
|
115
|
+
reason;
|
|
116
|
+
constructor(callback, lifecycle, abortion) {
|
|
117
|
+
super(`abort() in ${callback}: the ${lifecycle} has already succeeded`, { cause: abortion });
|
|
118
|
+
this.callback = callback;
|
|
119
|
+
this.reason = abortion.reason;
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
/** A `destroyOrThrow()` was refused by a `beforeDestroy` callback's `abort(reason)`. */
|
|
123
|
+
var RecordNotDestroyed = class extends ActiveRecordError {
|
|
124
|
+
name = "RecordNotDestroyed";
|
|
125
|
+
};
|
|
126
|
+
/** A name passed to `includes()` or `loaded()` that isn't one of the Model's associations. */
|
|
127
|
+
var UnknownAssociation = class extends ActiveRecordError {
|
|
128
|
+
name = "UnknownAssociation";
|
|
129
|
+
};
|
|
130
|
+
/** `record.loaded(name)` for an association that wasn't preloaded or read yet. */
|
|
131
|
+
var AssociationNotLoaded = class extends ActiveRecordError {
|
|
132
|
+
name = "AssociationNotLoaded";
|
|
133
|
+
};
|
|
134
|
+
//#endregion
|
|
135
|
+
//#region src/ancestors.ts
|
|
136
|
+
/** A class and every class (and object) it extends, nearest first. */
|
|
137
|
+
function ancestors(model) {
|
|
138
|
+
const chain = [];
|
|
139
|
+
for (let current = model; current !== null; current = Object.getPrototypeOf(current)) chain.push(current);
|
|
140
|
+
return chain;
|
|
141
|
+
}
|
|
142
|
+
//#endregion
|
|
143
|
+
//#region src/table-names.ts
|
|
144
|
+
/**
|
|
145
|
+
* The classes `Model.define({...})` makes; their `table` is inferred unless a subclass sets one.
|
|
146
|
+
* Module-level, but not request state (ADR-0003): derived only from the classes.
|
|
147
|
+
*/
|
|
148
|
+
const bases = /* @__PURE__ */ new WeakSet();
|
|
149
|
+
/**
|
|
150
|
+
* Each generated Model's table, by the class it belongs to, and whether its `static attributes`
|
|
151
|
+
* ignore some of its columns (`{ notes: false }`).
|
|
152
|
+
*/
|
|
153
|
+
const boundTables = /* @__PURE__ */ new WeakMap();
|
|
154
|
+
/**
|
|
155
|
+
* Each Model's answer to `ignoresColumns`, remembered since the compiler asks on every query.
|
|
156
|
+
* Module-level, but not request state (ADR-0003): derived only from the class.
|
|
157
|
+
*/
|
|
158
|
+
const ignoring = /* @__PURE__ */ new WeakMap();
|
|
159
|
+
/**
|
|
160
|
+
* The name of the class that extends `base` directly, the one a table is named after, as in
|
|
161
|
+
* Rails; empty when it has none (anonymous, `export default`, or `Model.define({...})` itself).
|
|
162
|
+
*/
|
|
163
|
+
function className(base, model) {
|
|
164
|
+
let current = model;
|
|
165
|
+
while (current !== base && Object.getPrototypeOf(current) !== base) current = Object.getPrototypeOf(current);
|
|
166
|
+
const { name } = current;
|
|
167
|
+
return current === base || name === "default" ? "" : name;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* A class name's table, by Rails' `tableize`: the name through `underscore`, pluralized
|
|
171
|
+
* (`BlogPost` → `blog_posts`, `Person` → `people`). The generators name tables with it too.
|
|
172
|
+
*/
|
|
173
|
+
function tableize(className) {
|
|
174
|
+
return pluralize(underscore(className));
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* The setter of a static that a class can set for itself: an assignment (a static block, or a
|
|
178
|
+
* class field compiled without useDefineForClassFields) gives that class its own value, as
|
|
179
|
+
* `static table = "…"` does.
|
|
180
|
+
*/
|
|
181
|
+
function ownValueSetter(name) {
|
|
182
|
+
return function(value) {
|
|
183
|
+
Object.defineProperty(this, name, {
|
|
184
|
+
value,
|
|
185
|
+
writable: true,
|
|
186
|
+
enumerable: true,
|
|
187
|
+
configurable: true
|
|
188
|
+
});
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Gives the classes extending `base` (one `define` made) an inferred `table`, by `tableize`. A
|
|
193
|
+
* subclass shares its parent's; `static table = "…"` anywhere in the chain overrides it.
|
|
194
|
+
*/
|
|
195
|
+
function inferTableNames(base) {
|
|
196
|
+
bases.add(base);
|
|
197
|
+
Object.defineProperty(base, "table", {
|
|
198
|
+
configurable: true,
|
|
199
|
+
get() {
|
|
200
|
+
const name = className(base, this);
|
|
201
|
+
return name === "" ? "" : tableize(name);
|
|
202
|
+
},
|
|
203
|
+
set: ownValueSetter("table")
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
/** The class name a Model's table name was inferred from, or undefined when it's declared. */
|
|
207
|
+
function tableNameSource(model) {
|
|
208
|
+
const owner = ancestors(model).find((each) => Object.hasOwn(each, "table"));
|
|
209
|
+
return owner !== void 0 && bases.has(owner) && !boundTables.has(owner) ? className(owner, model) : void 0;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Binds a generated Model's table to the class it belongs to: a subclass can't name another,
|
|
213
|
+
* since the attributes are that table's columns; and records whether its overrides ignore some
|
|
214
|
+
* columns.
|
|
215
|
+
*/
|
|
216
|
+
function bindTable(owner, table, { ignoresColumns }) {
|
|
217
|
+
owner.table = table;
|
|
218
|
+
boundTables.set(owner, {
|
|
219
|
+
table,
|
|
220
|
+
ignoresColumns
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
/** The table bound to the class `model` is, or extends, if any. */
|
|
224
|
+
function boundTableOf(model) {
|
|
225
|
+
const owner = ancestors(model).find((each) => boundTables.has(each));
|
|
226
|
+
return owner && {
|
|
227
|
+
...boundTables.get(owner),
|
|
228
|
+
owner
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Whether a Model ignores some of its table's columns, so its queries name their columns rather
|
|
233
|
+
* than `*` and an ignored column is never read, as in Rails. The nearest bound table decides.
|
|
234
|
+
* Remembered per Model: its table is bound when it's first used, before any query, so the
|
|
235
|
+
* answer can't change.
|
|
236
|
+
*/
|
|
237
|
+
function ignoresColumns(model) {
|
|
238
|
+
let answer = ignoring.get(model);
|
|
239
|
+
if (answer === void 0) {
|
|
240
|
+
answer = boundTableOf(model)?.ignoresColumns ?? false;
|
|
241
|
+
ignoring.set(model, answer);
|
|
242
|
+
}
|
|
243
|
+
return answer;
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* An abstract base class (the app's `ApplicationRecord`, or one marked `static abstract = true`)
|
|
247
|
+
* has no table, as Rails' `abstract_class`: it's only inherited from, so using it is an
|
|
248
|
+
* `InvalidModel`.
|
|
249
|
+
*/
|
|
250
|
+
function rejectAbstract(model) {
|
|
251
|
+
if (ancestors(model).some((each) => bases.has(each))) return;
|
|
252
|
+
const example = model.name ? `, such as class Product extends ${model.name} {}` : "";
|
|
253
|
+
throw new InvalidModel(`${model.name || "This class"} is an abstract base class, with no table; use a Model that extends it${example}`);
|
|
254
|
+
}
|
|
255
|
+
/** A Model must have a table name: its own, or one inferred from its class name. */
|
|
256
|
+
function requireTableName(model) {
|
|
257
|
+
const { table } = model;
|
|
258
|
+
const bound = boundTableOf(model);
|
|
259
|
+
if (bound !== void 0 && table !== bound.table) throw new InvalidModel(`${model.name} sets table "${String(table)}", but its attributes are the ${bound.table} table's, as ${bound.owner.name}'s are; a subclass shares its parent's table`);
|
|
260
|
+
if (typeof table === "string" && table !== "") return;
|
|
261
|
+
throw new InvalidModel(tableNameSource(model) === "" ? `${model.name || "A Model class"} has no class name to infer its table from; set static table` : `${model.name}'s table must be a table's name; remove it to use the one inferred from the class name`);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* A database's "no such table" for a table whose name was inferred, as an `InvalidModel` saying where
|
|
265
|
+
* the name came from (a bundler may have renamed the class). Any other error is returned as is.
|
|
266
|
+
*/
|
|
267
|
+
function explainMissingTable(adapter, error, models) {
|
|
268
|
+
const table = adapter.missingTable(error);
|
|
269
|
+
const model = models.find((each) => each.table === table && tableNameSource(each));
|
|
270
|
+
const source = model && tableNameSource(model);
|
|
271
|
+
if (table === void 0 || model === void 0) return error;
|
|
272
|
+
return new InvalidModel(`${model.name}'s table "${table}" doesn't exist in ${adapter.name} (inferred from the class name ${source}; create it, set static table, or keep class names if your bundler renames them)`, { cause: error });
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* The class name a Model's names are inferred from, its foreign keys': the class whose table it
|
|
276
|
+
* is (`Post`, for `class FeaturedPost extends Post {}`).
|
|
277
|
+
*/
|
|
278
|
+
function modelClassName(model) {
|
|
279
|
+
const base = ancestors(model).find((each) => bases.has(each));
|
|
280
|
+
if (base !== void 0) return className(base, model);
|
|
281
|
+
return (boundTableOf(model)?.owner ?? model).name;
|
|
282
|
+
}
|
|
283
|
+
//#endregion
|
|
284
|
+
//#region src/filtering.ts
|
|
285
|
+
/** What a listener sees in place of a filtered attribute's value (#83). */
|
|
286
|
+
const FILTERED = "[FILTERED]";
|
|
287
|
+
/**
|
|
288
|
+
* Rails' default `filter_parameters` for a new app: an attribute whose snake_case name holds
|
|
289
|
+
* one of these, in any case, is filtered (`passwordDigest`, `apiKey`, `resetToken`, `email`).
|
|
290
|
+
*/
|
|
291
|
+
const defaultFilterAttributes = [
|
|
292
|
+
"passw",
|
|
293
|
+
"email",
|
|
294
|
+
"secret",
|
|
295
|
+
"token",
|
|
296
|
+
"_key",
|
|
297
|
+
"crypt",
|
|
298
|
+
"salt",
|
|
299
|
+
"certificate",
|
|
300
|
+
"otp",
|
|
301
|
+
"ssn",
|
|
302
|
+
"cvv",
|
|
303
|
+
"cvc"
|
|
304
|
+
];
|
|
305
|
+
/**
|
|
306
|
+
* Whether `attribute`'s values are hidden from listeners: its snake_case name holds a string
|
|
307
|
+
* entry (in any case), or a RegExp entry matches the attribute or its snake_case name.
|
|
308
|
+
*/
|
|
309
|
+
function isFiltered(model, attribute) {
|
|
310
|
+
const name = underscore(attribute);
|
|
311
|
+
return model.filterAttributes.some((entry) => typeof entry === "string" ? name.includes(entry.toLowerCase()) : attribute.search(entry) !== -1 || name.search(entry) !== -1);
|
|
312
|
+
}
|
|
313
|
+
/** A bound value D1 gets as `value`, and listeners see as `shown`. */
|
|
314
|
+
var Filtered = class {
|
|
315
|
+
value;
|
|
316
|
+
shown;
|
|
317
|
+
constructor(value, shown = FILTERED) {
|
|
318
|
+
this.value = value;
|
|
319
|
+
this.shown = shown;
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
/** A primary key as an error shows it: "[FILTERED]" when the key is a filtered attribute. */
|
|
323
|
+
function shownKey(model, key) {
|
|
324
|
+
return isFiltered(model, model.primaryKey) ? FILTERED : String(key);
|
|
325
|
+
}
|
|
326
|
+
/** The value D1 binds. */
|
|
327
|
+
function boundValue(param) {
|
|
328
|
+
return param instanceof Filtered ? param.value : param;
|
|
329
|
+
}
|
|
330
|
+
/** The value listeners see. */
|
|
331
|
+
function shownValue$1(param) {
|
|
332
|
+
return param instanceof Filtered ? param.shown : param;
|
|
333
|
+
}
|
|
334
|
+
//#endregion
|
|
335
|
+
//#region src/conversion.ts
|
|
336
|
+
/** A value that can't be read as the attribute's type. */
|
|
337
|
+
const uncastable = Symbol("uncastable");
|
|
338
|
+
const identity = (value) => value;
|
|
339
|
+
const keyOf = ({ type, storage }) => storage ?? type;
|
|
340
|
+
const converters = {
|
|
341
|
+
string: {
|
|
342
|
+
cast: text,
|
|
343
|
+
read: text,
|
|
344
|
+
write: identity
|
|
345
|
+
},
|
|
346
|
+
integer: {
|
|
347
|
+
cast: castInteger,
|
|
348
|
+
read: safeInteger,
|
|
349
|
+
write: identity
|
|
350
|
+
},
|
|
351
|
+
real: {
|
|
352
|
+
cast: castReal,
|
|
353
|
+
read: finiteNumber,
|
|
354
|
+
write: identity
|
|
355
|
+
},
|
|
356
|
+
boolean: {
|
|
357
|
+
cast: castBoolean,
|
|
358
|
+
read: readBoolean,
|
|
359
|
+
write: (value) => value ? 1 : 0
|
|
360
|
+
},
|
|
361
|
+
datetime: {
|
|
362
|
+
cast: castDatetime,
|
|
363
|
+
read: readDatetime,
|
|
364
|
+
write: (value) => value.toISOString()
|
|
365
|
+
},
|
|
366
|
+
unixSeconds: {
|
|
367
|
+
cast: castDatetime,
|
|
368
|
+
read: unixTime(1e3),
|
|
369
|
+
write: (value) => Math.floor(value.getTime() / 1e3)
|
|
370
|
+
},
|
|
371
|
+
unixMilliseconds: {
|
|
372
|
+
cast: castDatetime,
|
|
373
|
+
read: unixTime(1),
|
|
374
|
+
write: (value) => value.getTime()
|
|
375
|
+
},
|
|
376
|
+
json: {
|
|
377
|
+
cast: castJson,
|
|
378
|
+
read: readJson,
|
|
379
|
+
write: (value) => JSON.stringify(value)
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
/** `value` as the attribute's type (null stays null), or `uncastable`. */
|
|
383
|
+
function castValue(attribute, value) {
|
|
384
|
+
return value === null ? null : converters[keyOf(attribute)].cast(value);
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* A condition's value as the attribute's type, or `uncastable`: as `castValue`, except that a
|
|
388
|
+
* finite number matches a string attribute as its decimal string (`7` → `"7"`), as `find` does
|
|
389
|
+
* for a text key and as Rails does, so a foreign key of another type still finds its target.
|
|
390
|
+
*/
|
|
391
|
+
function castCondition(attribute, value) {
|
|
392
|
+
if (attribute.type === "string" && typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
393
|
+
return castValue(attribute, value);
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* A stored value as the attribute's, or `uncastable` for one that isn't. `Attribute#read`, in
|
|
397
|
+
* attribute.ts, is how a cell D1 returned is read, so it fails naming its attribute.
|
|
398
|
+
*/
|
|
399
|
+
function readValue(attribute, value) {
|
|
400
|
+
return value === null || value === void 0 ? null : converters[keyOf(attribute)].read(value);
|
|
401
|
+
}
|
|
402
|
+
function writeValue(attribute, value) {
|
|
403
|
+
return value === null || value === void 0 ? null : converters[keyOf(attribute)].write(value);
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Converts a value with no declared attribute type (e.g. one interpolated into
|
|
407
|
+
* an `sql` fragment) using the converter its runtime type implies, so it's
|
|
408
|
+
* stored the same way as an attribute of that type.
|
|
409
|
+
*/
|
|
410
|
+
function writeUntypedValue(value) {
|
|
411
|
+
if (value instanceof Date) return writeValue({ type: "datetime" }, value);
|
|
412
|
+
if (typeof value === "boolean") return writeValue({ type: "boolean" }, value);
|
|
413
|
+
return value;
|
|
414
|
+
}
|
|
415
|
+
const booleans = /* @__PURE__ */ new Map([
|
|
416
|
+
[true, true],
|
|
417
|
+
[false, false],
|
|
418
|
+
[1, true],
|
|
419
|
+
[0, false],
|
|
420
|
+
["1", true],
|
|
421
|
+
["0", false],
|
|
422
|
+
["true", true],
|
|
423
|
+
["false", false],
|
|
424
|
+
["on", true],
|
|
425
|
+
["off", false]
|
|
426
|
+
]);
|
|
427
|
+
/** `true`/`false`, `1`/`0`, `"1"`/`"0"`, and `"true"`/`"false"` or `"on"`/`"off"` in any case. */
|
|
428
|
+
function castBoolean(value) {
|
|
429
|
+
const key = typeof value === "string" ? value.toLowerCase() : value;
|
|
430
|
+
return booleans.has(key) ? booleans.get(key) : uncastable;
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Any value JSON can write, as it is. What `stringify` writes lossily (a `Map` as `{}`, `NaN` as
|
|
434
|
+
* `null`) is kept; what it throws on (a BigInt, a cycle) or gives nothing for (a function, a
|
|
435
|
+
* symbol) is refused (#146). It's checked here, and written again at save, so a value is
|
|
436
|
+
* refused where it's assigned rather than where it's stored, and the cost is one more
|
|
437
|
+
* `stringify` per assignment.
|
|
438
|
+
*/
|
|
439
|
+
function castJson(value) {
|
|
440
|
+
try {
|
|
441
|
+
return JSON.stringify(value) === void 0 ? uncastable : value;
|
|
442
|
+
} catch {
|
|
443
|
+
return uncastable;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Text is parsed; one that isn't JSON is `uncastable`. Under a column declared JSON, SQLite
|
|
448
|
+
* stores a number-like value (123) as a number, and D1 returns it as one, which is already the
|
|
449
|
+
* value.
|
|
450
|
+
*/
|
|
451
|
+
function readJson(value) {
|
|
452
|
+
if (typeof value !== "string") return value;
|
|
453
|
+
try {
|
|
454
|
+
return JSON.parse(value);
|
|
455
|
+
} catch {
|
|
456
|
+
return uncastable;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
/** A whole number, signed, with nothing else but spaces around it. */
|
|
460
|
+
const integerText = /^\s*[+-]?\d+\s*$/;
|
|
461
|
+
/**
|
|
462
|
+
* A decimal number, with an optional exponent (`1.5`, `-2e3`, `.5`), and spaces around it.
|
|
463
|
+
* Digits after the point only follow a point, so no run of digits can match two ways: an
|
|
464
|
+
* optional point between two runs of digits backtracks quadratically on a long string (ReDoS).
|
|
465
|
+
*/
|
|
466
|
+
const realText = /^\s*[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?\s*$/i;
|
|
467
|
+
/** `value` as a number: a number as it is, or a string matching `pattern`; else `uncastable`. */
|
|
468
|
+
function numberFrom(value, pattern) {
|
|
469
|
+
if (typeof value === "number") return value;
|
|
470
|
+
return typeof value === "string" && pattern.test(value) ? Number(value) : uncastable;
|
|
471
|
+
}
|
|
472
|
+
/** `value` if it's text, else `uncastable`. */
|
|
473
|
+
function text(value) {
|
|
474
|
+
return typeof value === "string" ? value : uncastable;
|
|
475
|
+
}
|
|
476
|
+
/** `value` if it's a safe integer, else `uncastable`. */
|
|
477
|
+
function safeInteger(value) {
|
|
478
|
+
return Number.isSafeInteger(value) ? value : uncastable;
|
|
479
|
+
}
|
|
480
|
+
/** `value` if it's a finite number, else `uncastable`. */
|
|
481
|
+
function finiteNumber(value) {
|
|
482
|
+
return Number.isFinite(value) ? value : uncastable;
|
|
483
|
+
}
|
|
484
|
+
/** A safe integer, or a string that's wholly one: `1.7`, `"12abc"` and `"1e3"` aren't. */
|
|
485
|
+
function castInteger(value) {
|
|
486
|
+
return safeInteger(numberFrom(value, integerText));
|
|
487
|
+
}
|
|
488
|
+
/** A finite number, or a string that's wholly a decimal number. */
|
|
489
|
+
function castReal(value) {
|
|
490
|
+
return finiteNumber(numberFrom(value, realText));
|
|
491
|
+
}
|
|
492
|
+
/** A Unix time of this many milliseconds per unit as a `Date`; anything but a number is `uncastable`. */
|
|
493
|
+
function unixTime(millisecondsPer) {
|
|
494
|
+
return (value) => typeof value === "number" ? validDate(new Date(value * millisecondsPer)) : uncastable;
|
|
495
|
+
}
|
|
496
|
+
/** An ISO-8601 date: `2026-01-02`, read as midnight UTC. */
|
|
497
|
+
const isoDate = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
498
|
+
/** An ISO-8601 date and time, with `Z` or an offset: a time without one is ambiguous. */
|
|
499
|
+
const isoDateTime = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
500
|
+
/** A stored date and time with no zone, as SQLite's `CURRENT_TIMESTAMP` writes it: UTC (#73). */
|
|
501
|
+
const zonelessDateTime = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
|
|
502
|
+
/** What `toISOString` writes, the form datetimes are stored in: `2026-01-02T03:04:05.678Z`. */
|
|
503
|
+
const isoStringForm = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
504
|
+
/** What `toISOString` writes for a year outside 0000-9999: a sign and six digits (`+010000-…`). */
|
|
505
|
+
const expandedYearDateTime = /^[+-]\d{6}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
506
|
+
/**
|
|
507
|
+
* A stored datetime as a `Date`: text in a form an assignment accepts (an ISO date, or a date and
|
|
508
|
+
* time with its offset), what `toISOString` writes for a far year, or SQLite's own, with no
|
|
509
|
+
* zone, which is UTC, where `new Date` would read it in the process's time zone. A number isn't
|
|
510
|
+
* one: it's a Unix time (#73), and read as a time in ISO text it would be a moment in January
|
|
511
|
+
* 1970 (#159).
|
|
512
|
+
*/
|
|
513
|
+
function readDatetime(value) {
|
|
514
|
+
if (typeof value !== "string") return uncastable;
|
|
515
|
+
const stored = isoStringForm.test(value) ? dateIfOnCalendar(value) : void 0;
|
|
516
|
+
if (stored !== void 0) return stored;
|
|
517
|
+
if (expandedYearDateTime.test(value)) return dateIfCanonical(value) ?? uncastable;
|
|
518
|
+
return castDatetime(zonelessDateTime.test(value) ? `${value}Z` : value);
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Text in the stored form as a `Date`, if it names a moment on the calendar. `value` must match
|
|
522
|
+
* `isoStringForm`, which fixes where the month and day are. Every character is then a digit or a
|
|
523
|
+
* fixed separator, so only the calendar can be wrong, and `Date` rolls a day that
|
|
524
|
+
* doesn't exist over (`2026-02-30` to 2 March, `T24:00` to the next day): a date whose day or
|
|
525
|
+
* month isn't the text's is refused. Cheaper than writing the text back to compare (#216).
|
|
526
|
+
*/
|
|
527
|
+
function dateIfOnCalendar(value) {
|
|
528
|
+
const date = new Date(value);
|
|
529
|
+
const month = Number(value.slice(5, 7));
|
|
530
|
+
const day = Number(value.slice(8, 10));
|
|
531
|
+
return date.getUTCDate() === day && date.getUTCMonth() + 1 === month ? date : void 0;
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* `value` as a `Date`, if `toISOString` writes exactly this text for it. That also refuses a day
|
|
535
|
+
* that doesn't exist, and a year written with more digits than it needs (`+002026`).
|
|
536
|
+
*/
|
|
537
|
+
function dateIfCanonical(value) {
|
|
538
|
+
const date = new Date(value);
|
|
539
|
+
return !isInvalidDate(date) && date.toISOString() === value ? date : void 0;
|
|
540
|
+
}
|
|
541
|
+
/** `1` and `0` are the stored form of a boolean; any other cell isn't one. */
|
|
542
|
+
function readBoolean(value) {
|
|
543
|
+
if (value === 1) return true;
|
|
544
|
+
return value === 0 ? false : uncastable;
|
|
545
|
+
}
|
|
546
|
+
/** A valid `Date`, or an ISO-8601 string (a date, or a date and time with its offset). */
|
|
547
|
+
function castDatetime(value) {
|
|
548
|
+
if (value instanceof Date) return isInvalidDate(value) ? uncastable : value;
|
|
549
|
+
if (typeof value !== "string") return uncastable;
|
|
550
|
+
if (isoDate.test(value)) return dayOf(value) ?? uncastable;
|
|
551
|
+
if (!isoDateTime.test(value) || dayOf(value.slice(0, 10)) === void 0) return uncastable;
|
|
552
|
+
const date = new Date(value.replace(" ", "T"));
|
|
553
|
+
return isInvalidDate(date) ? uncastable : date;
|
|
554
|
+
}
|
|
555
|
+
/** `date`, or `uncastable` for an invalid one (a stored number past the range of a `Date`). */
|
|
556
|
+
function validDate(date) {
|
|
557
|
+
return isInvalidDate(date) ? uncastable : date;
|
|
558
|
+
}
|
|
559
|
+
/** Midnight UTC on `day` (`2026-01-02`), if that day exists. */
|
|
560
|
+
function dayOf(day) {
|
|
561
|
+
const date = /* @__PURE__ */ new Date(`${day}T00:00:00.000Z`);
|
|
562
|
+
return !isInvalidDate(date) && date.toISOString().startsWith(day) ? date : void 0;
|
|
563
|
+
}
|
|
564
|
+
function isInvalidDate(value) {
|
|
565
|
+
return value instanceof Date && Number.isNaN(value.getTime());
|
|
566
|
+
}
|
|
567
|
+
//#endregion
|
|
568
|
+
//#region src/spec-keys.ts
|
|
569
|
+
const attributeTypes = Object.keys({
|
|
570
|
+
string: true,
|
|
571
|
+
integer: true,
|
|
572
|
+
real: true,
|
|
573
|
+
boolean: true,
|
|
574
|
+
datetime: true,
|
|
575
|
+
json: true
|
|
576
|
+
});
|
|
577
|
+
/** Whether `value` names an attribute type. */
|
|
578
|
+
function isAttributeType(value) {
|
|
579
|
+
return attributeTypes.includes(value);
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Every key of a spec, in the order a message lists them. It's typed by `SpecObject`, so a key
|
|
583
|
+
* added there is a compile error until it has its rules here.
|
|
584
|
+
*/
|
|
585
|
+
const rules = {
|
|
586
|
+
type: {
|
|
587
|
+
isWellFormed: isAttributeType,
|
|
588
|
+
copiedToDefinition: false
|
|
589
|
+
},
|
|
590
|
+
null: {
|
|
591
|
+
isWellFormed: (value) => typeof value === "boolean",
|
|
592
|
+
copiedToDefinition: false
|
|
593
|
+
},
|
|
594
|
+
column: {
|
|
595
|
+
isWellFormed: (value) => typeof value === "string",
|
|
596
|
+
overridable: false,
|
|
597
|
+
copiedToDefinition: false
|
|
598
|
+
},
|
|
599
|
+
default: {
|
|
600
|
+
isWellFormed: (value) => typeof value === "function",
|
|
601
|
+
describedAs: "a default",
|
|
602
|
+
onRetype: "drop"
|
|
603
|
+
},
|
|
604
|
+
generateId: {
|
|
605
|
+
isWellFormed: (value) => typeof value === "boolean",
|
|
606
|
+
isGiven: (value) => value === true,
|
|
607
|
+
onlyFor: {
|
|
608
|
+
types: ["string"],
|
|
609
|
+
because: "generated ids are strings"
|
|
610
|
+
},
|
|
611
|
+
conflictsWith: ["default"],
|
|
612
|
+
onRetype: "drop"
|
|
613
|
+
},
|
|
614
|
+
storage: {
|
|
615
|
+
isWellFormed: (value) => typeof value === "string",
|
|
616
|
+
describedAs: "a storage",
|
|
617
|
+
allowedValues: epochStorages,
|
|
618
|
+
onlyFor: {
|
|
619
|
+
types: ["datetime"],
|
|
620
|
+
because: "only a datetime is stored as an epoch"
|
|
621
|
+
},
|
|
622
|
+
onRetype: "drop"
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
const entries = Object.entries(rules);
|
|
626
|
+
/** For each key, the keys it conflicts with, whichever of the two declares it. */
|
|
627
|
+
const conflicts = new Map(entries.map(([key]) => [key, []]));
|
|
628
|
+
for (const [key, { conflictsWith = [] }] of entries) for (const other of conflictsWith) {
|
|
629
|
+
conflicts.get(key).push(other);
|
|
630
|
+
conflicts.get(other).push(key);
|
|
631
|
+
}
|
|
632
|
+
/** The keys an override may hold, as a message lists them: `type, null, default, …`. */
|
|
633
|
+
const overridableKeyNames = entries.filter(([, rule]) => rule.overridable !== false).map(([key]) => key).join(", ");
|
|
634
|
+
/** The value of a key if it's given, else `undefined`. */
|
|
635
|
+
function givenValue(spec, key) {
|
|
636
|
+
const value = spec[key];
|
|
637
|
+
return (rules[key].isGiven ?? ((each) => each !== void 0))(value) ? value : void 0;
|
|
638
|
+
}
|
|
639
|
+
/** How a key reads in a message. */
|
|
640
|
+
const readsAs = (key) => rules[key].describedAs ?? key;
|
|
641
|
+
/** Whether `value` is an object holding only spec keys an override may change, each well formed or `undefined`. */
|
|
642
|
+
function isSpecOverride(value) {
|
|
643
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
644
|
+
return Object.entries(value).every(([key, each]) => {
|
|
645
|
+
if (!Object.hasOwn(rules, key) || rules[key].overridable === false) return false;
|
|
646
|
+
return each === void 0 || rules[key].isWellFormed(each);
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
/** The problem with `key` given together with a key it conflicts with. */
|
|
650
|
+
function conflictProblem(where, spec, key) {
|
|
651
|
+
const other = rules[key].conflictsWith?.find((each) => givenValue(spec, each) !== void 0);
|
|
652
|
+
return other === void 0 ? void 0 : `${where} has both ${readsAs(key)} and ${readsAs(other)}; keep one`;
|
|
653
|
+
}
|
|
654
|
+
/** A value as a message shows it: as JSON, or as text for one JSON can't write (a BigInt). */
|
|
655
|
+
function shown$1(value) {
|
|
656
|
+
try {
|
|
657
|
+
return JSON.stringify(value) ?? String(value);
|
|
658
|
+
} catch {
|
|
659
|
+
return String(value);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
/** The problem with a given key's value, or with its attribute's type. */
|
|
663
|
+
function valueProblem(where, spec, key) {
|
|
664
|
+
const { allowedValues, onlyFor } = rules[key];
|
|
665
|
+
const value = givenValue(spec, key);
|
|
666
|
+
if (allowedValues !== void 0 && !allowedValues.includes(value)) {
|
|
667
|
+
const names = allowedValues.map((each) => `"${each}"`).join(" or ");
|
|
668
|
+
return `${where} has ${key} ${shown$1(value)}; use ${names}`;
|
|
669
|
+
}
|
|
670
|
+
if (onlyFor !== void 0 && !onlyFor.types.includes(spec.type)) return `${where} is "${spec.type}", so it can't have ${readsAs(key)}: ${onlyFor.because}`;
|
|
671
|
+
}
|
|
672
|
+
/** Why a spec can't be as it is, or undefined if it can. `where` names it (`User.id`). */
|
|
673
|
+
function specProblem(where, spec) {
|
|
674
|
+
for (const [key] of entries) {
|
|
675
|
+
if (givenValue(spec, key) === void 0) continue;
|
|
676
|
+
const problem = conflictProblem(where, spec, key) ?? valueProblem(where, spec, key);
|
|
677
|
+
if (problem !== void 0) return problem;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* `base` with `override` applied. A key `override` gives replaces one it conflicts with, and a new
|
|
682
|
+
* type drops every key written for the old one (so the column's own default applies on insert,
|
|
683
|
+
* unless the override gives one, #81).
|
|
684
|
+
*/
|
|
685
|
+
function applyOverride(base, override) {
|
|
686
|
+
const given = Object.fromEntries(Object.entries(override).filter(([, value]) => value !== void 0));
|
|
687
|
+
const retyped = given.type !== void 0 && given.type !== base.type;
|
|
688
|
+
const dropped = new Set(entries.filter(([key, rule]) => {
|
|
689
|
+
return conflicts.get(key).some((other) => givenValue(given, other) !== void 0) || retyped && rule.onRetype === "drop";
|
|
690
|
+
}).map(([key]) => key));
|
|
691
|
+
const kept = Object.entries(base).filter(([key]) => !dropped.has(key));
|
|
692
|
+
return {
|
|
693
|
+
...Object.fromEntries(kept),
|
|
694
|
+
...given
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
/** The keys of `spec` that go into its attribute's definition as given: `default`, `generateId`, `storage`. */
|
|
698
|
+
function copiedKeys(spec) {
|
|
699
|
+
const copied = entries.filter(([key, rule]) => rule.copiedToDefinition !== false && givenValue(spec, key) !== void 0).map(([key]) => [key, spec[key]]);
|
|
700
|
+
return Object.fromEntries(copied);
|
|
701
|
+
}
|
|
702
|
+
//#endregion
|
|
703
|
+
//#region src/metadata.ts
|
|
704
|
+
/** Resolves an attribute's spec into its type, column and default. */
|
|
705
|
+
function define(name, spec) {
|
|
706
|
+
return typeof spec === "string" ? {
|
|
707
|
+
type: spec,
|
|
708
|
+
column: underscore(name)
|
|
709
|
+
} : {
|
|
710
|
+
type: spec.type,
|
|
711
|
+
column: spec.column ?? underscore(name),
|
|
712
|
+
...copiedKeys(spec)
|
|
713
|
+
};
|
|
714
|
+
}
|
|
715
|
+
/** Looks up a declared attribute; throws `UnknownAttribute` for any other name. */
|
|
716
|
+
function attributeOf(model, name) {
|
|
717
|
+
const attribute = model.attributeDefinitions.get(name);
|
|
718
|
+
if (attribute === void 0) throw new UnknownAttribute(`${model.name} has no attribute "${name}"`);
|
|
719
|
+
return attribute;
|
|
720
|
+
}
|
|
721
|
+
/** The attribute names mapped to `column` (usually one; none if the column isn't declared). */
|
|
722
|
+
function attributesForColumn(model, column) {
|
|
723
|
+
return [...model.attributeDefinitions].filter(([, definition]) => definition.column === column).map(([name]) => name);
|
|
724
|
+
}
|
|
725
|
+
/** `undefined` would silently store NULL, so writing it throws `TypeError` (use `null`). */
|
|
726
|
+
function requireDefined(model, name, value) {
|
|
727
|
+
if (value === void 0) throw new TypeError(`${model.name}: got undefined for "${name}"; use null to store NULL`);
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* The initial values of every attribute not in `given` that has one, made now: each one's
|
|
731
|
+
* `default`, or for a generated id, the Model's `generateId(name)`.
|
|
732
|
+
*/
|
|
733
|
+
function initialValues(model, given = {}) {
|
|
734
|
+
return [...model.attributeDefinitions].filter(([name, definition]) => !(name in given) && hasInitialValue(definition)).map(([name, definition]) => [name, definition.generateId ? model.generateId(name) : definition.default()]);
|
|
735
|
+
}
|
|
736
|
+
/** Whether an attribute gets a value when none is given: from its `default`, or `generateId`. */
|
|
737
|
+
function hasInitialValue(definition) {
|
|
738
|
+
return definition.generateId === true || definition.default !== void 0;
|
|
739
|
+
}
|
|
740
|
+
//#endregion
|
|
741
|
+
//#region src/attribute.ts
|
|
742
|
+
/** What `condition()` and `conditionCell()` give for a value that can't match anything. */
|
|
743
|
+
const noMatch = uncastable;
|
|
744
|
+
/**
|
|
745
|
+
* One attribute's value path, resolved once per Model class by `attributeFor` (#163). Which
|
|
746
|
+
* Model and attribute a refusal names, whether the attribute is filtered, and how its type is
|
|
747
|
+
* stored are known here, so a caller only says what the value is for.
|
|
748
|
+
*/
|
|
749
|
+
var Attribute = class {
|
|
750
|
+
#model;
|
|
751
|
+
name;
|
|
752
|
+
column;
|
|
753
|
+
#definition;
|
|
754
|
+
/** @internal Use `attributeFor`. */
|
|
755
|
+
constructor(model, name) {
|
|
756
|
+
this.#model = model;
|
|
757
|
+
this.name = name;
|
|
758
|
+
this.#definition = attributeOf(model, name);
|
|
759
|
+
this.column = this.#definition.column;
|
|
760
|
+
}
|
|
761
|
+
/** Whether it's a `string` attribute, which D1 compares as text, not by number. */
|
|
762
|
+
get isText() {
|
|
763
|
+
return this.#definition.type === "string";
|
|
764
|
+
}
|
|
765
|
+
/** Whether it's a `json` attribute, whose stored text is JSON itself. */
|
|
766
|
+
get isJson() {
|
|
767
|
+
return this.#definition.type === "json";
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* An assigned value (a setter, `build`, `update`, `insert`, `permit`) as the attribute's type:
|
|
771
|
+
* only what's unambiguous for it (#81). `undefined` throws, as it would store NULL silently;
|
|
772
|
+
* what can't be cast throws `TypeError` naming the Model and attribute, showing the value
|
|
773
|
+
* unless the attribute is filtered (#83).
|
|
774
|
+
*/
|
|
775
|
+
cast(value) {
|
|
776
|
+
requireDefined(this.#model, this.name, value);
|
|
777
|
+
return this.#orRefuse(castValue(this.#definition, value), value);
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* A key copied from another record or inherited from a condition: cast as a condition's, but
|
|
781
|
+
* one that can't be cast throws, naming the association it came through.
|
|
782
|
+
*/
|
|
783
|
+
key(value, association) {
|
|
784
|
+
requireDefined(this.#model, this.name, value);
|
|
785
|
+
return this.#orRefuse(castCondition(this.#definition, value), value, association);
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* A condition's value (`where`, `find`, a preload) as the attribute's type, or `noMatch`: a
|
|
789
|
+
* number also matches a string attribute as its digits, and a value that can't be cast
|
|
790
|
+
* matches nothing, so a value from a URL is never an error.
|
|
791
|
+
*/
|
|
792
|
+
condition(value) {
|
|
793
|
+
return castCondition(this.#definition, value);
|
|
794
|
+
}
|
|
795
|
+
/** A condition's value in the form D1 stores, or `noMatch`. */
|
|
796
|
+
conditionCell(value) {
|
|
797
|
+
const cast = this.condition(value);
|
|
798
|
+
return cast === noMatch ? noMatch : this.write(cast);
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* An already cast value in the form D1 stores. A `json` value changed in place into one JSON
|
|
802
|
+
* can't write throws `TypeError` naming the attribute, as assigning it would (#146).
|
|
803
|
+
*/
|
|
804
|
+
write(value) {
|
|
805
|
+
let stored;
|
|
806
|
+
try {
|
|
807
|
+
stored = writeValue(this.#definition, value);
|
|
808
|
+
} catch (error) {
|
|
809
|
+
if (this.#definition.type !== "json") throw error;
|
|
810
|
+
throw this.#refusal(value);
|
|
811
|
+
}
|
|
812
|
+
if (stored === void 0) throw this.#refusal(value);
|
|
813
|
+
return stored;
|
|
814
|
+
}
|
|
815
|
+
/** An assigned value cast, then in the form D1 stores. */
|
|
816
|
+
store(value) {
|
|
817
|
+
return this.write(this.cast(value));
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* A cell D1 returned as the attribute's value. One that isn't (text in a Unix time column, or
|
|
821
|
+
* past the range of a `Date`; a json cell that isn't JSON) throws `TypeError` naming the
|
|
822
|
+
* attribute, with the cell hidden if it's filtered, not the parser's own error (#73, #146).
|
|
823
|
+
*/
|
|
824
|
+
read(cell) {
|
|
825
|
+
const value = readValue(this.#definition, cell);
|
|
826
|
+
if (value === uncastable) throw this.#refusal(cell);
|
|
827
|
+
return value;
|
|
828
|
+
}
|
|
829
|
+
/** A copy of a value: written as D1 stores it, then read back. */
|
|
830
|
+
copy(value) {
|
|
831
|
+
return this.read(this.write(value));
|
|
832
|
+
}
|
|
833
|
+
/** Whether two values are the same as stored (dates by time, json by content). */
|
|
834
|
+
same(a, b) {
|
|
835
|
+
return writeValue(this.#definition, a) === writeValue(this.#definition, b);
|
|
836
|
+
}
|
|
837
|
+
/** An assigned value, cast and written, bound hidden from `onQuery` if filtered (#83). */
|
|
838
|
+
bind(params, value) {
|
|
839
|
+
this.bindCells(params, this.store(value));
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Binds cells (as D1 holds them) as the attribute's, each hidden from `onQuery` listeners when
|
|
843
|
+
* the attribute is filtered (#83); D1 still gets the real values. Filtering is asked at the
|
|
844
|
+
* time, since `filterAttributes` is a static a Model may set after this was resolved.
|
|
845
|
+
*/
|
|
846
|
+
bindCells(params, ...cells) {
|
|
847
|
+
const hidden = this.#hidden();
|
|
848
|
+
for (const cell of cells) params.push(hidden ? new Filtered(cell) : cell);
|
|
849
|
+
}
|
|
850
|
+
#orRefuse(cast, value, association) {
|
|
851
|
+
if (cast === uncastable) throw this.#refusal(value, association);
|
|
852
|
+
return cast;
|
|
853
|
+
}
|
|
854
|
+
/** Whether the attribute's values are hidden from listeners and errors (#83). */
|
|
855
|
+
#hidden() {
|
|
856
|
+
return isFiltered(this.#model, this.name);
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* "Sample: "no" isn't a boolean for "enabled"", the value hidden for a filtered attribute. Also
|
|
860
|
+
* what a stored value that can't be read says: a Unix time that isn't one (#73), or a json
|
|
861
|
+
* cell that isn't JSON (#146).
|
|
862
|
+
*/
|
|
863
|
+
#refusal(value, association) {
|
|
864
|
+
const { type } = this.#definition;
|
|
865
|
+
const noun = nouns[type] ?? type;
|
|
866
|
+
const article = /^[aeiou]/.test(noun) ? "an" : "a";
|
|
867
|
+
const text = this.#hidden() ? FILTERED : shown(value);
|
|
868
|
+
const from = association === void 0 ? "" : `, the key of ${association}`;
|
|
869
|
+
return /* @__PURE__ */ new TypeError(`${this.#model.name}: ${text} isn't ${article} ${noun} for "${this.name}"${from}`);
|
|
870
|
+
}
|
|
871
|
+
};
|
|
872
|
+
const resolved = /* @__PURE__ */ new WeakMap();
|
|
873
|
+
/**
|
|
874
|
+
* The resolved attribute of a Model, remembered per class (derived from the class, ADR-0003):
|
|
875
|
+
* `UnknownAttribute` for a name it doesn't have.
|
|
876
|
+
*/
|
|
877
|
+
function attributeFor(model, name) {
|
|
878
|
+
let attributes = resolved.get(model);
|
|
879
|
+
if (attributes === void 0) {
|
|
880
|
+
attributes = /* @__PURE__ */ new Map();
|
|
881
|
+
resolved.set(model, attributes);
|
|
882
|
+
}
|
|
883
|
+
let attribute = attributes.get(name);
|
|
884
|
+
if (attribute === void 0) {
|
|
885
|
+
attribute = new Attribute(model, name);
|
|
886
|
+
attributes.set(name, attribute);
|
|
887
|
+
}
|
|
888
|
+
return attribute;
|
|
889
|
+
}
|
|
890
|
+
/**
|
|
891
|
+
* Rows of `names`' values, assigned, as one JSON value the dialect reads them from; listeners see
|
|
892
|
+
* a filtered attribute's column as "[FILTERED]" in every row.
|
|
893
|
+
*/
|
|
894
|
+
function storedRows(model, names, rows) {
|
|
895
|
+
const attributes = names.map((name) => attributeFor(model, name));
|
|
896
|
+
const stored = rows.map((row) => row.map((value, index) => attributes[index].store(value)));
|
|
897
|
+
const json = JSON.stringify(stored);
|
|
898
|
+
const filtered = names.map((attribute) => isFiltered(model, attribute));
|
|
899
|
+
if (!filtered.includes(true)) return json;
|
|
900
|
+
const shown = stored.map((row) => row.map((value, index) => filtered[index] ? FILTERED : value));
|
|
901
|
+
return new Filtered(json, JSON.stringify(shown));
|
|
902
|
+
}
|
|
903
|
+
/**
|
|
904
|
+
* The values a record built from a Relation inherits from its conditions, cast as keys are: a
|
|
905
|
+
* hasMany's foreign key names its association (`link`) when it can't be cast.
|
|
906
|
+
*/
|
|
907
|
+
function castInherited(model, inherited, link) {
|
|
908
|
+
return Object.fromEntries(Object.entries(inherited).map(([attribute, value]) => {
|
|
909
|
+
const association = attribute === link?.attribute ? link.association : void 0;
|
|
910
|
+
return [attribute, attributeFor(model, attribute).key(value, association)];
|
|
911
|
+
}));
|
|
912
|
+
}
|
|
913
|
+
/** How much of a value an error shows: it came from outside, and errors are often logged. */
|
|
914
|
+
const SHOWN_LENGTH = 60;
|
|
915
|
+
/** What an attribute type is called in a refusal, where its name isn't it. */
|
|
916
|
+
const nouns = { json: "JSON value" };
|
|
917
|
+
/** A value as an error shows it: JSON where it has one, numbers as written, and at most 60 characters. */
|
|
918
|
+
function shown(value) {
|
|
919
|
+
const text = textOf(value);
|
|
920
|
+
return text.length > SHOWN_LENGTH ? `${text.slice(0, SHOWN_LENGTH)}…` : text;
|
|
921
|
+
}
|
|
922
|
+
function textOf(value) {
|
|
923
|
+
if (typeof value === "number" || isInvalidDate(value)) return String(value);
|
|
924
|
+
try {
|
|
925
|
+
return JSON.stringify(value) ?? String(value);
|
|
926
|
+
} catch {
|
|
927
|
+
return plainText(value);
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
/** `String(value)`, or its tag (`[object Array]`) when it has no string form: building the refusal mustn't throw. */
|
|
931
|
+
function plainText(value) {
|
|
932
|
+
try {
|
|
933
|
+
return String(value);
|
|
934
|
+
} catch {
|
|
935
|
+
return Object.prototype.toString.call(value);
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
//#endregion
|
|
939
|
+
//#region src/declarations.ts
|
|
940
|
+
/**
|
|
941
|
+
* Per-Model declarations (validations, callbacks, …), keyed by Model class. A subclass starts
|
|
942
|
+
* from a copy of its parent's list, so declaring on it never changes the parent.
|
|
943
|
+
*
|
|
944
|
+
* Module-level, but not request state (ADR-0003): declarations are made once, when a Model
|
|
945
|
+
* class is defined, and only read afterwards.
|
|
946
|
+
*/
|
|
947
|
+
const registry = /* @__PURE__ */ new WeakMap();
|
|
948
|
+
/** The declarations each class made itself, without its parent's, for reading class by class. */
|
|
949
|
+
const ownRegistry = /* @__PURE__ */ new WeakMap();
|
|
950
|
+
/** Models that have been used; their declarations can no longer change. */
|
|
951
|
+
const sealed = /* @__PURE__ */ new WeakSet();
|
|
952
|
+
/**
|
|
953
|
+
* Called on a Model's first use. From then on, declaring on it throws: declarations belong in
|
|
954
|
+
* the class's `static {}` block, never in request code, where they'd leak into every request.
|
|
955
|
+
*/
|
|
956
|
+
function seal(model) {
|
|
957
|
+
sealed.add(model);
|
|
958
|
+
}
|
|
959
|
+
/** Whether a Model has been used, so its declarations, and its ancestors', can no longer change. */
|
|
960
|
+
function isSealed(model) {
|
|
961
|
+
return sealed.has(model);
|
|
962
|
+
}
|
|
963
|
+
/** The declarations of `kind` for `model`: its own, or else its nearest ancestor's. */
|
|
964
|
+
function declared(model, kind) {
|
|
965
|
+
for (const current of ancestors(model)) {
|
|
966
|
+
const list = registry.get(current)?.get(kind);
|
|
967
|
+
if (list !== void 0) return list;
|
|
968
|
+
}
|
|
969
|
+
return [];
|
|
970
|
+
}
|
|
971
|
+
/** The declarations of `kind` that `model` and each class it extends made themselves, nearest first. */
|
|
972
|
+
function declaredByClass(model, kind) {
|
|
973
|
+
return ancestors(model).flatMap((from) => {
|
|
974
|
+
const values = ownRegistry.get(from)?.get(kind);
|
|
975
|
+
return values === void 0 ? [] : [{
|
|
976
|
+
from,
|
|
977
|
+
values
|
|
978
|
+
}];
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
/** Adds a declaration of `kind` to `model`, copying its inherited list first. */
|
|
982
|
+
function declare(model, kind, entry) {
|
|
983
|
+
if (sealed.has(model)) {
|
|
984
|
+
const { name } = model;
|
|
985
|
+
throw new InvalidModel(`${name} has already been used; declare validations, callbacks and messages in its static {} block`);
|
|
986
|
+
}
|
|
987
|
+
listsOf(registry, model).set(kind, [...declared(model, kind), entry]);
|
|
988
|
+
const own = listsOf(ownRegistry, model);
|
|
989
|
+
own.set(kind, [...own.get(kind) ?? [], entry]);
|
|
990
|
+
}
|
|
991
|
+
/** `model`'s lists in a registry, by kind, made empty the first time. */
|
|
992
|
+
function listsOf(lists, model) {
|
|
993
|
+
const found = lists.get(model) ?? /* @__PURE__ */ new Map();
|
|
994
|
+
lists.set(model, found);
|
|
995
|
+
return found;
|
|
996
|
+
}
|
|
997
|
+
//#endregion
|
|
998
|
+
//#region src/error-messages.ts
|
|
999
|
+
/** @internal Rails' English messages, used where no class has its own (listed in the guide). */
|
|
1000
|
+
const builtInMessages = {
|
|
1001
|
+
blank: "can't be blank",
|
|
1002
|
+
invalid: "is invalid",
|
|
1003
|
+
inclusion: "is not included in the list",
|
|
1004
|
+
taken: "has already been taken",
|
|
1005
|
+
tooShort: {
|
|
1006
|
+
one: "is too short (minimum is 1 character)",
|
|
1007
|
+
other: "is too short (minimum is %{count} characters)"
|
|
1008
|
+
},
|
|
1009
|
+
tooLong: {
|
|
1010
|
+
one: "is too long (maximum is 1 character)",
|
|
1011
|
+
other: "is too long (maximum is %{count} characters)"
|
|
1012
|
+
},
|
|
1013
|
+
wrongLength: {
|
|
1014
|
+
one: "is the wrong length (should be 1 character)",
|
|
1015
|
+
other: "is the wrong length (should be %{count} characters)"
|
|
1016
|
+
},
|
|
1017
|
+
notANumber: "is not a number",
|
|
1018
|
+
notAnInteger: "must be an integer",
|
|
1019
|
+
greaterThan: "must be greater than %{count}",
|
|
1020
|
+
greaterThanOrEqualTo: "must be greater than or equal to %{count}",
|
|
1021
|
+
lessThan: "must be less than %{count}",
|
|
1022
|
+
lessThanOrEqualTo: "must be less than or equal to %{count}",
|
|
1023
|
+
restrictDependentDestroy: {
|
|
1024
|
+
hasOne: "Cannot delete record because a dependent %{record} exists",
|
|
1025
|
+
hasMany: "Cannot delete record because dependent %{record} exist"
|
|
1026
|
+
}
|
|
1027
|
+
};
|
|
1028
|
+
const plurals = new Intl.PluralRules("en");
|
|
1029
|
+
/** `object[key]` when it's the object's own, so `toString` is never a message. */
|
|
1030
|
+
function ownValue(object, key) {
|
|
1031
|
+
return object !== void 0 && Object.hasOwn(object, key) ? object[key] : void 0;
|
|
1032
|
+
}
|
|
1033
|
+
/** One class's `errorMessages` calls as one: a later call's message wins, type by type. */
|
|
1034
|
+
function mergedCalls(calls) {
|
|
1035
|
+
const attributes = {};
|
|
1036
|
+
for (const call of calls) for (const [name, types] of Object.entries(call.attributes ?? {})) attributes[name] = {
|
|
1037
|
+
...attributes[name],
|
|
1038
|
+
...types
|
|
1039
|
+
};
|
|
1040
|
+
return Object.assign({}, ...calls, { attributes });
|
|
1041
|
+
}
|
|
1042
|
+
const catalogs = /* @__PURE__ */ new WeakMap();
|
|
1043
|
+
/** A Model's catalog, built once it's sealed; before that, built afresh, as declarations can still come. */
|
|
1044
|
+
function catalogOf(model) {
|
|
1045
|
+
const kept = catalogs.get(model);
|
|
1046
|
+
if (kept !== void 0) return kept;
|
|
1047
|
+
const names = /* @__PURE__ */ new Map();
|
|
1048
|
+
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);
|
|
1049
|
+
const catalog = {
|
|
1050
|
+
messages: [...declaredByClass(model, "errorMessages").map(({ values }) => mergedCalls(values)), builtInMessages],
|
|
1051
|
+
names
|
|
1052
|
+
};
|
|
1053
|
+
if (isSealed(model)) catalogs.set(model, catalog);
|
|
1054
|
+
return catalog;
|
|
1055
|
+
}
|
|
1056
|
+
/** The message for a type: for the attribute, then the class's own, nearest class first (Rails' order). */
|
|
1057
|
+
function templateFor(model, attribute, type) {
|
|
1058
|
+
if (type === "attributes") return void 0;
|
|
1059
|
+
for (const messages of catalogOf(model).messages) {
|
|
1060
|
+
const found = ownValue(ownValue(messages.attributes, attribute), type) ?? ownValue(messages, type);
|
|
1061
|
+
if (found !== void 0) return found;
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
/** The text of a message: the form the entry names, or else the plural form for `count`. */
|
|
1065
|
+
function messageText(template, entry) {
|
|
1066
|
+
if (template === void 0 || typeof template === "string") return template;
|
|
1067
|
+
const { count } = entry.values;
|
|
1068
|
+
return ownValue(template, entry.form ?? (typeof count === "number" ? plurals.select(count) : "other")) ?? template.other;
|
|
1069
|
+
}
|
|
1070
|
+
/** "createdAt" → "Created at" */
|
|
1071
|
+
function inWords(name) {
|
|
1072
|
+
const words = underscore(name).replaceAll("_", " ");
|
|
1073
|
+
return words.charAt(0).toUpperCase() + words.slice(1);
|
|
1074
|
+
}
|
|
1075
|
+
/** An attribute's name as messages show it: a class's `humanAttributeNames`, or "Created at". */
|
|
1076
|
+
function humanAttributeName(model, attribute) {
|
|
1077
|
+
return catalogOf(model).names.get(attribute) ?? inWords(attribute);
|
|
1078
|
+
}
|
|
1079
|
+
/** An attribute's value as `%{value}` shows it. */
|
|
1080
|
+
function shownValue(source, attribute) {
|
|
1081
|
+
if (attribute === "base") return "";
|
|
1082
|
+
const value = source.read(attribute);
|
|
1083
|
+
if (value === null || value === void 0) return "";
|
|
1084
|
+
if (isFiltered(source.model, attribute)) return FILTERED;
|
|
1085
|
+
if (value instanceof Date) return value.toISOString();
|
|
1086
|
+
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
1087
|
+
}
|
|
1088
|
+
/** An entry's message: given, or looked up now, with its `%{name}` placeholders filled in. */
|
|
1089
|
+
function messageOf(source, entry) {
|
|
1090
|
+
if (entry.message !== void 0) return entry.message;
|
|
1091
|
+
const { model } = source;
|
|
1092
|
+
const text = messageText(templateFor(model, entry.attribute, entry.type), entry);
|
|
1093
|
+
if (text === void 0) throw missingMessage(model, entry);
|
|
1094
|
+
return text.replace(/%\{(\w+)\}/g, (placeholder, name) => {
|
|
1095
|
+
if (name === "attribute") return humanAttributeName(model, entry.attribute);
|
|
1096
|
+
if (name === "model") return inWords(model.name);
|
|
1097
|
+
if (name === "value") return shownValue(source, entry.attribute);
|
|
1098
|
+
return String(ownValue(entry.values, name) ?? placeholder);
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
/** The error for a type no class has a message for. */
|
|
1102
|
+
function missingMessage(model, entry) {
|
|
1103
|
+
const where = `${model.name}'s errorMessages, or a class it extends`;
|
|
1104
|
+
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}`);
|
|
1105
|
+
}
|
|
1106
|
+
/** The attributes each class names in its `errorMessages` or `humanAttributeNames`, nearest class first. */
|
|
1107
|
+
function attributesNamedInMessages(model) {
|
|
1108
|
+
return [...declaredByClass(model, "errorMessages").map(({ from, values }) => ({
|
|
1109
|
+
from,
|
|
1110
|
+
declaration: "errorMessages",
|
|
1111
|
+
names: values.flatMap((value) => Object.keys(value.attributes ?? {}))
|
|
1112
|
+
})), ...declaredByClass(model, "humanAttributeNames").map(({ from, values }) => ({
|
|
1113
|
+
from,
|
|
1114
|
+
declaration: "humanAttributeNames",
|
|
1115
|
+
names: values.flatMap((value) => Object.keys(value))
|
|
1116
|
+
}))];
|
|
1117
|
+
}
|
|
1118
|
+
//#endregion
|
|
1119
|
+
//#region src/inspect-support.ts
|
|
1120
|
+
/** Node and workerd call a value's inspector under this registered symbol. */
|
|
1121
|
+
const inspectCustom = Symbol.for("nodejs.util.inspect.custom");
|
|
1122
|
+
/** Text in the color of a special value, or plain when colors are off. */
|
|
1123
|
+
function styled(options, text) {
|
|
1124
|
+
return options.stylize ? options.stylize(text, "special") : text;
|
|
1125
|
+
}
|
|
1126
|
+
/** A filtered value's stand-in: prints unquoted, so it isn't taken for a string, as a special value. */
|
|
1127
|
+
var FilteredMark = class {
|
|
1128
|
+
#changed;
|
|
1129
|
+
constructor(changed) {
|
|
1130
|
+
this.#changed = changed;
|
|
1131
|
+
}
|
|
1132
|
+
[inspectCustom](_depth, options) {
|
|
1133
|
+
return styled(options, FILTERED) + (this.#changed ? " (changed)" : "");
|
|
1134
|
+
}
|
|
1135
|
+
};
|
|
1136
|
+
/**
|
|
1137
|
+
* `label` and the runtime's own `inspect` of `body`, which is built only when there is depth left;
|
|
1138
|
+
* otherwise `[name]`, as Node prints any class instance nested too deep.
|
|
1139
|
+
*/
|
|
1140
|
+
function printed(label, name, body, { depth, options, inspect }) {
|
|
1141
|
+
if (depth < 0) return styled(options, `[${name}]`);
|
|
1142
|
+
return `${label} ${inspect(body(), {
|
|
1143
|
+
...options,
|
|
1144
|
+
depth
|
|
1145
|
+
})}`;
|
|
1146
|
+
}
|
|
1147
|
+
//#endregion
|
|
1148
|
+
//#region src/errors-collection.ts
|
|
1149
|
+
/** @internal The library's key for emptying an errors collection. */
|
|
1150
|
+
const clearErrors = Symbol("clearErrors");
|
|
1151
|
+
/** @internal The library's key for adding a failure it found, with an optional message to use as it is. */
|
|
1152
|
+
const addFailure = Symbol("addFailure");
|
|
1153
|
+
/** A record's validation errors: `record.errors`. Cleared at the start of each validation run. */
|
|
1154
|
+
var Errors = class {
|
|
1155
|
+
#entries = [];
|
|
1156
|
+
#source;
|
|
1157
|
+
/** @internal Made by the library for each record. */
|
|
1158
|
+
constructor(source) {
|
|
1159
|
+
this.#source = source;
|
|
1160
|
+
}
|
|
1161
|
+
add(attribute, message, options = {}) {
|
|
1162
|
+
if (typeof message === "string") {
|
|
1163
|
+
this.#entries.push({
|
|
1164
|
+
attribute,
|
|
1165
|
+
type: options.type ?? "invalid",
|
|
1166
|
+
values: {},
|
|
1167
|
+
message
|
|
1168
|
+
});
|
|
1169
|
+
return;
|
|
1170
|
+
}
|
|
1171
|
+
const { type, ...values } = message;
|
|
1172
|
+
if (typeof type !== "string") throw new TypeError("errors.add needs a message or a type");
|
|
1173
|
+
const entry = {
|
|
1174
|
+
attribute,
|
|
1175
|
+
type,
|
|
1176
|
+
values
|
|
1177
|
+
};
|
|
1178
|
+
messageOf(this.#source, entry);
|
|
1179
|
+
this.#entries.push(entry);
|
|
1180
|
+
}
|
|
1181
|
+
/** The messages for one attribute (always an array). */
|
|
1182
|
+
get(attribute) {
|
|
1183
|
+
return this.#entries.filter((entry) => entry.attribute === attribute).map((entry) => messageOf(this.#source, entry));
|
|
1184
|
+
}
|
|
1185
|
+
/** Every message with its attribute's human name first: "Email can't be blank". */
|
|
1186
|
+
fullMessages() {
|
|
1187
|
+
return this.#entries.map((entry) => {
|
|
1188
|
+
const message = messageOf(this.#source, entry);
|
|
1189
|
+
if (entry.attribute === "base") return message;
|
|
1190
|
+
return `${humanAttributeName(this.#source.model, entry.attribute)} ${message}`;
|
|
1191
|
+
});
|
|
1192
|
+
}
|
|
1193
|
+
/** Every error as `{ attribute, type, message }`, with its `values` when it has some (copies). */
|
|
1194
|
+
toArray() {
|
|
1195
|
+
return this.#entries.map((entry) => {
|
|
1196
|
+
const { attribute, type, values } = entry;
|
|
1197
|
+
const error = {
|
|
1198
|
+
attribute,
|
|
1199
|
+
type,
|
|
1200
|
+
message: messageOf(this.#source, entry)
|
|
1201
|
+
};
|
|
1202
|
+
return Object.keys(values).length === 0 ? error : {
|
|
1203
|
+
...error,
|
|
1204
|
+
values: { ...values }
|
|
1205
|
+
};
|
|
1206
|
+
});
|
|
1207
|
+
}
|
|
1208
|
+
isEmpty() {
|
|
1209
|
+
return this.#entries.length === 0;
|
|
1210
|
+
}
|
|
1211
|
+
get size() {
|
|
1212
|
+
return this.#entries.length;
|
|
1213
|
+
}
|
|
1214
|
+
/** `Errors [ { attribute, type, message }, … ]`, so a console shows what `#entries` holds (#104). */
|
|
1215
|
+
[inspectCustom](depth, options, inspect) {
|
|
1216
|
+
return printed("Errors", "Errors", () => this.toArray(), {
|
|
1217
|
+
depth,
|
|
1218
|
+
options,
|
|
1219
|
+
inspect
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
/** @internal Adds an error the library found, such as a validator's, returning its message. */
|
|
1223
|
+
[addFailure](attribute, { values = {}, ...failure }) {
|
|
1224
|
+
const entry = {
|
|
1225
|
+
attribute,
|
|
1226
|
+
values,
|
|
1227
|
+
...failure
|
|
1228
|
+
};
|
|
1229
|
+
this.#entries.push(entry);
|
|
1230
|
+
return messageOf(this.#source, entry);
|
|
1231
|
+
}
|
|
1232
|
+
/** @internal Called at the start of each validation run. */
|
|
1233
|
+
[clearErrors]() {
|
|
1234
|
+
this.#entries = [];
|
|
1235
|
+
}
|
|
1236
|
+
};
|
|
1237
|
+
//#endregion
|
|
1238
|
+
//#region src/loaded-associations.ts
|
|
1239
|
+
/**
|
|
1240
|
+
* The associations one record has loaded (preloaded, read, or set by a write): a record, an
|
|
1241
|
+
* array of records, or null. Each stays loaded while the owner's attribute still holds the key
|
|
1242
|
+
* it was loaded for, and a load overtaken by a change to its association isn't kept.
|
|
1243
|
+
*/
|
|
1244
|
+
var LoadedAssociations = class {
|
|
1245
|
+
/** The owner's attribute value now, which an entry's key is checked against. */
|
|
1246
|
+
#keyOf;
|
|
1247
|
+
#entries = /* @__PURE__ */ new Map();
|
|
1248
|
+
/** Counted when an association changes, by name and record-wide, so a stale load isn't kept. */
|
|
1249
|
+
#loadsDiscarded = /* @__PURE__ */ new Map();
|
|
1250
|
+
#allLoadsDiscarded = 0;
|
|
1251
|
+
constructor(keyOf) {
|
|
1252
|
+
this.#keyOf = keyOf;
|
|
1253
|
+
}
|
|
1254
|
+
/** The loaded association, if it was loaded for the key the owner holds now. */
|
|
1255
|
+
get(name) {
|
|
1256
|
+
const entry = this.#entries.get(name);
|
|
1257
|
+
if (entry === void 0 || !Object.is(this.#key(entry.attribute), entry.key)) return void 0;
|
|
1258
|
+
return entry;
|
|
1259
|
+
}
|
|
1260
|
+
/**
|
|
1261
|
+
* Sets the association to what a write or preload made it, for the key `attribute` holds now;
|
|
1262
|
+
* loads of it already sent won't be kept.
|
|
1263
|
+
*/
|
|
1264
|
+
set(name, attribute, value) {
|
|
1265
|
+
this.#entries.set(name, {
|
|
1266
|
+
attribute,
|
|
1267
|
+
key: this.#key(attribute),
|
|
1268
|
+
value
|
|
1269
|
+
});
|
|
1270
|
+
this.#discardPendingLoads(name);
|
|
1271
|
+
}
|
|
1272
|
+
/**
|
|
1273
|
+
* Starts a load of the association, before its query is sent, for the key its query was built
|
|
1274
|
+
* for: the function it returns keeps the loaded value only if nothing changed the association
|
|
1275
|
+
* meanwhile (#181).
|
|
1276
|
+
*/
|
|
1277
|
+
startLoad(name, attribute, key) {
|
|
1278
|
+
const generation = this.#generation(name);
|
|
1279
|
+
return (value) => {
|
|
1280
|
+
if (this.#generation(name) === generation) this.#entries.set(name, {
|
|
1281
|
+
attribute,
|
|
1282
|
+
key,
|
|
1283
|
+
value
|
|
1284
|
+
});
|
|
1285
|
+
};
|
|
1286
|
+
}
|
|
1287
|
+
/** Forgets the association; loads of it already sent won't be kept. */
|
|
1288
|
+
clear(name) {
|
|
1289
|
+
this.#entries.delete(name);
|
|
1290
|
+
this.#discardPendingLoads(name);
|
|
1291
|
+
}
|
|
1292
|
+
/** Forgets every association (`reload()`); loads already sent won't be kept. */
|
|
1293
|
+
clearAll() {
|
|
1294
|
+
this.#entries.clear();
|
|
1295
|
+
this.#allLoadsDiscarded += 1;
|
|
1296
|
+
}
|
|
1297
|
+
#key(attribute) {
|
|
1298
|
+
return this.#keyOf(attribute) ?? null;
|
|
1299
|
+
}
|
|
1300
|
+
#discardPendingLoads(name) {
|
|
1301
|
+
this.#loadsDiscarded.set(name, (this.#loadsDiscarded.get(name) ?? 0) + 1);
|
|
1302
|
+
}
|
|
1303
|
+
/**
|
|
1304
|
+
* Changes with each change to the association, so a load can tell whether it's still current.
|
|
1305
|
+
* The two counts are summed, so `clearAll()` makes every name stale without touching the map.
|
|
1306
|
+
*/
|
|
1307
|
+
#generation(name) {
|
|
1308
|
+
return this.#allLoadsDiscarded + (this.#loadsDiscarded.get(name) ?? 0);
|
|
1309
|
+
}
|
|
1310
|
+
};
|
|
1311
|
+
//#endregion
|
|
1312
|
+
//#region src/pending-autosaves.ts
|
|
1313
|
+
/**
|
|
1314
|
+
* The new records saving one record also saves: those built through its hasMany and hasOne
|
|
1315
|
+
* associations, after it, and those its belongsTo associations point at, before it.
|
|
1316
|
+
*/
|
|
1317
|
+
var PendingAutosaves = class {
|
|
1318
|
+
#built = /* @__PURE__ */ new Map();
|
|
1319
|
+
#belongsTo = /* @__PURE__ */ new Map();
|
|
1320
|
+
/** A record built through one of this record's hasMany or hasOne associations. */
|
|
1321
|
+
addBuilt(name, record) {
|
|
1322
|
+
this.#built.set(name, [...this.#built.get(name) ?? [], record]);
|
|
1323
|
+
}
|
|
1324
|
+
/** The records built through the association, in the order they were built. */
|
|
1325
|
+
built(name) {
|
|
1326
|
+
return this.#built.get(name) ?? [];
|
|
1327
|
+
}
|
|
1328
|
+
/** Every association's built records, by association name. */
|
|
1329
|
+
allBuilt() {
|
|
1330
|
+
return [...this.#built];
|
|
1331
|
+
}
|
|
1332
|
+
/** A new record a belongsTo points at, saved first when this record is; undefined clears it. */
|
|
1333
|
+
setBelongsTo(name, record) {
|
|
1334
|
+
if (record === void 0) this.#belongsTo.delete(name);
|
|
1335
|
+
else this.#belongsTo.set(name, record);
|
|
1336
|
+
}
|
|
1337
|
+
/** The new records this record's belongsTo associations point at, by association name. */
|
|
1338
|
+
allBelongsTo() {
|
|
1339
|
+
return [...this.#belongsTo];
|
|
1340
|
+
}
|
|
1341
|
+
/** Forgets what was built through the association or set on it (`reloadAssociation`). */
|
|
1342
|
+
clear(name) {
|
|
1343
|
+
this.#built.delete(name);
|
|
1344
|
+
this.#belongsTo.delete(name);
|
|
1345
|
+
}
|
|
1346
|
+
/** Forgets every association's (`reload()`). */
|
|
1347
|
+
clearAll() {
|
|
1348
|
+
this.#built.clear();
|
|
1349
|
+
this.#belongsTo.clear();
|
|
1350
|
+
}
|
|
1351
|
+
};
|
|
1352
|
+
//#endregion
|
|
1353
|
+
//#region src/record-state.ts
|
|
1354
|
+
/** @internal The hidden slot where a Record keeps its `RecordState`. */
|
|
1355
|
+
const state = Symbol("state");
|
|
1356
|
+
/** Each record's link to its database (its `RecordState`), for pinning it to one (#93). */
|
|
1357
|
+
function linksOf(records) {
|
|
1358
|
+
return [...records].map((record) => record[state]);
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1361
|
+
* Everything one Record knows about itself: its attribute values, lifecycle, the attributes
|
|
1362
|
+
* assigned since it was built, its Snapshot (each loaded attribute's stored form as last loaded
|
|
1363
|
+
* or saved), the changes its last save wrote, and the Database it belongs to.
|
|
1364
|
+
*
|
|
1365
|
+
* This is the only module that reads or writes those fields. Every rule about them (unloaded
|
|
1366
|
+
* attributes, undefined values, destroyed records, change detection) is enforced here.
|
|
1367
|
+
*/
|
|
1368
|
+
var RecordState = class {
|
|
1369
|
+
#model;
|
|
1370
|
+
#executor;
|
|
1371
|
+
#lifecycle = "new";
|
|
1372
|
+
#values = {};
|
|
1373
|
+
#assigned = /* @__PURE__ */ new Set();
|
|
1374
|
+
#snapshot = /* @__PURE__ */ new Map();
|
|
1375
|
+
/** The row the Snapshot was loaded from: its entries for the row's cells are made on first use (#91). */
|
|
1376
|
+
#snapshotRow;
|
|
1377
|
+
/** A new record's initial values in stored form, which `restore` returns attributes to. */
|
|
1378
|
+
#initialValues = /* @__PURE__ */ new Map();
|
|
1379
|
+
#savedChanges = {};
|
|
1380
|
+
#errors;
|
|
1381
|
+
#abortReason;
|
|
1382
|
+
/** The associations it has loaded, each kept while its key is current. */
|
|
1383
|
+
associations = new LoadedAssociations((attribute) => this.#values[attribute]);
|
|
1384
|
+
/** The new records saving it also saves, built through or pointed at by its associations. */
|
|
1385
|
+
autosaves = new PendingAutosaves();
|
|
1386
|
+
constructor(model) {
|
|
1387
|
+
this.#model = model;
|
|
1388
|
+
const read = (name) => Object.hasOwn(this.#values, name) ? this.#values[name] : null;
|
|
1389
|
+
this.#errors = new Errors({
|
|
1390
|
+
model,
|
|
1391
|
+
read
|
|
1392
|
+
});
|
|
1393
|
+
}
|
|
1394
|
+
/** The record's validation errors, filled by the last validation run. */
|
|
1395
|
+
get errors() {
|
|
1396
|
+
return this.#errors;
|
|
1397
|
+
}
|
|
1398
|
+
/** Why a callback last refused a save or destroy; cleared at the start of each run. */
|
|
1399
|
+
get abortReason() {
|
|
1400
|
+
return this.#abortReason;
|
|
1401
|
+
}
|
|
1402
|
+
set abortReason(reason) {
|
|
1403
|
+
this.#abortReason = reason;
|
|
1404
|
+
}
|
|
1405
|
+
/** Not yet saved: built, or created but not persisted. */
|
|
1406
|
+
get isNew() {
|
|
1407
|
+
return this.#lifecycle === "new";
|
|
1408
|
+
}
|
|
1409
|
+
/** Backed by a row: loaded, or saved successfully. */
|
|
1410
|
+
get isPersisted() {
|
|
1411
|
+
return this.#lifecycle === "persisted";
|
|
1412
|
+
}
|
|
1413
|
+
/** Deleted by this instance: a read-only snapshot of the row. */
|
|
1414
|
+
get isDestroyed() {
|
|
1415
|
+
return this.#lifecycle === "destroyed";
|
|
1416
|
+
}
|
|
1417
|
+
/** Records belong to the Database they were built or loaded through (ADR-0003). */
|
|
1418
|
+
belongTo(executor) {
|
|
1419
|
+
this.#executor = executor;
|
|
1420
|
+
}
|
|
1421
|
+
/** The record's Database; `NoDatabase` for a record constructed directly (`new User()`). */
|
|
1422
|
+
get executor() {
|
|
1423
|
+
if (this.#executor === void 0) {
|
|
1424
|
+
const { name } = this.#model;
|
|
1425
|
+
throw new NoDatabase(`${name} record has no Database; build or load records through db.model(${name})`);
|
|
1426
|
+
}
|
|
1427
|
+
return this.#executor;
|
|
1428
|
+
}
|
|
1429
|
+
/**
|
|
1430
|
+
* Refuses to use a record as a live one when it can't be: a destroyed record is a read-only
|
|
1431
|
+
* snapshot, and a persisted record without its primary key (from `select(...).distinct()`)
|
|
1432
|
+
* has no identity to write by.
|
|
1433
|
+
*/
|
|
1434
|
+
requireLive(action) {
|
|
1435
|
+
this.#requireNotDestroyed(action);
|
|
1436
|
+
this.requireKey(action);
|
|
1437
|
+
}
|
|
1438
|
+
/** A persisted record needs its primary key to be found by; one from `distinct()` has none. */
|
|
1439
|
+
requireKey(action) {
|
|
1440
|
+
const { name, primaryKey } = this.#model;
|
|
1441
|
+
if (this.#lifecycle === "persisted" && !this.#inSnapshot(primaryKey)) throw new MissingAttribute(`${name} record has no primary key loaded (it came from select(...).distinct()); it can't ${action}`);
|
|
1442
|
+
}
|
|
1443
|
+
/** An attribute's value; `MissingAttribute` if it wasn't loaded (left out of `select`). */
|
|
1444
|
+
read(name) {
|
|
1445
|
+
this.#requireAttribute(name);
|
|
1446
|
+
if (!Object.hasOwn(this.#values, name)) throw new MissingAttribute(`${this.#model.name} record has no "${name}" loaded; it was left out of select(...)`);
|
|
1447
|
+
return this.#values[name];
|
|
1448
|
+
}
|
|
1449
|
+
/**
|
|
1450
|
+
* Assigns one attribute. `undefined` throws `TypeError`, because it would silently store NULL
|
|
1451
|
+
* (use `null` for that); a destroyed record is read-only.
|
|
1452
|
+
*/
|
|
1453
|
+
write(name, value) {
|
|
1454
|
+
this.#requireNotDestroyed("be changed");
|
|
1455
|
+
this.#store(name, this.#attribute(name).cast(value));
|
|
1456
|
+
}
|
|
1457
|
+
/**
|
|
1458
|
+
* Writes a key copied from another record through `association`, cast as a condition's value
|
|
1459
|
+
* is (#94): an integer key into a text foreign key becomes its digits.
|
|
1460
|
+
*/
|
|
1461
|
+
writeKey(name, value, association) {
|
|
1462
|
+
this.#requireNotDestroyed("be changed");
|
|
1463
|
+
this.#store(name, this.#attribute(name).key(value, association));
|
|
1464
|
+
}
|
|
1465
|
+
/** Stores an attribute's already-cast value, as assigned. */
|
|
1466
|
+
#store(name, value) {
|
|
1467
|
+
this.#values[name] = value;
|
|
1468
|
+
this.#assigned.add(name);
|
|
1469
|
+
}
|
|
1470
|
+
/** Assigns several attributes; unknown names throw `UnknownAttribute`. */
|
|
1471
|
+
assign(attributes) {
|
|
1472
|
+
for (const [name, value] of Object.entries(attributes)) {
|
|
1473
|
+
attributeOf(this.#model, name);
|
|
1474
|
+
this.write(name, value);
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
/** A new record: every attribute reads as null until assigned, and initial values are made now. */
|
|
1478
|
+
build(attributes) {
|
|
1479
|
+
for (const name of this.#model.attributeDefinitions.keys()) this.#values[name] = null;
|
|
1480
|
+
for (const [name, value] of initialValues(this.#model)) {
|
|
1481
|
+
this.write(name, value);
|
|
1482
|
+
this.#initialValues.set(name, this.#storedForm(name));
|
|
1483
|
+
}
|
|
1484
|
+
this.assign(attributes);
|
|
1485
|
+
}
|
|
1486
|
+
/** Points this record at `value` through `attribute` (a foreign key), keeping it loaded. */
|
|
1487
|
+
pointAt(name, attribute, key, value) {
|
|
1488
|
+
this.writeKey(attribute, key, name);
|
|
1489
|
+
this.associations.set(name, attribute, value);
|
|
1490
|
+
}
|
|
1491
|
+
/** Forgets an association: what's loaded and its autosaves (`reloadAssociation`). */
|
|
1492
|
+
resetAssociation(name) {
|
|
1493
|
+
this.associations.clear(name);
|
|
1494
|
+
this.autosaves.clear(name);
|
|
1495
|
+
}
|
|
1496
|
+
/** Forgets every association, loaded and autosaved (`reload()`). */
|
|
1497
|
+
clearAssociations() {
|
|
1498
|
+
this.associations.clearAll();
|
|
1499
|
+
this.autosaves.clearAll();
|
|
1500
|
+
}
|
|
1501
|
+
/** Loads a D1 row; the record becomes persisted and clean. */
|
|
1502
|
+
loadRow(row) {
|
|
1503
|
+
let loadedCount = 0;
|
|
1504
|
+
for (const [name, definition] of this.#model.attributeDefinitions) {
|
|
1505
|
+
const { column } = definition;
|
|
1506
|
+
if (!(column in row)) continue;
|
|
1507
|
+
this.#values[name] = this.#attribute(name).read(row[column]);
|
|
1508
|
+
loadedCount++;
|
|
1509
|
+
}
|
|
1510
|
+
this.#markSaved(row, loadedCount);
|
|
1511
|
+
}
|
|
1512
|
+
/** The loaded attributes as a plain object (the record's own values, not copies). */
|
|
1513
|
+
attributes() {
|
|
1514
|
+
return { ...this.#values };
|
|
1515
|
+
}
|
|
1516
|
+
/** A new record's assigned attributes, or a persisted one's that differ from the Snapshot. */
|
|
1517
|
+
changedNames() {
|
|
1518
|
+
if (this.#lifecycle === "new") return [...this.#assigned];
|
|
1519
|
+
return Object.keys(this.#values).filter((name) => !this.#inSnapshot(name) || this.#snapshotOf(name) !== this.#storedForm(name));
|
|
1520
|
+
}
|
|
1521
|
+
/** `{ attribute: [before, after] }`; both are copies, never the record's own objects. */
|
|
1522
|
+
changes() {
|
|
1523
|
+
const changes = {};
|
|
1524
|
+
for (const name of this.changedNames()) changes[name] = [this.#inSnapshot(name) ? this.#snapshotValue(name) : null, this.#copyOf(name)];
|
|
1525
|
+
return changes;
|
|
1526
|
+
}
|
|
1527
|
+
/** `changes()`, with `undefined` before an attribute the record never loaded (a partial record's). */
|
|
1528
|
+
changesSinceLoad() {
|
|
1529
|
+
return Object.fromEntries(Object.entries(this.changes()).map(([name, [before, after]]) => [name, [this.#inSnapshot(name) ? before : void 0, after]]));
|
|
1530
|
+
}
|
|
1531
|
+
/** The changes the last successful save wrote (copies). */
|
|
1532
|
+
savedChanges() {
|
|
1533
|
+
return { ...this.#savedChanges };
|
|
1534
|
+
}
|
|
1535
|
+
/**
|
|
1536
|
+
* An attribute's value as last loaded or saved (a copy). A new record's is its initial
|
|
1537
|
+
* value (a default or generated id), or null, as Rails' `attribute_was` is.
|
|
1538
|
+
*/
|
|
1539
|
+
valueInDatabase(name) {
|
|
1540
|
+
this.read(name);
|
|
1541
|
+
const attribute = this.#attribute(name);
|
|
1542
|
+
if (this.#inSnapshot(name)) return this.#snapshotValue(name);
|
|
1543
|
+
return this.#initialValues.has(name) ? attribute.read(this.#initialValues.get(name)) : null;
|
|
1544
|
+
}
|
|
1545
|
+
/**
|
|
1546
|
+
* Whether the attribute has an unsaved change, optionally `from` and `to` given values
|
|
1547
|
+
* (compared as stored, so dates by time and json by content).
|
|
1548
|
+
*/
|
|
1549
|
+
isAttributeChanged(name, options = {}) {
|
|
1550
|
+
this.read(name);
|
|
1551
|
+
if (!this.changedNames().includes(name)) return false;
|
|
1552
|
+
return this.#matches(name, this.valueInDatabase(name), this.#values[name], options);
|
|
1553
|
+
}
|
|
1554
|
+
/** Whether the last save changed the attribute, optionally `from` and `to` given values. */
|
|
1555
|
+
hasSavedChangeTo(name, options = {}) {
|
|
1556
|
+
this.read(name);
|
|
1557
|
+
const change = this.#savedChanges[name];
|
|
1558
|
+
return change !== void 0 && this.#matches(name, change[0], change[1], options);
|
|
1559
|
+
}
|
|
1560
|
+
/** Puts unsaved changes back: to the Snapshot, or to a new record's initial values (or null). */
|
|
1561
|
+
restore(names = this.changedNames()) {
|
|
1562
|
+
this.#requireNotDestroyed("be changed");
|
|
1563
|
+
for (const name of names) {
|
|
1564
|
+
const attribute = this.#attribute(name);
|
|
1565
|
+
if (this.#lifecycle !== "new") {
|
|
1566
|
+
if (this.#inSnapshot(name)) this.#values[name] = this.#snapshotValue(name);
|
|
1567
|
+
} else if (this.#initialValues.has(name)) this.#values[name] = attribute.read(this.#initialValues.get(name));
|
|
1568
|
+
else {
|
|
1569
|
+
this.#values[name] = null;
|
|
1570
|
+
this.#assigned.delete(name);
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
#matches(name, before, after, options) {
|
|
1575
|
+
const same = (a, b) => this.#attribute(name).same(a, b);
|
|
1576
|
+
return (!("from" in options) || same(options.from, before)) && (!("to" in options) || same(options.to, after));
|
|
1577
|
+
}
|
|
1578
|
+
/** The attributes an insert writes: the assigned ones, so column defaults apply to the rest. */
|
|
1579
|
+
insertAssignments() {
|
|
1580
|
+
return this.#assignmentsOf([...this.#assigned]);
|
|
1581
|
+
}
|
|
1582
|
+
/** The attributes an update writes: the changed ones. */
|
|
1583
|
+
updateAssignments() {
|
|
1584
|
+
return this.#assignmentsOf(this.changedNames());
|
|
1585
|
+
}
|
|
1586
|
+
/** The primary key as stored in D1: the row's key before any unsaved change to it. */
|
|
1587
|
+
get storedKey() {
|
|
1588
|
+
return this.#snapshotOf(this.#model.primaryKey);
|
|
1589
|
+
}
|
|
1590
|
+
/** The stored primary key as a JavaScript value, e.g. to find the row again. */
|
|
1591
|
+
get storedKeyValue() {
|
|
1592
|
+
return this.#attribute(this.#model.primaryKey).read(this.storedKey);
|
|
1593
|
+
}
|
|
1594
|
+
/** After an insert: load what D1 stored; `savedChanges` is everything the new row holds. */
|
|
1595
|
+
commitInsert(row) {
|
|
1596
|
+
if (row === void 0) {
|
|
1597
|
+
this.#settle();
|
|
1598
|
+
this.#markSaved();
|
|
1599
|
+
} else this.loadRow(row);
|
|
1600
|
+
this.#savedChanges = Object.fromEntries(Object.keys(this.#values).filter((name) => this.#values[name] !== null).map((name) => [name, [null, this.#copyOf(name)]]));
|
|
1601
|
+
}
|
|
1602
|
+
/**
|
|
1603
|
+
* After an update: apply values the write added (timestamps), then record the save. Every
|
|
1604
|
+
* attribute holds what was stored (a `unixSeconds` Date has no milliseconds, a `json` NaN is
|
|
1605
|
+
* null), as an insert's re-read row gives (#73, #163), including one assigned a value equal
|
|
1606
|
+
* as stored, which wasn't a change.
|
|
1607
|
+
*/
|
|
1608
|
+
commitUpdate(added) {
|
|
1609
|
+
for (const [name, value] of added) this.#values[name] = value;
|
|
1610
|
+
this.#settle();
|
|
1611
|
+
this.#savedChanges = this.changes();
|
|
1612
|
+
this.#markSaved();
|
|
1613
|
+
}
|
|
1614
|
+
/** A save with nothing to write: nothing changes but `savedChanges`. */
|
|
1615
|
+
commitClean() {
|
|
1616
|
+
this.#savedChanges = {};
|
|
1617
|
+
}
|
|
1618
|
+
markDestroyed() {
|
|
1619
|
+
this.#lifecycle = "destroyed";
|
|
1620
|
+
}
|
|
1621
|
+
/** A destroyed record is a read-only snapshot. (A keyless record may change in memory.) */
|
|
1622
|
+
#requireNotDestroyed(action) {
|
|
1623
|
+
if (this.#lifecycle === "destroyed") throw new RecordDestroyed(`${this.#model.name} record was destroyed; it can't ${action}`);
|
|
1624
|
+
}
|
|
1625
|
+
/** An unknown name is UnknownAttribute, even one every object inherits (`constructor`, #84). */
|
|
1626
|
+
#requireAttribute(name) {
|
|
1627
|
+
this.#definition(name);
|
|
1628
|
+
}
|
|
1629
|
+
#definition(name) {
|
|
1630
|
+
return attributeOf(this.#model, name);
|
|
1631
|
+
}
|
|
1632
|
+
/** The resolved attribute, so a refusal names the Model and attribute. */
|
|
1633
|
+
#attribute(name) {
|
|
1634
|
+
return attributeFor(this.#model, name);
|
|
1635
|
+
}
|
|
1636
|
+
/** An attribute's current value in its stored form, for comparing with the Snapshot. */
|
|
1637
|
+
#storedForm(name) {
|
|
1638
|
+
return this.#attribute(name).write(this.#values[name]);
|
|
1639
|
+
}
|
|
1640
|
+
/** A copy of an attribute's current value, read back from its stored form. */
|
|
1641
|
+
#copyOf(name) {
|
|
1642
|
+
return this.#attribute(name).copy(this.#values[name]);
|
|
1643
|
+
}
|
|
1644
|
+
/** Every loaded attribute becomes what D1 holds for it: its value, written and read back. */
|
|
1645
|
+
#settle() {
|
|
1646
|
+
for (const name of Object.keys(this.#values)) this.#values[name] = this.#copyOf(name);
|
|
1647
|
+
}
|
|
1648
|
+
#assignmentsOf(names) {
|
|
1649
|
+
return names.map((name) => [name, this.#values[name]]);
|
|
1650
|
+
}
|
|
1651
|
+
/**
|
|
1652
|
+
* The current values become the Snapshot: persisted and clean. After a load, the entries for
|
|
1653
|
+
* `row`'s cells (`loadedCount` of the values) are made only when first used, so a record that's
|
|
1654
|
+
* only read never writes them (#91).
|
|
1655
|
+
*/
|
|
1656
|
+
#markSaved(row, loadedCount = 0) {
|
|
1657
|
+
this.#snapshot.clear();
|
|
1658
|
+
this.#snapshotRow = row;
|
|
1659
|
+
const names = Object.keys(this.#values);
|
|
1660
|
+
if (names.length !== loadedCount) {
|
|
1661
|
+
for (const name of names) if (!this.#inRow(name)) this.#snapshot.set(name, this.#storedForm(name));
|
|
1662
|
+
}
|
|
1663
|
+
this.#lifecycle = "persisted";
|
|
1664
|
+
this.#assigned.clear();
|
|
1665
|
+
}
|
|
1666
|
+
/** Whether the Snapshot has `name`: it was loaded or saved. */
|
|
1667
|
+
#inSnapshot(name) {
|
|
1668
|
+
return this.#snapshot.has(name) || this.#inRow(name);
|
|
1669
|
+
}
|
|
1670
|
+
/** `name`'s Snapshot entry, its stored form, made from the loaded row's cell on first use. */
|
|
1671
|
+
#snapshotOf(name) {
|
|
1672
|
+
if (this.#snapshot.has(name) || !this.#inRow(name)) return this.#snapshot.get(name);
|
|
1673
|
+
const attribute = this.#attribute(name);
|
|
1674
|
+
const stored = attribute.write(attribute.read(this.#snapshotRow[this.#definition(name).column]));
|
|
1675
|
+
this.#snapshot.set(name, stored);
|
|
1676
|
+
return stored;
|
|
1677
|
+
}
|
|
1678
|
+
/** `name`'s value as loaded or saved: a fresh copy, read back from its Snapshot entry. */
|
|
1679
|
+
#snapshotValue(name) {
|
|
1680
|
+
return this.#attribute(name).read(this.#snapshotOf(name));
|
|
1681
|
+
}
|
|
1682
|
+
/** Whether the row the Snapshot was loaded from has a cell for `name`. */
|
|
1683
|
+
#inRow(name) {
|
|
1684
|
+
return this.#snapshotRow !== void 0 && this.#definition(name).column in this.#snapshotRow;
|
|
1685
|
+
}
|
|
1686
|
+
};
|
|
1687
|
+
//#endregion
|
|
1688
|
+
//#region src/generated-model.ts
|
|
1689
|
+
const noAttributes = /* @__PURE__ */ new Map();
|
|
1690
|
+
/**
|
|
1691
|
+
* What each generated Model settled on when it was first used, by class (a subclass shares its
|
|
1692
|
+
* parent's). Until then, they're found again on each read, since a `static {}` block reads them
|
|
1693
|
+
* before the statics declared after it exist. Module-level, but not request state (ADR-0003):
|
|
1694
|
+
* derived only from the classes.
|
|
1695
|
+
*/
|
|
1696
|
+
const settled = /* @__PURE__ */ new WeakMap();
|
|
1697
|
+
/** Whether a class is a base for Models, not a Model: it holds a schema, or says it's abstract. */
|
|
1698
|
+
function isBase(each) {
|
|
1699
|
+
return Object.hasOwn(each, "schema") || Object.hasOwn(each, "abstract") && each.abstract === true;
|
|
1700
|
+
}
|
|
1701
|
+
/**
|
|
1702
|
+
* The class a generated Model's table belongs to (the one directly below its nearest base), and
|
|
1703
|
+
* the schema that base holds or inherits. None for a base itself, or a hand-declared Model (one
|
|
1704
|
+
* whose class, or a parent's, declares its own attributes).
|
|
1705
|
+
*/
|
|
1706
|
+
function tableOwnerOf(model) {
|
|
1707
|
+
const chain = ancestors(model);
|
|
1708
|
+
const index = chain.findIndex(isBase);
|
|
1709
|
+
const declared = chain.slice(0, index).some((each) => Object.hasOwn(each, "attributeDefinitions"));
|
|
1710
|
+
if (index <= 0 || declared) return void 0;
|
|
1711
|
+
const schema = chain.slice(index).find((each) => Object.hasOwn(each, "schema"))?.schema;
|
|
1712
|
+
return schema === void 0 ? void 0 : {
|
|
1713
|
+
owner: chain[index - 1],
|
|
1714
|
+
schema
|
|
1715
|
+
};
|
|
1716
|
+
}
|
|
1717
|
+
/** The attribute accessors on a prototype, reading and writing a record's values. */
|
|
1718
|
+
function defineAttributeAccessors(prototype, names) {
|
|
1719
|
+
for (const name of names) Object.defineProperty(prototype, name, {
|
|
1720
|
+
get() {
|
|
1721
|
+
return this[state].read(name);
|
|
1722
|
+
},
|
|
1723
|
+
set(value) {
|
|
1724
|
+
this[state].write(name, value);
|
|
1725
|
+
}
|
|
1726
|
+
});
|
|
1727
|
+
}
|
|
1728
|
+
/**
|
|
1729
|
+
* A Model the schema wasn't generated for, or whose table has changed since, as an
|
|
1730
|
+
* `InvalidModel`: what stops a dev server, which doesn't type-check. A schema with no list of
|
|
1731
|
+
* Models, as `active-record schema` loads the Models with before it has found them, checks none.
|
|
1732
|
+
*/
|
|
1733
|
+
function rejectUngenerated(name, table, schema) {
|
|
1734
|
+
if (schema.models === void 0) return;
|
|
1735
|
+
const generatedTable = Object.hasOwn(schema.models, name) ? schema.models[name] : void 0;
|
|
1736
|
+
if (generatedTable === void 0) throw new InvalidModel(`${name} isn't in the generated schema; run active-record schema`);
|
|
1737
|
+
if (generatedTable !== table) throw new InvalidModel(`${name}'s table is ${table}, but the generated schema has ${generatedTable}; run active-record schema`);
|
|
1738
|
+
}
|
|
1739
|
+
/** Finds a generated Model's table in its schema, and its attributes after its overrides. */
|
|
1740
|
+
function find(owner, schema) {
|
|
1741
|
+
const table = Object.hasOwn(owner, "table") ? owner.table : tableize(owner.name);
|
|
1742
|
+
rejectUngenerated(owner.name, table, schema);
|
|
1743
|
+
const tableSchema = Object.hasOwn(schema.tables, table) ? schema.tables[table] : void 0;
|
|
1744
|
+
if (tableSchema === void 0) throw new InvalidModel(`${owner.name}'s table, ${table}, isn't in the generated schema`);
|
|
1745
|
+
const { specs, ignoresColumns } = specsFor(owner.name, tableSchema, owner.attributes ?? {});
|
|
1746
|
+
const definitions = new Map(Object.entries(specs).map(([name, spec]) => [name, define(name, spec)]));
|
|
1747
|
+
return {
|
|
1748
|
+
table,
|
|
1749
|
+
primaryKey: Object.hasOwn(owner, "primaryKey") ? owner.primaryKey : tableSchema.primaryKey,
|
|
1750
|
+
definitions,
|
|
1751
|
+
ignoresColumns
|
|
1752
|
+
};
|
|
1753
|
+
}
|
|
1754
|
+
/**
|
|
1755
|
+
* A generated Model's table, primary key and attributes; undefined for any other class. What it
|
|
1756
|
+
* settled on, once it's been used; otherwise found again.
|
|
1757
|
+
*/
|
|
1758
|
+
function generated(model) {
|
|
1759
|
+
const found = settled.get(model);
|
|
1760
|
+
if (found !== void 0) return found;
|
|
1761
|
+
const place = tableOwnerOf(model);
|
|
1762
|
+
if (place === void 0) return void 0;
|
|
1763
|
+
return settled.get(place.owner) ?? find(place.owner, place.schema);
|
|
1764
|
+
}
|
|
1765
|
+
/**
|
|
1766
|
+
* Settles a generated Model's table and attributes the first time it's used, when its class
|
|
1767
|
+
* and its statics are all defined: binds its table, and defines its attribute accessors.
|
|
1768
|
+
*/
|
|
1769
|
+
function settleGenerated(model) {
|
|
1770
|
+
if (settled.has(model)) return;
|
|
1771
|
+
const place = tableOwnerOf(model);
|
|
1772
|
+
if (place === void 0) return;
|
|
1773
|
+
const { owner } = place;
|
|
1774
|
+
let found = settled.get(owner);
|
|
1775
|
+
if (found === void 0) {
|
|
1776
|
+
found = find(owner, place.schema);
|
|
1777
|
+
bindTable(owner, found.table, { ignoresColumns: found.ignoresColumns });
|
|
1778
|
+
defineAttributeAccessors(owner.prototype, found.definitions.keys());
|
|
1779
|
+
settled.set(owner, found);
|
|
1780
|
+
}
|
|
1781
|
+
settled.set(model, found);
|
|
1782
|
+
}
|
|
1783
|
+
/**
|
|
1784
|
+
* Whether a class's attributes are fixed: a hand-declared Model's are when it's defined, and a
|
|
1785
|
+
* generated Model's when it's first used. A base class has none, which is fixed too.
|
|
1786
|
+
*/
|
|
1787
|
+
function attributesSettled(model) {
|
|
1788
|
+
return settled.has(model) || tableOwnerOf(model) === void 0;
|
|
1789
|
+
}
|
|
1790
|
+
/** Whether a class is a generated Model: built on a base holding a generated schema. */
|
|
1791
|
+
function isGenerated(model) {
|
|
1792
|
+
return generated(model) !== void 0;
|
|
1793
|
+
}
|
|
1794
|
+
/** The adapter the generated schema a Model's base holds names, if any. */
|
|
1795
|
+
function schemaAdapter(model) {
|
|
1796
|
+
return ancestors(model).find((each) => Object.hasOwn(each, "schema"))?.schema?.adapter;
|
|
1797
|
+
}
|
|
1798
|
+
/**
|
|
1799
|
+
* The library's base class's `table`, `primaryKey` and `attributeDefinitions`: a generated
|
|
1800
|
+
* Model's from its schema, and otherwise none (a hand-declared Model sets its own).
|
|
1801
|
+
*/
|
|
1802
|
+
function defineGeneratedStatics(root) {
|
|
1803
|
+
const statics = {
|
|
1804
|
+
table: (model) => generated(model)?.table ?? "",
|
|
1805
|
+
primaryKey: (model) => generated(model)?.primaryKey ?? "id",
|
|
1806
|
+
attributeDefinitions: (model) => generated(model)?.definitions ?? noAttributes
|
|
1807
|
+
};
|
|
1808
|
+
for (const [name, read] of Object.entries(statics)) Object.defineProperty(root, name, {
|
|
1809
|
+
configurable: true,
|
|
1810
|
+
get() {
|
|
1811
|
+
return read(this);
|
|
1812
|
+
},
|
|
1813
|
+
set: ownValueSetter(name)
|
|
1814
|
+
});
|
|
1815
|
+
}
|
|
1816
|
+
/**
|
|
1817
|
+
* An override as given, checked (TypeScript checks it too, but not in plain JavaScript or past
|
|
1818
|
+
* a cast): `false` to ignore the column, or the spec changes.
|
|
1819
|
+
*/
|
|
1820
|
+
function checked(where, attribute, override) {
|
|
1821
|
+
if (override === false) return false;
|
|
1822
|
+
if (isAttributeType(override)) return { type: override };
|
|
1823
|
+
if (!isSpecOverride(override)) throw new InvalidModel(`${where}.${attribute}: an override is a type name, { ${overridableKeyNames} }, or false`);
|
|
1824
|
+
return override;
|
|
1825
|
+
}
|
|
1826
|
+
/**
|
|
1827
|
+
* A generated spec with an override applied, refused if it leaves a spec a type can't have (#99,
|
|
1828
|
+
* #73). The merged spec's type isn't known statically, so it's checked here, as a Model's is.
|
|
1829
|
+
*/
|
|
1830
|
+
function checkedOverride(where, spec, change) {
|
|
1831
|
+
const changed = applyOverride(typeof spec === "string" ? { type: spec } : spec, change);
|
|
1832
|
+
const problem = specProblem(where, changed);
|
|
1833
|
+
if (problem !== void 0) throw new InvalidModel(problem);
|
|
1834
|
+
return changed;
|
|
1835
|
+
}
|
|
1836
|
+
/** A table's attribute specs with `overrides` applied; throws `InvalidModel` for a bad one. */
|
|
1837
|
+
function specsFor(name, table, overrides) {
|
|
1838
|
+
const changes = /* @__PURE__ */ new Map();
|
|
1839
|
+
for (const [attribute, override] of Object.entries(overrides)) {
|
|
1840
|
+
if (override === void 0) continue;
|
|
1841
|
+
if (!Object.hasOwn(table.attributes, attribute)) throw new InvalidModel(`${name} has no attribute ${attribute} to override`);
|
|
1842
|
+
if (override === false && attribute === table.primaryKey) throw new InvalidModel(`${name}.${attribute} is the primary key, so it can't be ignored`);
|
|
1843
|
+
changes.set(attribute, checked(name, attribute, override));
|
|
1844
|
+
}
|
|
1845
|
+
const specs = {};
|
|
1846
|
+
for (const [attribute, spec] of Object.entries(table.attributes)) {
|
|
1847
|
+
const change = changes.get(attribute);
|
|
1848
|
+
if (change === false) continue;
|
|
1849
|
+
specs[attribute] = change === void 0 ? spec : checkedOverride(`${name}.${attribute}`, spec, change);
|
|
1850
|
+
}
|
|
1851
|
+
return {
|
|
1852
|
+
specs,
|
|
1853
|
+
ignoresColumns: [...changes.values()].includes(false)
|
|
1854
|
+
};
|
|
1855
|
+
}
|
|
1856
|
+
//#endregion
|
|
1857
|
+
export { CallbackAbort as $, requireDefined as A, shownKey as B, castInherited as C, attributesForColumn as D, attributeOf as E, zonelessDateTime as F, modelClassName as G, explainMissingTable as H, Filtered as I, tableize as J, rejectAbstract as K, boundValue as L, castValue as M, uncastable as N, define as O, writeUntypedValue as P, AssociationNotLoaded as Q, defaultFilterAttributes as R, attributeFor as S, storedRows as T, ignoresColumns as U, shownValue$1 as V, inferTableNames as W, AbortAfterPersistence as X, ancestors as Y, ActiveRecordError as Z, attributesNamedInMessages as _, UnknownAttribute as _t, isGenerated as a, InvalidModel as at, declared as b, RecordState as c, NoDatabase as ct, Errors as d, RecordInvalid as dt, CheckViolation as et, addFailure as f, RecordNotDestroyed as ft, printed as g, UnknownAssociation as gt, inspectCustom as h, RecordNotUnique as ht, isBase as i, InvalidForeignKey as it, specProblem as j, initialValues as k, linksOf as l, NotNullViolation as lt, FilteredMark as m, RecordNotSaved as mt, defineAttributeAccessors as n, DeleteRestriction as nt, schemaAdapter as o, IrreversibleOrder as ot, clearErrors as p, RecordNotFound as pt, requireTableName as q, defineGeneratedStatics as r, IncompatibleRelation as rt, settleGenerated as s, MissingAttribute as st, attributesSettled as t, ConstraintViolation as tt, state as u, RecordDestroyed as ut, humanAttributeName as v, abort as vt, noMatch as w, seal as x, declare as y, isFiltered as z };
|