@forestfuture/active-record 0.6.0 → 0.8.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/README.md +5 -4
- package/config-schema.json +60 -0
- package/dist/adapter.d.mts +3 -2
- package/dist/adapter.mjs +5 -3
- package/dist/batch-ReqVoCfa.mjs +9559 -0
- package/dist/cli.d.mts +216 -46
- package/dist/cli.mjs +4 -3
- package/dist/command.mjs +1102 -529
- package/dist/d1.d.mts +60 -0
- package/dist/d1.mjs +334 -0
- package/dist/epoch-storage-CDlQZcBB.mjs +988 -0
- package/dist/for-adapters-B0xMP6Dq.d.mts +23 -0
- package/dist/for-adapters-CfXMGeOu.mjs +31 -0
- package/dist/for-adapters-DhNV1mWf.mjs +276 -0
- package/dist/{generated-model-CfDggoVN.mjs → generated-model-g5oWsDKE.mjs} +732 -540
- package/dist/index-BATasvJa.d.mts +241 -0
- package/dist/index.d.mts +4 -143
- package/dist/index.mjs +5 -3
- package/dist/metadata-CzntpYzC.d.mts +182 -0
- package/dist/plugin-wOSILvSB.mjs +699 -0
- package/dist/plugin-x5-d3TSN.mjs +1035 -0
- package/dist/postgresql.d.mts +64 -0
- package/dist/postgresql.mjs +604 -0
- package/dist/src-D56_3odT.mjs +46 -0
- package/dist/storage-override-n4w1cS_M.mjs +220 -0
- package/dist/validations-DHDVV8hB.d.mts +1996 -0
- package/llms-full.txt +3283 -656
- package/package.json +25 -2
- package/skills/active-record/SKILL.md +24 -16
- package/dist/adapter-BSvFhTDf.d.mts +0 -1293
- package/dist/batch-DBeYk5wx.mjs +0 -4171
- package/dist/epoch-storage-o2aoOH7H.mjs +0 -112
- package/dist/storage-override-BYBYP8Mj.mjs +0 -91
|
@@ -1,146 +1,23 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
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
|
|
1
|
+
import { C as pluralize, E as underscore, H as RecordDestroyed, I as InvalidModel, R as MissingAttribute, S as listedNames, Z as UnknownAttribute, _ as enumEntries, a as castKey, c as readValue, d as writeValue, g as reservedWords, h as isIdentifier, i as castCondition, l as uncastable, m as isSameCell, n as digitsProblem, o as castValue, s as isInvalidDate, t as epochStorages, v as enumProblem, x as isEnumValues, z as NoDatabase } from "./epoch-storage-CDlQZcBB.mjs";
|
|
2
|
+
// src/ancestors.ts
|
|
136
3
|
/** A class and every class (and object) it extends, nearest first. */
|
|
137
4
|
function ancestors(model) {
|
|
138
5
|
const chain = [];
|
|
139
6
|
for (let current = model; current !== null; current = Object.getPrototypeOf(current)) chain.push(current);
|
|
140
7
|
return chain;
|
|
141
8
|
}
|
|
142
|
-
|
|
143
|
-
|
|
9
|
+
/**
|
|
10
|
+
* How `model`, or the nearest class it extends below `root`, declares the static `name`: its
|
|
11
|
+
* property descriptor, read without calling a getter, or undefined when none does.
|
|
12
|
+
*/
|
|
13
|
+
function staticBelow(model, root, name) {
|
|
14
|
+
for (const each of ancestors(model)) {
|
|
15
|
+
if (each === root) return void 0;
|
|
16
|
+
const declared = Object.getOwnPropertyDescriptor(each, name);
|
|
17
|
+
if (declared !== void 0) return declared;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
// src/table-names.ts
|
|
144
21
|
/**
|
|
145
22
|
* The classes `Model.define({...})` makes; their `table` is inferred unless a subclass sets one.
|
|
146
23
|
* Module-level, but not request state (ADR-0003): derived only from the classes.
|
|
@@ -152,19 +29,37 @@ const bases = /* @__PURE__ */ new WeakSet();
|
|
|
152
29
|
*/
|
|
153
30
|
const boundTables = /* @__PURE__ */ new WeakMap();
|
|
154
31
|
/**
|
|
155
|
-
* Each Model's answer to `
|
|
32
|
+
* Each Model's answer to `isIgnoringColumns`, remembered since the compiler asks on every query.
|
|
156
33
|
* Module-level, but not request state (ADR-0003): derived only from the class.
|
|
157
34
|
*/
|
|
158
35
|
const ignoring = /* @__PURE__ */ new WeakMap();
|
|
36
|
+
/** A class's `modelName`: its own name, unless it (or a class it extends) sets one. */
|
|
37
|
+
function modelNameOf(model) {
|
|
38
|
+
return model.modelName;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Gives the library's base class `modelName`: each class's own name, as Rails' `model_name`,
|
|
42
|
+
* unless it sets `static modelName = "…"`, which the classes extending it inherit (a set one is
|
|
43
|
+
* a value, found before this getter). Empty for a class with no name: anonymous, or `export
|
|
44
|
+
* default`.
|
|
45
|
+
*/
|
|
46
|
+
function defineModelName(root) {
|
|
47
|
+
Object.defineProperty(root, "modelName", {
|
|
48
|
+
configurable: true,
|
|
49
|
+
get() {
|
|
50
|
+
return this.name === "default" ? "" : this.name;
|
|
51
|
+
},
|
|
52
|
+
set: ownValueSetter("modelName")
|
|
53
|
+
});
|
|
54
|
+
}
|
|
159
55
|
/**
|
|
160
|
-
* The
|
|
161
|
-
* Rails; empty when it has none (anonymous, `export default`, or `Model.define({...})` itself).
|
|
56
|
+
* The `modelName` of the class that extends `base` directly, the one a table is named after, as
|
|
57
|
+
* in Rails; empty when it has none (anonymous, `export default`, or `Model.define({...})` itself).
|
|
162
58
|
*/
|
|
163
|
-
function
|
|
59
|
+
function modelNameBelow(base, model) {
|
|
164
60
|
let current = model;
|
|
165
61
|
while (current !== base && Object.getPrototypeOf(current) !== base) current = Object.getPrototypeOf(current);
|
|
166
|
-
|
|
167
|
-
return current === base || name === "default" ? "" : name;
|
|
62
|
+
return current === base ? "" : modelNameOf(current);
|
|
168
63
|
}
|
|
169
64
|
/**
|
|
170
65
|
* A class name's table, by Rails' `tableize`: the name through `underscore`, pluralized
|
|
@@ -197,27 +92,27 @@ function inferTableNames(base) {
|
|
|
197
92
|
Object.defineProperty(base, "table", {
|
|
198
93
|
configurable: true,
|
|
199
94
|
get() {
|
|
200
|
-
const name =
|
|
95
|
+
const name = modelNameBelow(base, this);
|
|
201
96
|
return name === "" ? "" : tableize(name);
|
|
202
97
|
},
|
|
203
98
|
set: ownValueSetter("table")
|
|
204
99
|
});
|
|
205
100
|
}
|
|
206
|
-
/** The
|
|
101
|
+
/** The modelName a Model's table name was inferred from, or undefined when it's declared. */
|
|
207
102
|
function tableNameSource(model) {
|
|
208
103
|
const owner = ancestors(model).find((each) => Object.hasOwn(each, "table"));
|
|
209
|
-
return owner !== void 0 && bases.has(owner) && !boundTables.has(owner) ?
|
|
104
|
+
return owner !== void 0 && bases.has(owner) && !boundTables.has(owner) ? modelNameBelow(owner, model) : void 0;
|
|
210
105
|
}
|
|
211
106
|
/**
|
|
212
107
|
* Binds a generated Model's table to the class it belongs to: a subclass can't name another,
|
|
213
108
|
* since the attributes are that table's columns; and records whether its overrides ignore some
|
|
214
109
|
* columns.
|
|
215
110
|
*/
|
|
216
|
-
function bindTable(owner, table, {
|
|
111
|
+
function bindTable(owner, table, { isIgnoringColumns }) {
|
|
217
112
|
owner.table = table;
|
|
218
113
|
boundTables.set(owner, {
|
|
219
114
|
table,
|
|
220
|
-
|
|
115
|
+
isIgnoringColumns
|
|
221
116
|
});
|
|
222
117
|
}
|
|
223
118
|
/** The table bound to the class `model` is, or extends, if any. */
|
|
@@ -234,10 +129,10 @@ function boundTableOf(model) {
|
|
|
234
129
|
* Remembered per Model: its table is bound when it's first used, before any query, so the
|
|
235
130
|
* answer can't change.
|
|
236
131
|
*/
|
|
237
|
-
function
|
|
132
|
+
function isIgnoringColumns(model) {
|
|
238
133
|
let answer = ignoring.get(model);
|
|
239
134
|
if (answer === void 0) {
|
|
240
|
-
answer = boundTableOf(model)?.
|
|
135
|
+
answer = boundTableOf(model)?.isIgnoringColumns ?? false;
|
|
241
136
|
ignoring.set(model, answer);
|
|
242
137
|
}
|
|
243
138
|
return answer;
|
|
@@ -252,13 +147,18 @@ function rejectAbstract(model) {
|
|
|
252
147
|
const example = model.name ? `, such as class Product extends ${model.name} {}` : "";
|
|
253
148
|
throw new InvalidModel(`${model.name || "This class"} is an abstract base class, with no table; use a Model that extends it${example}`);
|
|
254
149
|
}
|
|
255
|
-
/** A Model must
|
|
150
|
+
/** A Model's `modelName` must be a string, since names are made from it and the schema lists it by it. */
|
|
151
|
+
function requireModelName(model) {
|
|
152
|
+
if (typeof model.modelName === "string") return;
|
|
153
|
+
throw new InvalidModel(`${model.name}'s modelName must be a string; remove it to use the class name`);
|
|
154
|
+
}
|
|
155
|
+
/** A Model must have a table name: its own, or one inferred from its modelName. */
|
|
256
156
|
function requireTableName(model) {
|
|
257
157
|
const { table } = model;
|
|
258
158
|
const bound = boundTableOf(model);
|
|
259
159
|
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
160
|
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
|
|
161
|
+
throw new InvalidModel(tableNameSource(model) === "" ? `${model.name || "A Model class"} has no class name to infer its table from; set static table, or static modelName` : `${model.name}'s table must be a table's name; remove it to use the one inferred from its modelName`);
|
|
262
162
|
}
|
|
263
163
|
/**
|
|
264
164
|
* A database's "no such table" for a table whose name was inferred, as an `InvalidModel` saying where
|
|
@@ -269,311 +169,198 @@ function explainMissingTable(adapter, error, models) {
|
|
|
269
169
|
const model = models.find((each) => each.table === table && tableNameSource(each));
|
|
270
170
|
const source = model && tableNameSource(model);
|
|
271
171
|
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
|
|
172
|
+
return new InvalidModel(`${model.name}'s table "${table}" doesn't exist in ${adapter.name} (inferred from the modelName ${source}; create it, set static table, or set static modelName if your bundler renames classes)`, { cause: error });
|
|
273
173
|
}
|
|
274
174
|
/**
|
|
275
|
-
* The
|
|
276
|
-
* is (`Post`, for `class FeaturedPost extends Post {}`).
|
|
175
|
+
* The name a Model's foreign keys are inferred from: the `modelName` of the class whose table
|
|
176
|
+
* it is (`Post`, for `class FeaturedPost extends Post {}`).
|
|
277
177
|
*/
|
|
278
|
-
function
|
|
178
|
+
function tableOwnerModelName(model) {
|
|
279
179
|
const base = ancestors(model).find((each) => bases.has(each));
|
|
280
|
-
if (base !== void 0) return
|
|
281
|
-
return (boundTableOf(model)?.owner ?? model)
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
const
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
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);
|
|
180
|
+
if (base !== void 0) return modelNameBelow(base, model);
|
|
181
|
+
return modelNameOf(boundTableOf(model)?.owner ?? model);
|
|
182
|
+
}
|
|
183
|
+
// src/enum-methods.ts
|
|
184
|
+
/** Each name of every enum attribute, with the methods it gives. */
|
|
185
|
+
function enumNames(definitions) {
|
|
186
|
+
return [...definitions].flatMap(([attribute, definition]) => {
|
|
187
|
+
if (definition.enum === void 0) return [];
|
|
188
|
+
const before = affix(attribute, definition.prefix);
|
|
189
|
+
const after = affix(attribute, definition.suffix);
|
|
190
|
+
return enumEntries(definition.enum).map(([name]) => {
|
|
191
|
+
const stem = `${before}${methodPart(name)}${after}`;
|
|
192
|
+
const records = [
|
|
193
|
+
`is${stem}`,
|
|
194
|
+
`saveAs${stem}`,
|
|
195
|
+
`saveAs${stem}OrThrow`
|
|
196
|
+
];
|
|
197
|
+
const scopes = [uncapitalized(stem), `not${stem}`];
|
|
198
|
+
return {
|
|
199
|
+
attribute,
|
|
200
|
+
name,
|
|
201
|
+
records: definition.instanceMethods === false ? [] : records,
|
|
202
|
+
scopes: definition.scopes === false ? [] : scopes
|
|
203
|
+
};
|
|
204
|
+
});
|
|
205
|
+
});
|
|
401
206
|
}
|
|
402
|
-
function
|
|
403
|
-
|
|
207
|
+
function affix(attribute, option) {
|
|
208
|
+
if (option === true) return methodPart(attribute);
|
|
209
|
+
return typeof option === "string" ? methodPart(option) : "";
|
|
404
210
|
}
|
|
405
|
-
/**
|
|
406
|
-
|
|
407
|
-
|
|
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;
|
|
211
|
+
/** The scopes the enums of `definitions` give a Model, as `EnumStatics` types them. */
|
|
212
|
+
function enumScopeNames(definitions) {
|
|
213
|
+
return enumNames(definitions).flatMap(({ scopes }) => scopes);
|
|
431
214
|
}
|
|
432
|
-
/**
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
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
|
-
}
|
|
215
|
+
/** How a word reads inside a method's name, as `MethodPart` types it. */
|
|
216
|
+
function methodPart(word) {
|
|
217
|
+
const [head = "", ...rest] = word.split("_");
|
|
218
|
+
return capitalized(head + rest.map(capitalized).join(""));
|
|
445
219
|
}
|
|
220
|
+
const capitalized = (text) => text.charAt(0).toUpperCase() + text.slice(1);
|
|
221
|
+
const uncapitalized = (text) => text.charAt(0).toLowerCase() + text.slice(1);
|
|
446
222
|
/**
|
|
447
|
-
*
|
|
448
|
-
*
|
|
449
|
-
*
|
|
223
|
+
* Defines each enum attribute's methods on `prototype`: `isPublished()` is `status === "published"`,
|
|
224
|
+
* and `saveAsPublished()` is `update({ status: "published" })`, so it saves the record's other
|
|
225
|
+
* changes too, as Rails' `published!` does.
|
|
450
226
|
*/
|
|
451
|
-
function
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
227
|
+
function defineEnumMethods(prototype, definitions) {
|
|
228
|
+
for (const { attribute, name, records } of enumNames(definitions)) {
|
|
229
|
+
const [predicate, setter, throwingSetter] = records;
|
|
230
|
+
if (predicate === void 0) continue;
|
|
231
|
+
defineMethod(prototype, predicate, function() {
|
|
232
|
+
return this[attribute] === name;
|
|
233
|
+
});
|
|
234
|
+
defineMethod(prototype, setter, function() {
|
|
235
|
+
return this.update({ [attribute]: name });
|
|
236
|
+
});
|
|
237
|
+
defineMethod(prototype, throwingSetter, function() {
|
|
238
|
+
return this.updateOrThrow({ [attribute]: name });
|
|
239
|
+
});
|
|
457
240
|
}
|
|
458
241
|
}
|
|
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
242
|
/**
|
|
507
|
-
*
|
|
508
|
-
*
|
|
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).
|
|
243
|
+
* Defines each enum attribute's scopes on `model`, as `this.scope(…)` statics: `published()` is
|
|
244
|
+
* `where({ status: "published" })`, and `notPublished()` is `whereNot(…)`, as Rails' are.
|
|
512
245
|
*/
|
|
513
|
-
function
|
|
514
|
-
|
|
515
|
-
const
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
246
|
+
function defineEnumStatics(model, definitions) {
|
|
247
|
+
const declaring = model;
|
|
248
|
+
for (const { attribute, name, scopes } of enumNames(definitions)) {
|
|
249
|
+
const [only, without] = scopes;
|
|
250
|
+
if (only === void 0) continue;
|
|
251
|
+
const onlyScope = declaring.scope((q) => q.where({ [attribute]: name }));
|
|
252
|
+
const withoutScope = declaring.scope((q) => q.whereNot({ [attribute]: name }));
|
|
253
|
+
enumScopes.add(onlyScope);
|
|
254
|
+
enumScopes.add(withoutScope);
|
|
255
|
+
defineMethod(model, only, onlyScope, { named: false });
|
|
256
|
+
defineMethod(model, without, withoutScope, { named: false });
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
/** Puts `method` on `target` as `name`, writable as a declared method is, and names it unless told not to. */
|
|
260
|
+
function defineMethod(target, name, method, { named = true } = {}) {
|
|
261
|
+
if (Object.hasOwn(target, name)) return;
|
|
262
|
+
if (named) Object.defineProperty(method, "name", { value: name });
|
|
263
|
+
Object.defineProperty(target, name, {
|
|
264
|
+
value: method,
|
|
265
|
+
writable: true,
|
|
266
|
+
configurable: true
|
|
267
|
+
});
|
|
519
268
|
}
|
|
269
|
+
/** The scope statics `defineEnumStatics` made, so a static a Model declares itself is told apart. */
|
|
270
|
+
const enumScopes = /* @__PURE__ */ new WeakSet();
|
|
520
271
|
/**
|
|
521
|
-
*
|
|
522
|
-
*
|
|
523
|
-
*
|
|
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).
|
|
272
|
+
* Why an enum's method names can't be as they are, or undefined: two enums give one name, or one
|
|
273
|
+
* takes the name of a record method, an attribute, a Relation method, a Model static, or a static
|
|
274
|
+
* the Model declares itself. Rails refuses the same when an enum is declared.
|
|
526
275
|
*/
|
|
527
|
-
function
|
|
528
|
-
const
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
276
|
+
function enumNameProblem(model, taken, methodsOff = /* @__PURE__ */ new Map()) {
|
|
277
|
+
const checks = {
|
|
278
|
+
...taken,
|
|
279
|
+
methodsOffFix: (attribute) => methodsOff.get(attribute)
|
|
280
|
+
};
|
|
281
|
+
const givenBy = /* @__PURE__ */ new Map();
|
|
282
|
+
for (const each of enumNames(model.attributeDefinitions)) {
|
|
283
|
+
const { attribute, records, scopes } = each;
|
|
284
|
+
for (const method of [...records, ...scopes]) {
|
|
285
|
+
const other = givenBy.get(method);
|
|
286
|
+
if (other !== void 0) return repeated(model.name, {
|
|
287
|
+
first: other,
|
|
288
|
+
second: attribute,
|
|
289
|
+
method
|
|
290
|
+
}, checks);
|
|
291
|
+
givenBy.set(method, attribute);
|
|
292
|
+
}
|
|
293
|
+
const problem = declarableProblem(model, each, [...records, ...scopes], checks) ?? recordProblem(model, attribute, records, checks) ?? staticProblem(model, attribute, scopes, checks);
|
|
294
|
+
if (problem !== void 0) return problem;
|
|
295
|
+
}
|
|
532
296
|
}
|
|
533
297
|
/**
|
|
534
|
-
*
|
|
535
|
-
*
|
|
298
|
+
* A method name an enum's name gives that TypeScript can't declare (#340): one that isn't an
|
|
299
|
+
* identifier (`isIn-progress`), or a scope that's a reserved word (`new`), which the generated
|
|
300
|
+
* schema couldn't declare as a static.
|
|
536
301
|
*/
|
|
537
|
-
function
|
|
538
|
-
const
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
if (
|
|
552
|
-
const
|
|
553
|
-
return
|
|
554
|
-
}
|
|
555
|
-
/** `
|
|
556
|
-
function
|
|
557
|
-
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
return
|
|
566
|
-
}
|
|
567
|
-
|
|
568
|
-
|
|
302
|
+
function declarableProblem(model, { attribute, name, scopes }, methods, checks) {
|
|
303
|
+
const fix = remedy(attribute, checks);
|
|
304
|
+
const undeclarable = methods.find((method) => !isIdentifier(method));
|
|
305
|
+
if (undeclarable !== void 0) {
|
|
306
|
+
const kind = scopes.includes(undeclarable) ? "scope" : "method";
|
|
307
|
+
const suggested = uncapitalized(methodPart(name.split(/[^\p{L}\p{N}_$]+/u).join("_")));
|
|
308
|
+
const example = isIdentifier(suggested) ? ` ({ ${suggested}: ${JSON.stringify(name)} })` : "";
|
|
309
|
+
return `${model.name}'s enum ${attribute} gives a ${kind} named "${undeclarable}", which isn't a name TypeScript can declare; name it with letters, digits, _ and $, and map it to the value it's stored as${example}${offFix(attribute, checks)}`;
|
|
310
|
+
}
|
|
311
|
+
const reserved = methods.find((method) => reservedWords.has(method));
|
|
312
|
+
return reserved === void 0 ? void 0 : `${model.name}'s enum ${attribute} gives a scope named "${reserved}", which is a reserved word; ${fix}`;
|
|
313
|
+
}
|
|
314
|
+
/** Two of an enum's names, or two enums, giving one method name. */
|
|
315
|
+
function repeated(model, { first, second, method }, checks) {
|
|
316
|
+
if (first !== second) return `${model}'s enums ${first} and ${second} both give a method named "${method}"; give one a prefix or a suffix${[first, second].map((attribute) => namedOffFix(attribute, checks)).join("")}`;
|
|
317
|
+
const off = offFix(second, checks);
|
|
318
|
+
return `${model}'s enum ${first} gives "${method}" for two of its names; ${off === "" ? "rename one" : "map one to a name of your own"}${off}`;
|
|
319
|
+
}
|
|
320
|
+
/** `offFix`, naming the enum: for a message about two of them. */
|
|
321
|
+
function namedOffFix(attribute, checks) {
|
|
322
|
+
const fix = checks.methodsOffFix(attribute);
|
|
323
|
+
return fix === void 0 ? "" : `, or leave ${attribute}'s methods off (remove ${fix})`;
|
|
324
|
+
}
|
|
325
|
+
/** How to fix an enum whose method name is taken: an affix, or for the database's, its methods off. */
|
|
326
|
+
const remedy = (attribute, checks) => `give ${attribute} a prefix or a suffix${offFix(attribute, checks)}`;
|
|
327
|
+
/** For an enum whose names the database gave (#64): leaving its methods off, as they start. */
|
|
328
|
+
function offFix(attribute, checks) {
|
|
329
|
+
const fix = checks.methodsOffFix(attribute);
|
|
330
|
+
return fix === void 0 ? "" : `, or leave its methods off (remove ${fix})`;
|
|
331
|
+
}
|
|
332
|
+
function recordProblem(model, attribute, methods, checks) {
|
|
333
|
+
for (const method of methods) {
|
|
334
|
+
const what = model.attributeDefinitions.has(method) ? "an attribute" : checks.isRecordName(method) ? "a record method" : void 0;
|
|
335
|
+
if (what !== void 0) return `${model.name}'s enum ${attribute} gives a method named "${method}", which is the name of ${what}; ${remedy(attribute, checks)}`;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
function staticProblem(model, attribute, scopes, checks) {
|
|
339
|
+
for (const scope of scopes) {
|
|
340
|
+
const what = scope in Function.prototype ? "a Function method" : checks.isReservedStatic(scope) ? "a Relation method or a Model static" : void 0;
|
|
341
|
+
if (what !== void 0) return `${model.name}'s enum ${attribute} gives a scope named "${scope}", which is the name of ${what}; ${remedy(attribute, checks)}`;
|
|
342
|
+
const declared = checks.staticOf(scope);
|
|
343
|
+
const isEnumScope = typeof declared?.value === "function" && enumScopes.has(declared.value);
|
|
344
|
+
if (declared !== void 0 && !isEnumScope) return `${model.name} declares "${scope}", which is also the name of a scope its enum ${attribute} gives; rename it, or ${remedy(attribute, checks)}`;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
// src/spec-keys.ts
|
|
569
348
|
const attributeTypes = Object.keys({
|
|
570
349
|
string: true,
|
|
571
350
|
integer: true,
|
|
572
351
|
real: true,
|
|
352
|
+
decimal: true,
|
|
573
353
|
boolean: true,
|
|
574
354
|
datetime: true,
|
|
575
|
-
|
|
355
|
+
date: true,
|
|
356
|
+
time: true,
|
|
357
|
+
json: true,
|
|
358
|
+
binary: true
|
|
576
359
|
});
|
|
360
|
+
/** The built-in types' names, as a message lists them: `"string", "integer", …`. */
|
|
361
|
+
const typeNameList = attributeTypes.map((name) => `"${String(name)}"`).join(", ");
|
|
362
|
+
/** The built-in types' names as a list to choose from: `"string", …, or "binary"`. */
|
|
363
|
+
const attributeTypeNames = typeNameList.replace(/, ([^,]+)$/, ", or $1");
|
|
577
364
|
/** Whether `value` names an attribute type. */
|
|
578
365
|
function isAttributeType(value) {
|
|
579
366
|
return attributeTypes.includes(value);
|
|
@@ -584,7 +371,7 @@ function isAttributeType(value) {
|
|
|
584
371
|
*/
|
|
585
372
|
const rules = {
|
|
586
373
|
type: {
|
|
587
|
-
isWellFormed: isAttributeType,
|
|
374
|
+
isWellFormed: (value) => isAttributeType(value) || isCustomType(value),
|
|
588
375
|
copiedToDefinition: false
|
|
589
376
|
},
|
|
590
377
|
null: {
|
|
@@ -620,8 +407,81 @@ const rules = {
|
|
|
620
407
|
because: "only a datetime is stored as an epoch"
|
|
621
408
|
},
|
|
622
409
|
onRetype: "drop"
|
|
410
|
+
},
|
|
411
|
+
precision: decimalDigits("a precision"),
|
|
412
|
+
scale: decimalDigits("a scale"),
|
|
413
|
+
enum: {
|
|
414
|
+
isWellFormed: isEnumValues,
|
|
415
|
+
describedAs: "an enum",
|
|
416
|
+
onlyFor: {
|
|
417
|
+
types: ["string", "integer"],
|
|
418
|
+
because: "an enum is stored as text or integers"
|
|
419
|
+
},
|
|
420
|
+
problemFor: enumProblem,
|
|
421
|
+
onRetype: "drop"
|
|
422
|
+
},
|
|
423
|
+
prefix: affixRule("prefix"),
|
|
424
|
+
suffix: affixRule("suffix"),
|
|
425
|
+
scopes: methodsSwitch("scopes"),
|
|
426
|
+
instanceMethods: methodsSwitch("instanceMethods"),
|
|
427
|
+
validate: {
|
|
428
|
+
isWellFormed: isEnumValidation,
|
|
429
|
+
describedAs: "validate",
|
|
430
|
+
wellFormedAs: "use true, or { allowNull: true }",
|
|
431
|
+
isGiven: isGivenUnless(false),
|
|
432
|
+
requires: "enum",
|
|
433
|
+
onRetype: "drop"
|
|
623
434
|
}
|
|
624
435
|
};
|
|
436
|
+
/** The rule for a decimal's precision or scale: a whole number of digits. */
|
|
437
|
+
function decimalDigits(describedAs) {
|
|
438
|
+
return {
|
|
439
|
+
isWellFormed: (value) => Number.isSafeInteger(value) && value >= 0,
|
|
440
|
+
describedAs,
|
|
441
|
+
wellFormedAs: "use a whole number of digits",
|
|
442
|
+
onlyFor: {
|
|
443
|
+
types: ["decimal"],
|
|
444
|
+
because: "only a decimal has digits to limit"
|
|
445
|
+
},
|
|
446
|
+
onRetype: "drop"
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
/** `true`, `false`, or an object holding only a boolean `allowNull`. */
|
|
450
|
+
function isEnumValidation(value) {
|
|
451
|
+
if (typeof value === "boolean") return true;
|
|
452
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
453
|
+
return Object.entries(value).every(([key, each]) => key === "allowNull" && (each === void 0 || typeof each === "boolean"));
|
|
454
|
+
}
|
|
455
|
+
/** The rule for a switch that leaves an enum's methods out when it's `false`. */
|
|
456
|
+
function methodsSwitch(key) {
|
|
457
|
+
return {
|
|
458
|
+
isWellFormed: (value) => typeof value === "boolean",
|
|
459
|
+
describedAs: key,
|
|
460
|
+
wellFormedAs: "use false to leave them out",
|
|
461
|
+
isGiven: isGivenUnless(true),
|
|
462
|
+
requires: "enum",
|
|
463
|
+
onRetype: "drop"
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
/** `isGiven` for a key whose `off` value (and `undefined`) leaves it as if it weren't given. */
|
|
467
|
+
function isGivenUnless(off) {
|
|
468
|
+
return (value) => value !== void 0 && value !== off;
|
|
469
|
+
}
|
|
470
|
+
/** The rule for a prefix or a suffix: a word around an enum's names in its methods' names. */
|
|
471
|
+
function affixRule(key) {
|
|
472
|
+
return {
|
|
473
|
+
isWellFormed: isAffix,
|
|
474
|
+
describedAs: `a ${key}`,
|
|
475
|
+
wellFormedAs: "use true for the attribute's name, or a word",
|
|
476
|
+
isGiven: isGivenUnless(false),
|
|
477
|
+
requires: "enum",
|
|
478
|
+
onRetype: "drop"
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
/** A prefix or suffix: `true` for the attribute's name, `false` for none, or a word. */
|
|
482
|
+
function isAffix(value) {
|
|
483
|
+
return typeof value === "boolean" || typeof value === "string" && value !== "";
|
|
484
|
+
}
|
|
625
485
|
const entries = Object.entries(rules);
|
|
626
486
|
/** For each key, the keys it conflicts with, whichever of the two declares it. */
|
|
627
487
|
const conflicts = new Map(entries.map(([key]) => [key, []]));
|
|
@@ -629,6 +489,12 @@ for (const [key, { conflictsWith = [] }] of entries) for (const other of conflic
|
|
|
629
489
|
conflicts.get(key).push(other);
|
|
630
490
|
conflicts.get(other).push(key);
|
|
631
491
|
}
|
|
492
|
+
/** An enum's keys: `enum`, and those it means nothing without (`prefix`, `scopes`, …). */
|
|
493
|
+
const enumKeys = new Set(entries.filter(([key, rule]) => key === "enum" || rule.requires === "enum").map(([key]) => key));
|
|
494
|
+
/** A spec without its enum and the keys that go with one (#64). */
|
|
495
|
+
function withoutEnum(spec) {
|
|
496
|
+
return Object.fromEntries(Object.entries(spec).filter(([key]) => !enumKeys.has(key)));
|
|
497
|
+
}
|
|
632
498
|
/** The keys an override may hold, as a message lists them: `type, null, default, …`. */
|
|
633
499
|
const overridableKeyNames = entries.filter(([, rule]) => rule.overridable !== false).map(([key]) => key).join(", ");
|
|
634
500
|
/** The value of a key if it's given, else `undefined`. */
|
|
@@ -636,6 +502,10 @@ function givenValue(spec, key) {
|
|
|
636
502
|
const value = spec[key];
|
|
637
503
|
return (rules[key].isGiven ?? ((each) => each !== void 0))(value) ? value : void 0;
|
|
638
504
|
}
|
|
505
|
+
/** How a spec's type reads in a message: `"integer"`, or `a custom type` (#20). */
|
|
506
|
+
function typeNamed(type) {
|
|
507
|
+
return isAttributeType(type) ? `"${type}"` : "a custom type";
|
|
508
|
+
}
|
|
639
509
|
/** How a key reads in a message. */
|
|
640
510
|
const readsAs = (key) => rules[key].describedAs ?? key;
|
|
641
511
|
/** Whether `value` is an object holding only spec keys an override may change, each well formed or `undefined`. */
|
|
@@ -659,23 +529,40 @@ function shown$1(value) {
|
|
|
659
529
|
return String(value);
|
|
660
530
|
}
|
|
661
531
|
}
|
|
532
|
+
/** The problem with a given key's shape, past the types, or with it given without the key it needs. */
|
|
533
|
+
function shapeProblem(where, spec, key) {
|
|
534
|
+
const { requires, isWellFormed, wellFormedAs } = rules[key];
|
|
535
|
+
const value = givenValue(spec, key);
|
|
536
|
+
if (wellFormedAs !== void 0 && !isWellFormed(value)) return `${where} has ${readsAs(key)} ${shown$1(value)}; ${wellFormedAs}`;
|
|
537
|
+
if (requires !== void 0 && givenValue(spec, requires) === void 0) return `${where} has ${readsAs(key)} but no ${requires}; give it ${readsAs(requires)}, or remove ${readsAs(key)}`;
|
|
538
|
+
}
|
|
662
539
|
/** The problem with a given key's value, or with its attribute's type. */
|
|
663
540
|
function valueProblem(where, spec, key) {
|
|
664
|
-
const { allowedValues, onlyFor } = rules[key];
|
|
541
|
+
const { allowedValues, onlyFor, problemFor } = rules[key];
|
|
665
542
|
const value = givenValue(spec, key);
|
|
666
543
|
if (allowedValues !== void 0 && !allowedValues.includes(value)) {
|
|
667
544
|
const names = allowedValues.map((each) => `"${each}"`).join(" or ");
|
|
668
545
|
return `${where} has ${key} ${shown$1(value)}; use ${names}`;
|
|
669
546
|
}
|
|
670
|
-
|
|
547
|
+
const { type } = spec;
|
|
548
|
+
if (onlyFor !== void 0 && !(isAttributeType(type) && onlyFor.types.includes(type))) return `${where} is ${typeNamed(type)}, so it can't have ${readsAs(key)}: ${onlyFor.because}`;
|
|
549
|
+
const problem = isAttributeType(type) ? problemFor?.(value, type) : void 0;
|
|
550
|
+
return problem === void 0 ? void 0 : `${where}${problem}`;
|
|
671
551
|
}
|
|
672
552
|
/** Why a spec can't be as it is, or undefined if it can. `where` names it (`User.id`). */
|
|
673
553
|
function specProblem(where, spec) {
|
|
554
|
+
if (!rules.type.isWellFormed(spec.type)) return `${where} has type ${shown$1(spec.type)}; use a type's name (${typeNameList}), or a type defineType made`;
|
|
674
555
|
for (const [key] of entries) {
|
|
675
556
|
if (givenValue(spec, key) === void 0) continue;
|
|
676
|
-
const problem = conflictProblem(where, spec, key) ?? valueProblem(where, spec, key);
|
|
557
|
+
const problem = conflictProblem(where, spec, key) ?? shapeProblem(where, spec, key) ?? valueProblem(where, spec, key);
|
|
677
558
|
if (problem !== void 0) return problem;
|
|
678
559
|
}
|
|
560
|
+
return decimalDigitsProblem(where, spec);
|
|
561
|
+
}
|
|
562
|
+
/** A precision and scale no `NUMERIC(p, s)` can have (#398). */
|
|
563
|
+
function decimalDigitsProblem(where, spec) {
|
|
564
|
+
const problem = digitsProblem(spec);
|
|
565
|
+
return problem === void 0 ? void 0 : `${where} has ${problem}`;
|
|
679
566
|
}
|
|
680
567
|
/**
|
|
681
568
|
* `base` with `override` applied. A key `override` gives replaces one it conflicts with, and a new
|
|
@@ -694,24 +581,77 @@ function applyOverride(base, override) {
|
|
|
694
581
|
...given
|
|
695
582
|
};
|
|
696
583
|
}
|
|
697
|
-
/** The keys of `spec` that go into its attribute's definition as given:
|
|
584
|
+
/** The keys of `spec` that go into its attribute's definition as given: all but its type, nullability and column. */
|
|
698
585
|
function copiedKeys(spec) {
|
|
699
586
|
const copied = entries.filter(([key, rule]) => rule.copiedToDefinition !== false && givenValue(spec, key) !== void 0).map(([key]) => [key, spec[key]]);
|
|
700
587
|
return Object.fromEntries(copied);
|
|
701
588
|
}
|
|
702
|
-
|
|
703
|
-
|
|
589
|
+
// src/custom-types.ts
|
|
590
|
+
/** Every type `defineType` made, so a spec can't pass off another object as one. */
|
|
591
|
+
const defined = /* @__PURE__ */ new WeakSet();
|
|
592
|
+
/**
|
|
593
|
+
* Defines an attribute type, used in a spec as a type name is: `price: money`, or
|
|
594
|
+
* `{ type: money, null: false }`. Its values are kept as `storedAs` keeps its own, so they're
|
|
595
|
+
* read strictly, compared and ordered as that type's are.
|
|
596
|
+
*/
|
|
597
|
+
function defineType(type) {
|
|
598
|
+
requireWellFormed(type);
|
|
599
|
+
const made = Object.freeze({
|
|
600
|
+
storedAs: type.storedAs,
|
|
601
|
+
cast: (input) => type.cast(input),
|
|
602
|
+
serialize: (value) => type.serialize(value),
|
|
603
|
+
deserialize: (stored) => type.deserialize(stored)
|
|
604
|
+
});
|
|
605
|
+
defined.add(made);
|
|
606
|
+
return made;
|
|
607
|
+
}
|
|
608
|
+
/** The functions a type needs, each checked when it's made. */
|
|
609
|
+
const functionNames = [
|
|
610
|
+
"cast",
|
|
611
|
+
"serialize",
|
|
612
|
+
"deserialize"
|
|
613
|
+
];
|
|
614
|
+
/**
|
|
615
|
+
* Throws `TypeError` for a type that couldn't work, past the types (plain JavaScript, or a cast):
|
|
616
|
+
* a `storedAs` that isn't a built-in type's name, or a function it lacks.
|
|
617
|
+
*/
|
|
618
|
+
function requireWellFormed(type) {
|
|
619
|
+
if (!isAttributeType(type.storedAs)) throw new TypeError(`defineType: storedAs ${JSON.stringify(type.storedAs)} isn't a type's name; use ${attributeTypeNames}`);
|
|
620
|
+
const missing = functionNames.find((name) => typeof type[name] !== "function");
|
|
621
|
+
if (missing !== void 0) throw new TypeError(`defineType: ${missing} isn't a function`);
|
|
622
|
+
}
|
|
623
|
+
/** Whether `value` is a type `defineType` made. */
|
|
624
|
+
function isCustomType(value) {
|
|
625
|
+
return typeof value === "object" && value !== null && defined.has(value);
|
|
626
|
+
}
|
|
627
|
+
// src/metadata.ts
|
|
628
|
+
/** A spec written out: a type alone (a name, or a custom type) as `{ type }`. */
|
|
629
|
+
function specObjectOf(spec) {
|
|
630
|
+
return typeof spec === "string" || isCustomType(spec) ? { type: spec } : spec;
|
|
631
|
+
}
|
|
704
632
|
/** Resolves an attribute's spec into its type, column and default. */
|
|
705
633
|
function define(name, spec) {
|
|
706
|
-
|
|
634
|
+
if (typeof spec === "string") return {
|
|
707
635
|
type: spec,
|
|
708
636
|
column: underscore(name)
|
|
709
|
-
}
|
|
710
|
-
|
|
637
|
+
};
|
|
638
|
+
if (isCustomType(spec)) return {
|
|
639
|
+
...resolvedType(spec),
|
|
640
|
+
column: underscore(name)
|
|
641
|
+
};
|
|
642
|
+
return {
|
|
643
|
+
...resolvedType(spec.type),
|
|
711
644
|
column: spec.column ?? underscore(name),
|
|
712
645
|
...copiedKeys(spec)
|
|
713
646
|
};
|
|
714
647
|
}
|
|
648
|
+
/** A spec's type as a definition holds it: a custom type as the type it's stored as, and itself. */
|
|
649
|
+
function resolvedType(type) {
|
|
650
|
+
return isCustomType(type) ? {
|
|
651
|
+
type: type.storedAs,
|
|
652
|
+
customType: type
|
|
653
|
+
} : { type };
|
|
654
|
+
}
|
|
715
655
|
/** Looks up a declared attribute; throws `UnknownAttribute` for any other name. */
|
|
716
656
|
function attributeOf(model, name) {
|
|
717
657
|
const attribute = model.attributeDefinitions.get(name);
|
|
@@ -737,8 +677,62 @@ function initialValues(model, given = {}) {
|
|
|
737
677
|
function hasInitialValue(definition) {
|
|
738
678
|
return definition.generateId === true || definition.default !== void 0;
|
|
739
679
|
}
|
|
740
|
-
|
|
741
|
-
|
|
680
|
+
// src/filtering.ts
|
|
681
|
+
/** What a listener sees in place of a filtered attribute's value (#83). */
|
|
682
|
+
const FILTERED = "[FILTERED]";
|
|
683
|
+
/**
|
|
684
|
+
* Rails' default `filter_parameters` for a new app: an attribute whose snake_case name holds
|
|
685
|
+
* one of these, in any case, is filtered (`passwordDigest`, `apiKey`, `resetToken`, `email`).
|
|
686
|
+
*/
|
|
687
|
+
const defaultFilterAttributes = [
|
|
688
|
+
"passw",
|
|
689
|
+
"email",
|
|
690
|
+
"secret",
|
|
691
|
+
"token",
|
|
692
|
+
"_key",
|
|
693
|
+
"crypt",
|
|
694
|
+
"salt",
|
|
695
|
+
"certificate",
|
|
696
|
+
"otp",
|
|
697
|
+
"ssn",
|
|
698
|
+
"cvv",
|
|
699
|
+
"cvc"
|
|
700
|
+
];
|
|
701
|
+
/**
|
|
702
|
+
* Whether `attribute`'s values are hidden from listeners: its snake_case name holds a string
|
|
703
|
+
* entry lowercased, or read in snake_case (`"apiKey"` as `api_key`, #397), or a RegExp entry
|
|
704
|
+
* matches the attribute or its snake_case name.
|
|
705
|
+
*/
|
|
706
|
+
function isFiltered(model, attribute) {
|
|
707
|
+
const name = underscore(attribute);
|
|
708
|
+
return model.filterAttributes.some((entry) => typeof entry === "string" ? name.includes(entry.toLowerCase()) || name.includes(underscore(entry)) : attribute.search(entry) !== -1 || name.search(entry) !== -1);
|
|
709
|
+
}
|
|
710
|
+
/** The values of `attributes` that `model` filters, so a message can tell not to show them. */
|
|
711
|
+
function filteredValues(model, attributes) {
|
|
712
|
+
return Object.entries(attributes).filter(([name]) => isFiltered(model, name)).map(([, value]) => value);
|
|
713
|
+
}
|
|
714
|
+
/** A bound value D1 gets as `value`, and listeners see as `shown`. */
|
|
715
|
+
var Filtered = class {
|
|
716
|
+
value;
|
|
717
|
+
shown;
|
|
718
|
+
constructor(value, shown = FILTERED) {
|
|
719
|
+
this.value = value;
|
|
720
|
+
this.shown = shown;
|
|
721
|
+
}
|
|
722
|
+
};
|
|
723
|
+
/** A primary key as an error shows it: "[FILTERED]" when the key is a filtered attribute. */
|
|
724
|
+
function shownKey(model, key) {
|
|
725
|
+
return isFiltered(model, model.primaryKey) ? FILTERED : String(key);
|
|
726
|
+
}
|
|
727
|
+
/** The value D1 binds. */
|
|
728
|
+
function boundValue(param) {
|
|
729
|
+
return param instanceof Filtered ? param.value : param;
|
|
730
|
+
}
|
|
731
|
+
/** The value listeners see. */
|
|
732
|
+
function shownValue$1(param) {
|
|
733
|
+
return param instanceof Filtered ? param.shown : param;
|
|
734
|
+
}
|
|
735
|
+
// src/attribute.ts
|
|
742
736
|
/** What `condition()` and `conditionCell()` give for a value that can't match anything. */
|
|
743
737
|
const noMatch = uncastable;
|
|
744
738
|
/**
|
|
@@ -762,6 +756,14 @@ var Attribute = class {
|
|
|
762
756
|
get isText() {
|
|
763
757
|
return this.#definition.type === "string";
|
|
764
758
|
}
|
|
759
|
+
/** Whether it's a `binary` attribute, whose cells are bytes, which JSON can't hold (#20). */
|
|
760
|
+
get isBinary() {
|
|
761
|
+
return this.#definition.type === "binary";
|
|
762
|
+
}
|
|
763
|
+
/** Whether it's a `json` attribute, whose stored text is JSON itself. */
|
|
764
|
+
get isJson() {
|
|
765
|
+
return this.#definition.type === "json";
|
|
766
|
+
}
|
|
765
767
|
/**
|
|
766
768
|
* An assigned value (a setter, `build`, `update`, `insert`, `permit`) as the attribute's type:
|
|
767
769
|
* only what's unambiguous for it (#81). `undefined` throws, as it would store NULL silently;
|
|
@@ -770,7 +772,14 @@ var Attribute = class {
|
|
|
770
772
|
*/
|
|
771
773
|
cast(value) {
|
|
772
774
|
requireDefined(this.#model, this.name, value);
|
|
773
|
-
|
|
775
|
+
const cast = this.#convertOrRefuse(value, () => castValue(this.#definition, value));
|
|
776
|
+
if (cast === uncastable && this.#isValidatedEnum()) return value;
|
|
777
|
+
return this.#orRefuse(cast, value);
|
|
778
|
+
}
|
|
779
|
+
/** Whether it's an enum declared `validate: true`, which keeps an unknown value it's given. */
|
|
780
|
+
#isValidatedEnum() {
|
|
781
|
+
const { enum: values, validate = false } = this.#definition;
|
|
782
|
+
return values !== void 0 && validate !== false;
|
|
774
783
|
}
|
|
775
784
|
/**
|
|
776
785
|
* A key copied from another record or inherited from a condition: cast as a condition's, but
|
|
@@ -778,7 +787,7 @@ var Attribute = class {
|
|
|
778
787
|
*/
|
|
779
788
|
key(value, association) {
|
|
780
789
|
requireDefined(this.#model, this.name, value);
|
|
781
|
-
return this.#orRefuse(
|
|
790
|
+
return this.#orRefuse(castKey(this.#definition, value), value, association);
|
|
782
791
|
}
|
|
783
792
|
/**
|
|
784
793
|
* A condition's value (`where`, `find`, a preload) as the attribute's type, or `noMatch`: a
|
|
@@ -802,6 +811,7 @@ var Attribute = class {
|
|
|
802
811
|
try {
|
|
803
812
|
stored = writeValue(this.#definition, value);
|
|
804
813
|
} catch (error) {
|
|
814
|
+
if (this.#definition.customType !== void 0) throw this.#refusal(value, void 0, error);
|
|
805
815
|
if (this.#definition.type !== "json") throw error;
|
|
806
816
|
throw this.#refusal(value);
|
|
807
817
|
}
|
|
@@ -818,7 +828,7 @@ var Attribute = class {
|
|
|
818
828
|
* attribute, with the cell hidden if it's filtered, not the parser's own error (#73, #146).
|
|
819
829
|
*/
|
|
820
830
|
read(cell) {
|
|
821
|
-
const value = readValue(this.#definition, cell);
|
|
831
|
+
const value = this.#convertOrRefuse(cell, () => readValue(this.#definition, cell));
|
|
822
832
|
if (value === uncastable) throw this.#refusal(cell);
|
|
823
833
|
return value;
|
|
824
834
|
}
|
|
@@ -826,9 +836,24 @@ var Attribute = class {
|
|
|
826
836
|
copy(value) {
|
|
827
837
|
return this.read(this.write(value));
|
|
828
838
|
}
|
|
829
|
-
/**
|
|
830
|
-
same(
|
|
831
|
-
|
|
839
|
+
/**
|
|
840
|
+
* Whether two values are the same as stored (dates by time, json and bytes by content). Each is
|
|
841
|
+
* cast as a condition's value first, so `isAttributeChanged`'s `from` and `to` compare as
|
|
842
|
+
* Rails' do, and one that can't be cast is the same as nothing (#20).
|
|
843
|
+
*/
|
|
844
|
+
isSame(a, b) {
|
|
845
|
+
const [x, y] = [this.#comparable(a), this.#comparable(b)];
|
|
846
|
+
if (x === noMatch || y === noMatch) return false;
|
|
847
|
+
return isSameCell(writeValue(this.#definition, x), writeValue(this.#definition, y));
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* A value to compare, cast as a condition's: `null` stays `null`, and a validated enum's
|
|
851
|
+
* unknown value, which a record may hold, stays as it is (#340).
|
|
852
|
+
*/
|
|
853
|
+
#comparable(value) {
|
|
854
|
+
if (value === null || value === void 0) return value ?? null;
|
|
855
|
+
const cast = this.condition(value);
|
|
856
|
+
return cast === noMatch && this.#isValidatedEnum() ? value : cast;
|
|
832
857
|
}
|
|
833
858
|
/** An assigned value, cast and written, bound hidden from `onQuery` if filtered (#83). */
|
|
834
859
|
bind(params, value) {
|
|
@@ -840,29 +865,47 @@ var Attribute = class {
|
|
|
840
865
|
* time, since `filterAttributes` is a static a Model may set after this was resolved.
|
|
841
866
|
*/
|
|
842
867
|
bindCells(params, ...cells) {
|
|
843
|
-
const hidden = this.#
|
|
868
|
+
const hidden = this.#isHidden();
|
|
844
869
|
for (const cell of cells) params.push(hidden ? new Filtered(cell) : cell);
|
|
845
870
|
}
|
|
846
871
|
#orRefuse(cast, value, association) {
|
|
847
872
|
if (cast === uncastable) throw this.#refusal(value, association);
|
|
848
873
|
return cast;
|
|
849
874
|
}
|
|
875
|
+
/**
|
|
876
|
+
* `convert`'s result. What a custom type's own function throws for `value` is refused as any
|
|
877
|
+
* value its type can't hold, with the type's error as the cause (#20).
|
|
878
|
+
*/
|
|
879
|
+
#convertOrRefuse(value, convert) {
|
|
880
|
+
try {
|
|
881
|
+
return convert();
|
|
882
|
+
} catch (error) {
|
|
883
|
+
if (this.#definition.customType === void 0) throw error;
|
|
884
|
+
throw this.#refusal(value, void 0, error);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
850
887
|
/** Whether the attribute's values are hidden from listeners and errors (#83). */
|
|
851
|
-
#
|
|
888
|
+
#isHidden() {
|
|
852
889
|
return isFiltered(this.#model, this.name);
|
|
853
890
|
}
|
|
854
891
|
/**
|
|
855
892
|
* "Sample: "no" isn't a boolean for "enabled"", the value hidden for a filtered attribute. Also
|
|
856
893
|
* what a stored value that can't be read says: a Unix time that isn't one (#73), or a json
|
|
857
|
-
* cell that isn't JSON (#146).
|
|
894
|
+
* cell that isn't JSON (#146). A custom type's own error is its cause, unless the attribute is
|
|
895
|
+
* filtered: the error may show the value (#20).
|
|
858
896
|
*/
|
|
859
|
-
#refusal(value, association) {
|
|
860
|
-
const
|
|
861
|
-
const
|
|
862
|
-
const article = /^[aeiou]/.test(noun) ? "an" : "a";
|
|
863
|
-
const text = this.#hidden() ? FILTERED : shown(value);
|
|
897
|
+
#refusal(value, association, cause) {
|
|
898
|
+
const hidden = this.#isHidden();
|
|
899
|
+
const text = hidden ? FILTERED : shown(value);
|
|
864
900
|
const from = association === void 0 ? "" : `, the key of ${association}`;
|
|
865
|
-
return
|
|
901
|
+
return new TypeError(`${this.#model.name}: ${text} isn't ${this.#described()} for "${this.name}"${from}`, hidden || cause === void 0 ? void 0 : { cause });
|
|
902
|
+
}
|
|
903
|
+
/** What a value of the attribute is, as a refusal says it: `a boolean`, `one of "draft", "published"`. */
|
|
904
|
+
#described() {
|
|
905
|
+
const { type, enum: values, customType } = this.#definition;
|
|
906
|
+
if (values !== void 0) return `one of ${listedNames(values)}`;
|
|
907
|
+
if (customType !== void 0) return "a valid value";
|
|
908
|
+
return valueNames[type] ?? withArticle(type);
|
|
866
909
|
}
|
|
867
910
|
};
|
|
868
911
|
const resolved = /* @__PURE__ */ new WeakMap();
|
|
@@ -884,19 +927,6 @@ function attributeFor(model, name) {
|
|
|
884
927
|
return attribute;
|
|
885
928
|
}
|
|
886
929
|
/**
|
|
887
|
-
* Rows of `names`' values, assigned, as one JSON value the dialect reads them from; listeners see
|
|
888
|
-
* a filtered attribute's column as "[FILTERED]" in every row.
|
|
889
|
-
*/
|
|
890
|
-
function storedRows(model, names, rows) {
|
|
891
|
-
const attributes = names.map((name) => attributeFor(model, name));
|
|
892
|
-
const stored = rows.map((row) => row.map((value, index) => attributes[index].store(value)));
|
|
893
|
-
const json = JSON.stringify(stored);
|
|
894
|
-
const filtered = names.map((attribute) => isFiltered(model, attribute));
|
|
895
|
-
if (!filtered.includes(true)) return json;
|
|
896
|
-
const shown = stored.map((row) => row.map((value, index) => filtered[index] ? FILTERED : value));
|
|
897
|
-
return new Filtered(json, JSON.stringify(shown));
|
|
898
|
-
}
|
|
899
|
-
/**
|
|
900
930
|
* The values a record built from a Relation inherits from its conditions, cast as keys are: a
|
|
901
931
|
* hasMany's foreign key names its association (`link`) when it can't be cast.
|
|
902
932
|
*/
|
|
@@ -906,16 +936,25 @@ function castInherited(model, inherited, link) {
|
|
|
906
936
|
return [attribute, attributeFor(model, attribute).key(value, association)];
|
|
907
937
|
}));
|
|
908
938
|
}
|
|
939
|
+
/** A word with `a` or `an` before it, as a message reads it: `an integer`, `a string`. */
|
|
940
|
+
function withArticle(word) {
|
|
941
|
+
return `${/^[aeiou]/.test(word) ? "an" : "a"} ${word}`;
|
|
942
|
+
}
|
|
909
943
|
/** How much of a value an error shows: it came from outside, and errors are often logged. */
|
|
910
944
|
const SHOWN_LENGTH = 60;
|
|
911
|
-
/** What an attribute type is called in a refusal, where its name isn't it. */
|
|
912
|
-
const
|
|
945
|
+
/** What a value of an attribute type is called in a refusal, where `a`/`an` and its name isn't it. */
|
|
946
|
+
const valueNames = {
|
|
947
|
+
json: "a JSON value",
|
|
948
|
+
binary: "binary data"
|
|
949
|
+
};
|
|
913
950
|
/** A value as an error shows it: JSON where it has one, numbers as written, and at most 60 characters. */
|
|
914
951
|
function shown(value) {
|
|
915
952
|
const text = textOf(value);
|
|
916
953
|
return text.length > SHOWN_LENGTH ? `${text.slice(0, SHOWN_LENGTH)}…` : text;
|
|
917
954
|
}
|
|
918
955
|
function textOf(value) {
|
|
956
|
+
if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return `<${value.constructor.name} of ${value.byteLength} bytes>`;
|
|
957
|
+
if (value instanceof Blob) return `<${value.constructor.name} of ${value.size} bytes>`;
|
|
919
958
|
if (typeof value === "number" || isInvalidDate(value)) return String(value);
|
|
920
959
|
try {
|
|
921
960
|
return JSON.stringify(value) ?? String(value);
|
|
@@ -931,8 +970,7 @@ function plainText(value) {
|
|
|
931
970
|
return Object.prototype.toString.call(value);
|
|
932
971
|
}
|
|
933
972
|
}
|
|
934
|
-
|
|
935
|
-
//#region src/declarations.ts
|
|
973
|
+
// src/declarations.ts
|
|
936
974
|
/**
|
|
937
975
|
* Per-Model declarations (validations, callbacks, …), keyed by Model class. A subclass starts
|
|
938
976
|
* from a copy of its parent's list, so declaring on it never changes the parent.
|
|
@@ -990,13 +1028,16 @@ function listsOf(lists, model) {
|
|
|
990
1028
|
lists.set(model, found);
|
|
991
1029
|
return found;
|
|
992
1030
|
}
|
|
993
|
-
|
|
994
|
-
//#region src/error-messages.ts
|
|
1031
|
+
// src/error-messages.ts
|
|
995
1032
|
/** @internal Rails' English messages, used where no class has its own (listed in the guide). */
|
|
996
1033
|
const builtInMessages = {
|
|
997
1034
|
blank: "can't be blank",
|
|
1035
|
+
present: "must be blank",
|
|
998
1036
|
invalid: "is invalid",
|
|
1037
|
+
required: "must exist",
|
|
999
1038
|
inclusion: "is not included in the list",
|
|
1039
|
+
exclusion: "is reserved",
|
|
1040
|
+
accepted: "must be accepted",
|
|
1000
1041
|
taken: "has already been taken",
|
|
1001
1042
|
tooShort: {
|
|
1002
1043
|
one: "is too short (minimum is 1 character)",
|
|
@@ -1016,6 +1057,8 @@ const builtInMessages = {
|
|
|
1016
1057
|
greaterThanOrEqualTo: "must be greater than or equal to %{count}",
|
|
1017
1058
|
lessThan: "must be less than %{count}",
|
|
1018
1059
|
lessThanOrEqualTo: "must be less than or equal to %{count}",
|
|
1060
|
+
equalTo: "must be equal to %{count}",
|
|
1061
|
+
otherThan: "must be other than %{count}",
|
|
1019
1062
|
restrictDependentDestroy: {
|
|
1020
1063
|
hasOne: "Cannot delete record because a dependent %{record} exists",
|
|
1021
1064
|
hasMany: "Cannot delete record because dependent %{record} exist"
|
|
@@ -1065,7 +1108,7 @@ function messageText(template, entry) {
|
|
|
1065
1108
|
}
|
|
1066
1109
|
/** "createdAt" → "Created at" */
|
|
1067
1110
|
function inWords(name) {
|
|
1068
|
-
const words = underscore(name).replaceAll(
|
|
1111
|
+
const words = underscore(name).replaceAll(/[_.]/g, " ");
|
|
1069
1112
|
return words.charAt(0).toUpperCase() + words.slice(1);
|
|
1070
1113
|
}
|
|
1071
1114
|
/** An attribute's name as messages show it: a class's `humanAttributeNames`, or "Created at". */
|
|
@@ -1089,7 +1132,7 @@ function messageOf(source, entry) {
|
|
|
1089
1132
|
if (text === void 0) throw missingMessage(model, entry);
|
|
1090
1133
|
return text.replace(/%\{(\w+)\}/g, (placeholder, name) => {
|
|
1091
1134
|
if (name === "attribute") return humanAttributeName(model, entry.attribute);
|
|
1092
|
-
if (name === "model") return inWords(model.
|
|
1135
|
+
if (name === "model") return inWords(model.modelName);
|
|
1093
1136
|
if (name === "value") return shownValue(source, entry.attribute);
|
|
1094
1137
|
return String(ownValue(entry.values, name) ?? placeholder);
|
|
1095
1138
|
});
|
|
@@ -1111,8 +1154,7 @@ function attributesNamedInMessages(model) {
|
|
|
1111
1154
|
names: values.flatMap((value) => Object.keys(value))
|
|
1112
1155
|
}))];
|
|
1113
1156
|
}
|
|
1114
|
-
|
|
1115
|
-
//#region src/inspect-support.ts
|
|
1157
|
+
// src/inspect-support.ts
|
|
1116
1158
|
/** Node and workerd call a value's inspector under this registered symbol. */
|
|
1117
1159
|
const inspectCustom = Symbol.for("nodejs.util.inspect.custom");
|
|
1118
1160
|
/** Text in the color of a special value, or plain when colors are off. */
|
|
@@ -1140,12 +1182,13 @@ function printed(label, name, body, { depth, options, inspect }) {
|
|
|
1140
1182
|
depth
|
|
1141
1183
|
})}`;
|
|
1142
1184
|
}
|
|
1143
|
-
|
|
1144
|
-
//#region src/errors-collection.ts
|
|
1185
|
+
// src/errors-collection.ts
|
|
1145
1186
|
/** @internal The library's key for emptying an errors collection. */
|
|
1146
1187
|
const clearErrors = Symbol("clearErrors");
|
|
1147
1188
|
/** @internal The library's key for adding a failure it found, with an optional message to use as it is. */
|
|
1148
1189
|
const addFailure = Symbol("addFailure");
|
|
1190
|
+
/** @internal The library's key for a failure's full message, without adding it (`strict`). */
|
|
1191
|
+
const fullMessageOf = Symbol("fullMessageOf");
|
|
1149
1192
|
/** A record's validation errors: `record.errors`. Cleared at the start of each validation run. */
|
|
1150
1193
|
var Errors = class {
|
|
1151
1194
|
#entries = [];
|
|
@@ -1180,11 +1223,12 @@ var Errors = class {
|
|
|
1180
1223
|
}
|
|
1181
1224
|
/** Every message with its attribute's human name first: "Email can't be blank". */
|
|
1182
1225
|
fullMessages() {
|
|
1183
|
-
return this.#entries.map((entry) =>
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1226
|
+
return this.#entries.map((entry) => this.#fullMessage(entry));
|
|
1227
|
+
}
|
|
1228
|
+
#fullMessage(entry) {
|
|
1229
|
+
const message = messageOf(this.#source, entry);
|
|
1230
|
+
if (entry.attribute === "base") return message;
|
|
1231
|
+
return `${humanAttributeName(this.#source.model, entry.attribute)} ${message}`;
|
|
1188
1232
|
}
|
|
1189
1233
|
/** Every error as `{ attribute, type, message }`, with its `values` when it has some (copies). */
|
|
1190
1234
|
toArray() {
|
|
@@ -1225,13 +1269,20 @@ var Errors = class {
|
|
|
1225
1269
|
this.#entries.push(entry);
|
|
1226
1270
|
return messageOf(this.#source, entry);
|
|
1227
1271
|
}
|
|
1272
|
+
/** @internal A failure's full message, as `fullMessages()` would give it, without adding it. */
|
|
1273
|
+
[fullMessageOf](attribute, { values = {}, ...failure }) {
|
|
1274
|
+
return this.#fullMessage({
|
|
1275
|
+
attribute,
|
|
1276
|
+
values,
|
|
1277
|
+
...failure
|
|
1278
|
+
});
|
|
1279
|
+
}
|
|
1228
1280
|
/** @internal Called at the start of each validation run. */
|
|
1229
1281
|
[clearErrors]() {
|
|
1230
1282
|
this.#entries = [];
|
|
1231
1283
|
}
|
|
1232
1284
|
};
|
|
1233
|
-
|
|
1234
|
-
//#region src/loaded-associations.ts
|
|
1285
|
+
// src/loaded-associations.ts
|
|
1235
1286
|
/**
|
|
1236
1287
|
* The associations one record has loaded (preloaded, read, or set by a write): a record, an
|
|
1237
1288
|
* array of records, or null. Each stays loaded while the owner's attribute still holds the key
|
|
@@ -1250,7 +1301,7 @@ var LoadedAssociations = class {
|
|
|
1250
1301
|
/** The loaded association, if it was loaded for the key the owner holds now. */
|
|
1251
1302
|
get(name) {
|
|
1252
1303
|
const entry = this.#entries.get(name);
|
|
1253
|
-
if (entry === void 0 || !
|
|
1304
|
+
if (entry === void 0 || !isSameKey(this.#key(entry.attribute), entry.key)) return void 0;
|
|
1254
1305
|
return entry;
|
|
1255
1306
|
}
|
|
1256
1307
|
/**
|
|
@@ -1267,10 +1318,10 @@ var LoadedAssociations = class {
|
|
|
1267
1318
|
}
|
|
1268
1319
|
/**
|
|
1269
1320
|
* Starts a load of the association, before its query is sent, for the key its query was built
|
|
1270
|
-
* for: the function it returns keeps the loaded value only if nothing changed the association
|
|
1321
|
+
* for (the attributes' values now, unless it's given): the function it returns keeps the loaded value only if nothing changed the association
|
|
1271
1322
|
* meanwhile (#181).
|
|
1272
1323
|
*/
|
|
1273
|
-
startLoad(name, attribute, key) {
|
|
1324
|
+
startLoad(name, attribute, key = this.#key(attribute)) {
|
|
1274
1325
|
const generation = this.#generation(name);
|
|
1275
1326
|
return (value) => {
|
|
1276
1327
|
if (this.#generation(name) === generation) this.#entries.set(name, {
|
|
@@ -1291,6 +1342,7 @@ var LoadedAssociations = class {
|
|
|
1291
1342
|
this.#allLoadsDiscarded += 1;
|
|
1292
1343
|
}
|
|
1293
1344
|
#key(attribute) {
|
|
1345
|
+
if (typeof attribute !== "string") return attribute.map((each) => this.#keyOf(each) ?? null);
|
|
1294
1346
|
return this.#keyOf(attribute) ?? null;
|
|
1295
1347
|
}
|
|
1296
1348
|
#discardPendingLoads(name) {
|
|
@@ -1304,11 +1356,16 @@ var LoadedAssociations = class {
|
|
|
1304
1356
|
return this.#allLoadsDiscarded + (this.#loadsDiscarded.get(name) ?? 0);
|
|
1305
1357
|
}
|
|
1306
1358
|
};
|
|
1307
|
-
|
|
1308
|
-
|
|
1359
|
+
/** Whether two keys are the same: one value, or each of a list's (#60). */
|
|
1360
|
+
function isSameKey(now, loaded) {
|
|
1361
|
+
if (!Array.isArray(now) || !Array.isArray(loaded)) return Object.is(now, loaded);
|
|
1362
|
+
return now.every((each, index) => Object.is(each, loaded[index]));
|
|
1363
|
+
}
|
|
1364
|
+
// src/pending-autosaves.ts
|
|
1309
1365
|
/**
|
|
1310
|
-
* The
|
|
1311
|
-
* associations, after it
|
|
1366
|
+
* The records saving one record may also save: those built through its hasMany and hasOne
|
|
1367
|
+
* associations or pushed onto a hasMany, after it (`autosavesOf` says which), and the new ones
|
|
1368
|
+
* its belongsTo associations point at, before it.
|
|
1312
1369
|
*/
|
|
1313
1370
|
var PendingAutosaves = class {
|
|
1314
1371
|
#built = /* @__PURE__ */ new Map();
|
|
@@ -1317,6 +1374,15 @@ var PendingAutosaves = class {
|
|
|
1317
1374
|
addBuilt(name, record) {
|
|
1318
1375
|
this.#built.set(name, [...this.#built.get(name) ?? [], record]);
|
|
1319
1376
|
}
|
|
1377
|
+
/** Takes `records` out of those built through the association (`delete`, `destroy`). */
|
|
1378
|
+
removeBuilt(name, records) {
|
|
1379
|
+
const kept = this.built(name).filter((record) => !records.includes(record));
|
|
1380
|
+
this.#built.set(name, kept);
|
|
1381
|
+
}
|
|
1382
|
+
/** A hasOne's one record to save with this record, replacing any before it. */
|
|
1383
|
+
setBuilt(name, record) {
|
|
1384
|
+
this.#built.set(name, [record]);
|
|
1385
|
+
}
|
|
1320
1386
|
/** The records built through the association, in the order they were built. */
|
|
1321
1387
|
built(name) {
|
|
1322
1388
|
return this.#built.get(name) ?? [];
|
|
@@ -1334,6 +1400,10 @@ var PendingAutosaves = class {
|
|
|
1334
1400
|
allBelongsTo() {
|
|
1335
1401
|
return [...this.#belongsTo];
|
|
1336
1402
|
}
|
|
1403
|
+
/** Whether there are none: saving the record saves no other record with it. */
|
|
1404
|
+
isEmpty() {
|
|
1405
|
+
return [...this.#built.values()].every((records) => records.length === 0) && this.#belongsTo.size === 0;
|
|
1406
|
+
}
|
|
1337
1407
|
/** Forgets what was built through the association or set on it (`reloadAssociation`). */
|
|
1338
1408
|
clear(name) {
|
|
1339
1409
|
this.#built.delete(name);
|
|
@@ -1345,8 +1415,7 @@ var PendingAutosaves = class {
|
|
|
1345
1415
|
this.#belongsTo.clear();
|
|
1346
1416
|
}
|
|
1347
1417
|
};
|
|
1348
|
-
|
|
1349
|
-
//#region src/record-state.ts
|
|
1418
|
+
// src/record-state.ts
|
|
1350
1419
|
/** @internal The hidden slot where a Record keeps its `RecordState`. */
|
|
1351
1420
|
const state = Symbol("state");
|
|
1352
1421
|
/** Each record's link to its database (its `RecordState`), for pinning it to one (#93). */
|
|
@@ -1379,6 +1448,12 @@ var RecordState = class {
|
|
|
1379
1448
|
associations = new LoadedAssociations((attribute) => this.#values[attribute]);
|
|
1380
1449
|
/** The new records saving it also saves, built through or pointed at by its associations. */
|
|
1381
1450
|
autosaves = new PendingAutosaves();
|
|
1451
|
+
/** Destroyed when its owner is saved through an `autosave: true` association (#37). */
|
|
1452
|
+
isMarkedForDestruction = false;
|
|
1453
|
+
/** Whether its last save created it, as Rails' `previously_new_record?` (#351). */
|
|
1454
|
+
isPreviouslyNew = false;
|
|
1455
|
+
/** The contexts it's being validated in, while it is (#51). */
|
|
1456
|
+
validationContexts = [];
|
|
1382
1457
|
constructor(model) {
|
|
1383
1458
|
this.#model = model;
|
|
1384
1459
|
const read = (name) => Object.hasOwn(this.#values, name) ? this.#values[name] : null;
|
|
@@ -1434,7 +1509,7 @@ var RecordState = class {
|
|
|
1434
1509
|
/** A persisted record needs its primary key to be found by; one from `distinct()` has none. */
|
|
1435
1510
|
requireKey(action) {
|
|
1436
1511
|
const { name, primaryKey } = this.#model;
|
|
1437
|
-
if (this.#lifecycle === "persisted" && !this.#
|
|
1512
|
+
if (this.#lifecycle === "persisted" && !this.#isInSnapshot(primaryKey)) throw new MissingAttribute(`${name} record has no primary key loaded (it came from select(...).distinct()); it can't ${action}`);
|
|
1438
1513
|
}
|
|
1439
1514
|
/** An attribute's value; `MissingAttribute` if it wasn't loaded (left out of `select`). */
|
|
1440
1515
|
read(name) {
|
|
@@ -1479,10 +1554,14 @@ var RecordState = class {
|
|
|
1479
1554
|
}
|
|
1480
1555
|
this.assign(attributes);
|
|
1481
1556
|
}
|
|
1482
|
-
/**
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1557
|
+
/**
|
|
1558
|
+
* Points this record at `value` through `association`'s foreign key, keeping it loaded for its
|
|
1559
|
+
* key attributes (a polymorphic belongsTo's type is written before, by its `set`; #60).
|
|
1560
|
+
*/
|
|
1561
|
+
pointAt(association, key, value) {
|
|
1562
|
+
const { name, ownerAttribute, keyAttributes } = association;
|
|
1563
|
+
this.writeKey(ownerAttribute, key, name);
|
|
1564
|
+
this.associations.set(name, keyAttributes, value);
|
|
1486
1565
|
}
|
|
1487
1566
|
/** Forgets an association: what's loaded and its autosaves (`reloadAssociation`). */
|
|
1488
1567
|
resetAssociation(name) {
|
|
@@ -1509,20 +1588,24 @@ var RecordState = class {
|
|
|
1509
1588
|
attributes() {
|
|
1510
1589
|
return { ...this.#values };
|
|
1511
1590
|
}
|
|
1512
|
-
/**
|
|
1591
|
+
/**
|
|
1592
|
+
* A new record's assigned attributes that differ from their initial values (a declared default
|
|
1593
|
+
* or generated id, else null), as Rails' changes run from defaults (#41); or a persisted
|
|
1594
|
+
* one's that differ from the Snapshot. Both compare stored forms.
|
|
1595
|
+
*/
|
|
1513
1596
|
changedNames() {
|
|
1514
|
-
if (this.#lifecycle === "new") return [...this.#assigned];
|
|
1515
|
-
return Object.keys(this.#values).filter((name) => !this.#
|
|
1597
|
+
if (this.#lifecycle === "new") return [...this.#assigned].filter((name) => !isSameCell(this.#storedForm(name), this.#initialOf(name)));
|
|
1598
|
+
return Object.keys(this.#values).filter((name) => !this.#isInSnapshot(name) || !isSameCell(this.#snapshotOf(name), this.#storedForm(name)));
|
|
1516
1599
|
}
|
|
1517
1600
|
/** `{ attribute: [before, after] }`; both are copies, never the record's own objects. */
|
|
1518
1601
|
changes() {
|
|
1519
1602
|
const changes = {};
|
|
1520
|
-
for (const name of this.changedNames()) changes[name] = [this.#
|
|
1603
|
+
for (const name of this.changedNames()) changes[name] = [this.#valueBefore(name), this.#copyOf(name)];
|
|
1521
1604
|
return changes;
|
|
1522
1605
|
}
|
|
1523
1606
|
/** `changes()`, with `undefined` before an attribute the record never loaded (a partial record's). */
|
|
1524
1607
|
changesSinceLoad() {
|
|
1525
|
-
return Object.fromEntries(Object.entries(this.changes()).map(([name, [before, after]]) => [name, [this.#
|
|
1608
|
+
return Object.fromEntries(Object.entries(this.changes()).map(([name, [before, after]]) => [name, [this.#isInSnapshot(name) ? before : void 0, after]]));
|
|
1526
1609
|
}
|
|
1527
1610
|
/** The changes the last successful save wrote (copies). */
|
|
1528
1611
|
savedChanges() {
|
|
@@ -1534,9 +1617,7 @@ var RecordState = class {
|
|
|
1534
1617
|
*/
|
|
1535
1618
|
valueInDatabase(name) {
|
|
1536
1619
|
this.read(name);
|
|
1537
|
-
|
|
1538
|
-
if (this.#inSnapshot(name)) return this.#snapshotValue(name);
|
|
1539
|
-
return this.#initialValues.has(name) ? attribute.read(this.#initialValues.get(name)) : null;
|
|
1620
|
+
return this.#valueBefore(name);
|
|
1540
1621
|
}
|
|
1541
1622
|
/**
|
|
1542
1623
|
* Whether the attribute has an unsaved change, optionally `from` and `to` given values
|
|
@@ -1545,13 +1626,13 @@ var RecordState = class {
|
|
|
1545
1626
|
isAttributeChanged(name, options = {}) {
|
|
1546
1627
|
this.read(name);
|
|
1547
1628
|
if (!this.changedNames().includes(name)) return false;
|
|
1548
|
-
return this.#
|
|
1629
|
+
return this.#isMatching(name, this.valueInDatabase(name), this.#values[name], options);
|
|
1549
1630
|
}
|
|
1550
1631
|
/** Whether the last save changed the attribute, optionally `from` and `to` given values. */
|
|
1551
1632
|
hasSavedChangeTo(name, options = {}) {
|
|
1552
1633
|
this.read(name);
|
|
1553
1634
|
const change = this.#savedChanges[name];
|
|
1554
|
-
return change !== void 0 && this.#
|
|
1635
|
+
return change !== void 0 && this.#isMatching(name, change[0], change[1], options);
|
|
1555
1636
|
}
|
|
1556
1637
|
/** Puts unsaved changes back: to the Snapshot, or to a new record's initial values (or null). */
|
|
1557
1638
|
restore(names = this.changedNames()) {
|
|
@@ -1559,7 +1640,7 @@ var RecordState = class {
|
|
|
1559
1640
|
for (const name of names) {
|
|
1560
1641
|
const attribute = this.#attribute(name);
|
|
1561
1642
|
if (this.#lifecycle !== "new") {
|
|
1562
|
-
if (this.#
|
|
1643
|
+
if (this.#isInSnapshot(name)) this.#values[name] = this.#snapshotValue(name);
|
|
1563
1644
|
} else if (this.#initialValues.has(name)) this.#values[name] = attribute.read(this.#initialValues.get(name));
|
|
1564
1645
|
else {
|
|
1565
1646
|
this.#values[name] = null;
|
|
@@ -1567,8 +1648,8 @@ var RecordState = class {
|
|
|
1567
1648
|
}
|
|
1568
1649
|
}
|
|
1569
1650
|
}
|
|
1570
|
-
#
|
|
1571
|
-
const same = (a, b) => this.#attribute(name).
|
|
1651
|
+
#isMatching(name, before, after, options) {
|
|
1652
|
+
const same = (a, b) => this.#attribute(name).isSame(a, b);
|
|
1572
1653
|
return (!("from" in options) || same(options.from, before)) && (!("to" in options) || same(options.to, after));
|
|
1573
1654
|
}
|
|
1574
1655
|
/** The attributes an insert writes: the assigned ones, so column defaults apply to the rest. */
|
|
@@ -1587,13 +1668,23 @@ var RecordState = class {
|
|
|
1587
1668
|
get storedKeyValue() {
|
|
1588
1669
|
return this.#attribute(this.#model.primaryKey).read(this.storedKey);
|
|
1589
1670
|
}
|
|
1590
|
-
/**
|
|
1671
|
+
/**
|
|
1672
|
+
* After an insert: load what D1 stored. `savedChanges` is the changes the insert wrote, and
|
|
1673
|
+
* what the write or the database filled in (a generated key, timestamps, a column default),
|
|
1674
|
+
* each from its value before: a declared default the record kept isn't one (#41).
|
|
1675
|
+
*/
|
|
1591
1676
|
commitInsert(row) {
|
|
1677
|
+
const written = new Set(this.changedNames());
|
|
1678
|
+
const before = new Map(Object.keys(this.#values).map((name) => [name, {
|
|
1679
|
+
stored: this.#storedForm(name),
|
|
1680
|
+
value: this.#valueBefore(name)
|
|
1681
|
+
}]));
|
|
1592
1682
|
if (row === void 0) {
|
|
1593
1683
|
this.#settle();
|
|
1594
1684
|
this.#markSaved();
|
|
1595
1685
|
} else this.loadRow(row);
|
|
1596
|
-
this.#savedChanges = Object.fromEntries(
|
|
1686
|
+
this.#savedChanges = Object.fromEntries([...before].filter(([name, { stored }]) => written.has(name) || !isSameCell(this.#storedForm(name), stored)).map(([name, { value }]) => [name, [value, this.#copyOf(name)]]));
|
|
1687
|
+
this.isPreviouslyNew = true;
|
|
1597
1688
|
}
|
|
1598
1689
|
/**
|
|
1599
1690
|
* After an update: apply values the write added (timestamps), then record the save. Every
|
|
@@ -1606,13 +1697,29 @@ var RecordState = class {
|
|
|
1606
1697
|
this.#settle();
|
|
1607
1698
|
this.#savedChanges = this.changes();
|
|
1608
1699
|
this.#markSaved();
|
|
1700
|
+
this.isPreviouslyNew = false;
|
|
1701
|
+
}
|
|
1702
|
+
/**
|
|
1703
|
+
* After a write straight to the row (`updateColumns`, #351): these attributes hold what was
|
|
1704
|
+
* stored, or what `row` returned for them, and have no unsaved change. The rest, and
|
|
1705
|
+
* `savedChanges`, are as they were.
|
|
1706
|
+
*/
|
|
1707
|
+
commitColumns(names, row = {}) {
|
|
1708
|
+
for (const name of names) {
|
|
1709
|
+
const { column } = this.#definition(name);
|
|
1710
|
+
const attribute = this.#attribute(name);
|
|
1711
|
+
this.#values[name] = column in row ? attribute.read(row[column]) : this.#copyOf(name);
|
|
1712
|
+
this.#snapshot.set(name, this.#storedForm(name));
|
|
1713
|
+
}
|
|
1609
1714
|
}
|
|
1610
1715
|
/** A save with nothing to write: nothing changes but `savedChanges`. */
|
|
1611
1716
|
commitClean() {
|
|
1612
1717
|
this.#savedChanges = {};
|
|
1718
|
+
this.isPreviouslyNew = false;
|
|
1613
1719
|
}
|
|
1614
1720
|
markDestroyed() {
|
|
1615
1721
|
this.#lifecycle = "destroyed";
|
|
1722
|
+
this.isPreviouslyNew = false;
|
|
1616
1723
|
}
|
|
1617
1724
|
/** A destroyed record is a read-only snapshot. (A keyless record may change in memory.) */
|
|
1618
1725
|
#requireNotDestroyed(action) {
|
|
@@ -1629,6 +1736,15 @@ var RecordState = class {
|
|
|
1629
1736
|
#attribute(name) {
|
|
1630
1737
|
return attributeFor(this.#model, name);
|
|
1631
1738
|
}
|
|
1739
|
+
/** A new record's initial value as stored: its declared default or generated id, else null. */
|
|
1740
|
+
#initialOf(name) {
|
|
1741
|
+
return this.#initialValues.has(name) ? this.#initialValues.get(name) : this.#attribute(name).write(null);
|
|
1742
|
+
}
|
|
1743
|
+
/** The value before the unsaved change: as last loaded or saved, or a new record's initial one. */
|
|
1744
|
+
#valueBefore(name) {
|
|
1745
|
+
if (this.#isInSnapshot(name)) return this.#snapshotValue(name);
|
|
1746
|
+
return this.#attribute(name).read(this.#initialOf(name));
|
|
1747
|
+
}
|
|
1632
1748
|
/** An attribute's current value in its stored form, for comparing with the Snapshot. */
|
|
1633
1749
|
#storedForm(name) {
|
|
1634
1750
|
return this.#attribute(name).write(this.#values[name]);
|
|
@@ -1654,18 +1770,18 @@ var RecordState = class {
|
|
|
1654
1770
|
this.#snapshotRow = row;
|
|
1655
1771
|
const names = Object.keys(this.#values);
|
|
1656
1772
|
if (names.length !== loadedCount) {
|
|
1657
|
-
for (const name of names) if (!this.#
|
|
1773
|
+
for (const name of names) if (!this.#isInRow(name)) this.#snapshot.set(name, this.#storedForm(name));
|
|
1658
1774
|
}
|
|
1659
1775
|
this.#lifecycle = "persisted";
|
|
1660
1776
|
this.#assigned.clear();
|
|
1661
1777
|
}
|
|
1662
1778
|
/** Whether the Snapshot has `name`: it was loaded or saved. */
|
|
1663
|
-
#
|
|
1664
|
-
return this.#snapshot.has(name) || this.#
|
|
1779
|
+
#isInSnapshot(name) {
|
|
1780
|
+
return this.#snapshot.has(name) || this.#isInRow(name);
|
|
1665
1781
|
}
|
|
1666
1782
|
/** `name`'s Snapshot entry, its stored form, made from the loaded row's cell on first use. */
|
|
1667
1783
|
#snapshotOf(name) {
|
|
1668
|
-
if (this.#snapshot.has(name) || !this.#
|
|
1784
|
+
if (this.#snapshot.has(name) || !this.#isInRow(name)) return this.#snapshot.get(name);
|
|
1669
1785
|
const attribute = this.#attribute(name);
|
|
1670
1786
|
const stored = attribute.write(attribute.read(this.#snapshotRow[this.#definition(name).column]));
|
|
1671
1787
|
this.#snapshot.set(name, stored);
|
|
@@ -1676,12 +1792,77 @@ var RecordState = class {
|
|
|
1676
1792
|
return this.#attribute(name).read(this.#snapshotOf(name));
|
|
1677
1793
|
}
|
|
1678
1794
|
/** Whether the row the Snapshot was loaded from has a cell for `name`. */
|
|
1679
|
-
#
|
|
1795
|
+
#isInRow(name) {
|
|
1680
1796
|
return this.#snapshotRow !== void 0 && this.#definition(name).column in this.#snapshotRow;
|
|
1681
1797
|
}
|
|
1682
1798
|
};
|
|
1683
|
-
|
|
1684
|
-
|
|
1799
|
+
// src/enum-switch.ts
|
|
1800
|
+
/** Takes an override's `enum: true` or `false` out of it, so its other changes are checked as any override's. */
|
|
1801
|
+
function takeEnumSwitch(override) {
|
|
1802
|
+
if (typeof override !== "object" || override === null) return { change: override };
|
|
1803
|
+
if (!("enum" in override) || typeof override.enum !== "boolean") return { change: override };
|
|
1804
|
+
const { enum: useDatabaseEnum, ...change } = override;
|
|
1805
|
+
return {
|
|
1806
|
+
useDatabaseEnum,
|
|
1807
|
+
change
|
|
1808
|
+
};
|
|
1809
|
+
}
|
|
1810
|
+
/**
|
|
1811
|
+
* A generated spec as an override's switch leaves it: `enum: true` lifts the `scopes: false` and
|
|
1812
|
+
* `instanceMethods: false` the schema wrote, so an enum's defaults apply, and the override's own
|
|
1813
|
+
* switches, applied after, win; so does an override's own list, which replaces the names.
|
|
1814
|
+
* `enum: false` drops the enum and its keys. Either switch is an `InvalidModel` on a column
|
|
1815
|
+
* without a generated enum.
|
|
1816
|
+
*/
|
|
1817
|
+
function generatedEnumBase(where, spec, { useDatabaseEnum, change }) {
|
|
1818
|
+
if (useDatabaseEnum === void 0) return hasOwnNames(change) ? withMethodsOn(spec) : spec;
|
|
1819
|
+
if (spec.enum === void 0) throw new InvalidModel(nothingToSwitch(where, useDatabaseEnum));
|
|
1820
|
+
return useDatabaseEnum ? withMethodsOn(spec) : withoutEnum(spec);
|
|
1821
|
+
}
|
|
1822
|
+
/** Whether an override gives an enum's names itself: a list or a mapping, not `undefined`. */
|
|
1823
|
+
function hasOwnNames(change) {
|
|
1824
|
+
return "enum" in change && change.enum !== void 0;
|
|
1825
|
+
}
|
|
1826
|
+
/** A spec without the switches a generated enum's methods are off by, so an enum's defaults apply. */
|
|
1827
|
+
function withMethodsOn(spec) {
|
|
1828
|
+
const { scopes: _scopes, instanceMethods: _instanceMethods, ...lifted } = spec;
|
|
1829
|
+
return lifted;
|
|
1830
|
+
}
|
|
1831
|
+
/** Why a switch has nothing to act on, and what to write instead of `enum: true`. */
|
|
1832
|
+
function nothingToSwitch(where, useDatabaseEnum) {
|
|
1833
|
+
return useDatabaseEnum ? `${where} has no enum from the database to turn on; list its names instead (enum: ["…", …])` : `${where} has no enum from the database to turn off`;
|
|
1834
|
+
}
|
|
1835
|
+
/** The method switches an override turns on, as written: `enum: true`, or `scopes: true`, … */
|
|
1836
|
+
const methodSwitches = [
|
|
1837
|
+
"enum",
|
|
1838
|
+
"scopes",
|
|
1839
|
+
"instanceMethods"
|
|
1840
|
+
];
|
|
1841
|
+
/** An override as an object of keys, whatever was written: `{}` for a type name, `false` or none. */
|
|
1842
|
+
function overrideKeys(override) {
|
|
1843
|
+
return typeof override === "object" && override !== null ? override : {};
|
|
1844
|
+
}
|
|
1845
|
+
/**
|
|
1846
|
+
* What to remove from an attribute's override to leave its database enum's methods off again
|
|
1847
|
+
* (`enum: true`), or undefined: no enum from the database, its methods off, or a list of its own.
|
|
1848
|
+
*/
|
|
1849
|
+
function methodsOffFix(spec, definition, override) {
|
|
1850
|
+
if (!(spec !== void 0 && specObjectOf(spec).enum !== void 0) || definition.enum === void 0 || typeof override["enum"] === "object") return;
|
|
1851
|
+
const turnedOn = methodSwitches.filter((key) => override[key] === true);
|
|
1852
|
+
return turnedOn.length === 0 ? void 0 : turnedOn.map((key) => `${key}: true`).join(" and ");
|
|
1853
|
+
}
|
|
1854
|
+
/** For each enum whose names the database gave, with its methods on, `methodsOffFix`'s answer (#64). */
|
|
1855
|
+
function methodsOffFixes(model) {
|
|
1856
|
+
const table = model.schema?.tables[model.table]?.attributes ?? {};
|
|
1857
|
+
const overrides = overrideKeys(model.attributes);
|
|
1858
|
+
const fixes = /* @__PURE__ */ new Map();
|
|
1859
|
+
for (const [attribute, definition] of model.attributeDefinitions) {
|
|
1860
|
+
const fix = methodsOffFix(table[attribute], definition, overrideKeys(overrides[attribute]));
|
|
1861
|
+
if (fix !== void 0) fixes.set(attribute, fix);
|
|
1862
|
+
}
|
|
1863
|
+
return fixes;
|
|
1864
|
+
}
|
|
1865
|
+
// src/generated-model.ts
|
|
1685
1866
|
const noAttributes = /* @__PURE__ */ new Map();
|
|
1686
1867
|
/**
|
|
1687
1868
|
* What each generated Model settled on when it was first used, by class (a subclass shares its
|
|
@@ -1732,19 +1913,23 @@ function rejectUngenerated(name, table, schema) {
|
|
|
1732
1913
|
if (generatedTable === void 0) throw new InvalidModel(`${name} isn't in the generated schema; run active-record schema`);
|
|
1733
1914
|
if (generatedTable !== table) throw new InvalidModel(`${name}'s table is ${table}, but the generated schema has ${generatedTable}; run active-record schema`);
|
|
1734
1915
|
}
|
|
1735
|
-
/**
|
|
1916
|
+
/**
|
|
1917
|
+
* Finds a generated Model's table in its schema, and its attributes after its overrides. The
|
|
1918
|
+
* schema lists it by its `modelName`, which its table is inferred from too.
|
|
1919
|
+
*/
|
|
1736
1920
|
function find(owner, schema) {
|
|
1737
|
-
const
|
|
1738
|
-
|
|
1921
|
+
const name = modelNameOf(owner);
|
|
1922
|
+
const table = Object.hasOwn(owner, "table") ? owner.table : tableize(name);
|
|
1923
|
+
rejectUngenerated(name, table, schema);
|
|
1739
1924
|
const tableSchema = Object.hasOwn(schema.tables, table) ? schema.tables[table] : void 0;
|
|
1740
1925
|
if (tableSchema === void 0) throw new InvalidModel(`${owner.name}'s table, ${table}, isn't in the generated schema`);
|
|
1741
|
-
const { specs,
|
|
1926
|
+
const { specs, isIgnoringColumns } = specsFor(owner.name, tableSchema, owner.attributes ?? {});
|
|
1742
1927
|
const definitions = new Map(Object.entries(specs).map(([name, spec]) => [name, define(name, spec)]));
|
|
1743
1928
|
return {
|
|
1744
1929
|
table,
|
|
1745
1930
|
primaryKey: Object.hasOwn(owner, "primaryKey") ? owner.primaryKey : tableSchema.primaryKey,
|
|
1746
1931
|
definitions,
|
|
1747
|
-
|
|
1932
|
+
isIgnoringColumns
|
|
1748
1933
|
};
|
|
1749
1934
|
}
|
|
1750
1935
|
/**
|
|
@@ -1770,8 +1955,10 @@ function settleGenerated(model) {
|
|
|
1770
1955
|
let found = settled.get(owner);
|
|
1771
1956
|
if (found === void 0) {
|
|
1772
1957
|
found = find(owner, place.schema);
|
|
1773
|
-
bindTable(owner, found.table, {
|
|
1958
|
+
bindTable(owner, found.table, { isIgnoringColumns: found.isIgnoringColumns });
|
|
1774
1959
|
defineAttributeAccessors(owner.prototype, found.definitions.keys());
|
|
1960
|
+
defineEnumMethods(owner.prototype, found.definitions);
|
|
1961
|
+
defineEnumStatics(owner, found.definitions);
|
|
1775
1962
|
settled.set(owner, found);
|
|
1776
1963
|
}
|
|
1777
1964
|
settled.set(model, found);
|
|
@@ -1780,7 +1967,7 @@ function settleGenerated(model) {
|
|
|
1780
1967
|
* Whether a class's attributes are fixed: a hand-declared Model's are when it's defined, and a
|
|
1781
1968
|
* generated Model's when it's first used. A base class has none, which is fixed too.
|
|
1782
1969
|
*/
|
|
1783
|
-
function
|
|
1970
|
+
function hasSettledAttributes(model) {
|
|
1784
1971
|
return settled.has(model) || tableOwnerOf(model) === void 0;
|
|
1785
1972
|
}
|
|
1786
1973
|
/** Whether a class is a generated Model: built on a base holding a generated schema. */
|
|
@@ -1815,16 +2002,22 @@ function defineGeneratedStatics(root) {
|
|
|
1815
2002
|
*/
|
|
1816
2003
|
function checked(where, attribute, override) {
|
|
1817
2004
|
if (override === false) return false;
|
|
1818
|
-
if (isAttributeType(override)) return { type: override };
|
|
1819
|
-
|
|
1820
|
-
|
|
2005
|
+
if (isAttributeType(override) || isCustomType(override)) return { change: { type: override } };
|
|
2006
|
+
const { useDatabaseEnum, change } = takeEnumSwitch(override);
|
|
2007
|
+
if (!isSpecOverride(change)) throw new InvalidModel(`${where}.${attribute}: an override is a type name, { ${overridableKeyNames} }, or false`);
|
|
2008
|
+
return {
|
|
2009
|
+
useDatabaseEnum,
|
|
2010
|
+
change
|
|
2011
|
+
};
|
|
1821
2012
|
}
|
|
1822
2013
|
/**
|
|
1823
2014
|
* A generated spec with an override applied, refused if it leaves a spec a type can't have (#99,
|
|
1824
2015
|
* #73). The merged spec's type isn't known statically, so it's checked here, as a Model's is.
|
|
1825
2016
|
*/
|
|
1826
|
-
function checkedOverride(where, spec,
|
|
1827
|
-
const
|
|
2017
|
+
function checkedOverride(where, spec, override) {
|
|
2018
|
+
const base = generatedEnumBase(where, specObjectOf(spec), override);
|
|
2019
|
+
const { change } = override;
|
|
2020
|
+
const changed = applyOverride(base, change);
|
|
1828
2021
|
const problem = specProblem(where, changed);
|
|
1829
2022
|
if (problem !== void 0) throw new InvalidModel(problem);
|
|
1830
2023
|
return changed;
|
|
@@ -1846,8 +2039,7 @@ function specsFor(name, table, overrides) {
|
|
|
1846
2039
|
}
|
|
1847
2040
|
return {
|
|
1848
2041
|
specs,
|
|
1849
|
-
|
|
2042
|
+
isIgnoringColumns: [...changes.values()].includes(false)
|
|
1850
2043
|
};
|
|
1851
2044
|
}
|
|
1852
|
-
|
|
1853
|
-
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 };
|
|
2045
|
+
export { modelNameOf as $, FILTERED as A, define as B, declared as C, castInherited as D, attributeFor as E, isFiltered as F, defineEnumMethods as G, requireDefined as H, shownKey as I, enumScopeNames as J, defineEnumStatics as K, shownValue$1 as L, boundValue as M, defaultFilterAttributes as N, noMatch as O, filteredValues as P, isIgnoringColumns as Q, attributeOf as R, declare as S, seal as T, defineType as U, initialValues as V, specProblem as W, explainMissingTable as X, defineModelName as Y, inferTableNames as Z, inspectCustom as _, isGenerated as a, tableize as at, attributesNamedInMessages as b, methodsOffFixes as c, state as d, ownValueSetter as et, Errors as f, FilteredMark as g, fullMessageOf as h, isBase as i, tableOwnerModelName as it, Filtered as j, withArticle as k, RecordState as l, clearErrors as m, defineGeneratedStatics as n, requireModelName as nt, schemaAdapter as o, ancestors as ot, addFailure as p, enumNameProblem as q, hasSettledAttributes as r, requireTableName as rt, settleGenerated as s, staticBelow as st, defineAttributeAccessors as t, rejectAbstract as tt, linksOf as u, printed as v, declaredByClass as w, humanAttributeName as x, styled as y, attributesForColumn as z };
|