@forestfuture/active-record 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
- import { a as AttributeType, c as ValueSource, d as EnumNames, f as EnumValues, g as CustomType, h as AnyCustomType, i as AttributeSpecs, m as TextEnum, n as AttributeProperties, o as ExactSpecs, p as IntegerEnum, s as SpecObject, t as AttributeDefinition, u as EnumMapping } from "./metadata-CzntpYzC.mjs";
1
+ import { D as Duration, M as AttributeAlias, N as DefinedSpecs, O as AnyCustomType, P as WithoutAliases, S as SecurePasswordMethods, T as WithSecurePasswords, _ as SecureTokenOptions, a as AttributeType, b as PasswordResetTokenArgument, c as SpecObject, d as EnumMapping, f as EnumNames, g as SecureTokenMethods, h as TextEnum, i as AttributeSpecs, j as AliasSpecs, k as CustomType, l as ValueSource, m as IntegerEnum, n as AttributeProperties, o as DeclaredAttributes, p as EnumValues, s as ExactSpecs, t as AttributeDefinition, w as SecurePasswordSpecs, x as SecurePasswordDeclaration, y as AuthenticateByAttributes } from "./metadata-BIUbGJlS.mjs";
2
2
  /** What `comparison` compares: numbers with numbers, strings with strings, Dates by their time. */
3
3
  type Comparable = number | string | Date;
4
4
  /** A bound: a value, or a function of the record being validated (`(event) => event.startsAt`). */
5
5
  type ComparisonBound<R = never> = Comparable | ((record: R) => Comparable | null);
6
- /** The bounds of a `comparison` rule, with Rails' error types as keys. `R` is the record type. */
6
+ /** The bounds of a `comparison` rule, with its error types as keys. `R` is the record type. */
7
7
  interface ComparisonOptions<R = never> {
8
8
  greaterThan?: ComparisonBound<R>;
9
9
  greaterThanOrEqualTo?: ComparisonBound<R>;
@@ -37,7 +37,7 @@ type ScopeStems<A> = { [K in keyof A]: A[K] extends {
37
37
  } ? never : Stems<K, A[K]>; }[keyof A];
38
38
  /**
39
39
  * What the enums of the specs `A` add to a record: a predicate for each name, and a setter that
40
- * assigns it and saves, with its `OrThrow`, as Rails' `published!` updates the record.
40
+ * assigns it and saves, with its `OrThrow`.
41
41
  */
42
42
  type EnumMethods<A> = { [P in `is${RecordStems<A>}`]: () => boolean; } & { [P in `saveAs${RecordStems<A>}`]: () => Promise<boolean>; } & { [P in `saveAs${RecordStems<A>}OrThrow`]: () => Promise<true>; };
43
43
  /** What the enums of the specs `A` add to a Model: a scope for each name, and a `not…` scope. */
@@ -84,7 +84,8 @@ type UnscopedPart = "where" | "order" | "limit" | "offset" | "select" | "distinc
84
84
  declare class Attribute {
85
85
  #private;
86
86
  readonly name: string;
87
- readonly column: string;
87
+ /** Its column; `UnknownAttribute` for a virtual attribute, which has none (#356). */
88
+ get column(): string;
88
89
  /** Whether it's a `string` attribute, which D1 compares as text, not by number. */
89
90
  get isText(): boolean;
90
91
  /** Whether it's a `binary` attribute, whose cells are bytes, which JSON can't hold (#20). */
@@ -98,6 +99,23 @@ declare class Attribute {
98
99
  * unless the attribute is filtered (#83).
99
100
  */
100
101
  cast(value: unknown): unknown;
102
+ /** An assigned value cast, then normalized (#354): what a record keeps for it. */
103
+ assigned(value: unknown): unknown;
104
+ /**
105
+ * An already cast value through each of the attribute's normalizations, in order (#354): null
106
+ * only through those declared `applyToNull`. Each result is cast again, so it's a value of the
107
+ * attribute's type, whatever plain JavaScript returns; a promise is refused.
108
+ */
109
+ normalize(value: unknown): unknown;
110
+ /**
111
+ * A condition's value cast as a condition's, then normalized as an assigned value is (#354), each
112
+ * result cast again as a condition's, so a decimal's precision limits neither. A value that
113
+ * can't be cast is kept as it was given, so it still matches nothing, and an error that names it
114
+ * names what was given; a result that can't be cast throws, as assigning it would.
115
+ */
116
+ normalizedCondition(value: unknown): unknown;
117
+ /** Whether the attribute has a normalization, so its conditions need normalizing (#354). */
118
+ get hasNormalization(): boolean;
101
119
  /**
102
120
  * A key copied from another record or inherited from a condition: cast as a condition's, but
103
121
  * one that can't be cast throws, naming the association it came through.
@@ -118,6 +136,8 @@ declare class Attribute {
118
136
  write(value: unknown): unknown;
119
137
  /** An assigned value cast, then in the form D1 stores. */
120
138
  store(value: unknown): unknown;
139
+ /** An assigned value cast and normalized (#354), then in the form D1 stores. */
140
+ storeNormalized(value: unknown): unknown;
121
141
  /**
122
142
  * A cell D1 returned as the attribute's value. One that isn't (text in a Unix time column, or
123
143
  * past the range of a `Date`; a json cell that isn't JSON) throws `TypeError` naming the
@@ -129,7 +149,7 @@ declare class Attribute {
129
149
  /**
130
150
  * Whether two values are the same as stored (dates by time, json and bytes by content). Each is
131
151
  * cast as a condition's value first, so `isAttributeChanged`'s `from` and `to` compare as
132
- * Rails' do, and one that can't be cast is the same as nothing (#20).
152
+ * conditions do, and one that can't be cast is the same as nothing (#20).
133
153
  */
134
154
  isSame(a: unknown, b: unknown): boolean;
135
155
  /** An assigned value, cast and written, bound hidden from `onQuery` if filtered (#83). */
@@ -187,6 +207,13 @@ interface Dialect {
187
207
  * it matches `linked`'s column as a condition on `linked` would: by text for a text attribute.
188
208
  */
189
209
  linkedKey(key: string, keyAttribute: Attribute, linked: Attribute): string;
210
+ /**
211
+ * A record's write that must change its row (an update or delete by its key and `lockVersion`,
212
+ * #357), followed by a check that fails the whole atomic batch when it changed none, with an
213
+ * error whose message holds `marker`, bound as a value: one statement or several, the write's
214
+ * result first.
215
+ */
216
+ staleGuard(write: CompiledSql, marker: string): CompiledSql[];
190
217
  /**
191
218
  * A bulk removal (a DELETE, or an UPDATE nullifying a key) and the counter caches it changes
192
219
  * (#61), as one statement: `decrements` writes the counters' UPDATEs, given SQL counting the rows
@@ -207,37 +234,18 @@ interface QuerySql {
207
234
  sql: string;
208
235
  params: unknown[];
209
236
  }
210
- /** What `user.posts()` has besides its Relation's methods, as Rails' collection proxy does. */
211
- interface CollectionMethods<M extends Model> {
212
- /**
213
- * Adds records to the association (Rails' `<<`): sets each one's foreign key and saves them
214
- * together, resolving to `false`, with nothing written, if one can't be saved.
215
- */
216
- push(...records: M[]): Promise<boolean>;
217
- /**
218
- * Removes records from the association by its `dependent:` strategy, as Rails' collection
219
- * `delete`: destroys them with `"destroy"`, deletes their rows with `"deleteAll"`, and
220
- * otherwise sets their foreign key to NULL. Resolves to the records.
221
- */
222
- delete(...records: M[]): Promise<M[]>;
223
- /**
224
- * Destroys records of the association, callbacks and dependents included, whatever its
225
- * `dependent:` is, in one write: if one refuses, it throws `RecordNotDestroyed` and nothing
226
- * is destroyed. Resolves to the records.
227
- */
228
- destroy(...records: M[]): Promise<M[]>;
229
- /**
230
- * Removes every record of the association as `deleteAll()` does, by its `dependent:`, and
231
- * forgets the records built through it: afterwards it reads as empty without a query.
232
- */
233
- clear(): Promise<void>;
234
- /**
235
- * Destroys every record of the association, callbacks and dependents included, whatever its
236
- * `dependent:` is, in one write, as `destroy` does; then it reads as empty without a query.
237
- * Resolves to the records.
238
- */
239
- destroyAll(): Promise<M[]>;
240
- }
237
+ /**
238
+ * What `normalizes` takes for an attribute whose values are `T`: a function given a value of
239
+ * the attribute's type, once it's cast, returning the value to keep. It isn't given `null`
240
+ * unless `applyToNull` is `true`.
241
+ */
242
+ type NormalizeOptions<T> = {
243
+ with: (value: NonNullable<T>) => T;
244
+ applyToNull?: false;
245
+ } | {
246
+ with: (value: T) => T;
247
+ applyToNull: true;
248
+ };
241
249
  /** What Node's `util.inspect` passes a custom inspector; `src/` doesn't import Node's types. */
242
250
  interface InspectOptions {
243
251
  depth?: number | null;
@@ -249,7 +257,7 @@ type Inspect = (value: unknown, options?: InspectOptions) => string;
249
257
  declare const inspectCustom: unique symbol;
250
258
  /** What `inOrderOf` takes after its list: whether to keep only the records with a listed value. */
251
259
  interface InOrderOfOptions {
252
- /** Keep only the records whose value is in the list (the default), as Rails does; `false` keeps every one, those not in it last. */
260
+ /** Keep only the records whose value is in the list (the default); `false` keeps every one, those not in it last. */
253
261
  filter?: boolean;
254
262
  }
255
263
  /** A part of a query `unscope` drops by name: `unscope("order")`. */
@@ -268,15 +276,15 @@ declare class Comparison<T = unknown> {
268
276
  }
269
277
  /** `attribute > value` */
270
278
  declare function gt<T>(value: T): Comparison<T>;
271
- /** `attribute >= value`, like Rails' endless range `value..` */
279
+ /** `attribute >= value`: everything from `value` on. */
272
280
  declare function gte<T>(value: T): Comparison<T>;
273
- /** `attribute < value`, like Rails' beginless range `...value` */
281
+ /** `attribute < value`: everything before `value`. */
274
282
  declare function lt<T>(value: T): Comparison<T>;
275
- /** `attribute <= value`, like Rails' beginless range `..value` */
283
+ /** `attribute <= value`: everything up to `value`, `value` included. */
276
284
  declare function lte<T>(value: T): Comparison<T>;
277
285
  /**
278
- * `attribute BETWEEN start AND end`, both ends included, like Rails' `start..end`. With
279
- * `excludeEnd`, `start <= attribute < end`, like `start...end` (e.g. a window of days).
286
+ * `attribute BETWEEN start AND end`, both ends included. With
287
+ * `excludeEnd`, `start <= attribute < end` (e.g. a window of days).
280
288
  */
281
289
  declare function between<T>(start: T, end: T, options?: {
282
290
  excludeEnd?: boolean;
@@ -316,6 +324,159 @@ type OrderSpec<M> = { [K in keyof AttributesOf<M>]?: OrderDirection | {
316
324
  direction: OrderDirection;
317
325
  nulls?: NullsPlacement;
318
326
  }; };
327
+ /** What `user.posts()` has besides its Relation's methods. */
328
+ interface CollectionMethods<M extends Model> {
329
+ /**
330
+ * Adds records to the association: sets each one's foreign key and saves them
331
+ * together, resolving to `false`, with nothing written, if one can't be saved.
332
+ */
333
+ push(...records: M[]): Promise<boolean>;
334
+ /**
335
+ * Removes records from the association by its `dependent:` strategy:
336
+ * destroys them with `"destroy"`, deletes their rows with `"deleteAll"`, and
337
+ * otherwise sets their foreign key to NULL. Resolves to the records.
338
+ */
339
+ delete(...records: M[]): Promise<M[]>;
340
+ /**
341
+ * Destroys records of the association, callbacks and dependents included, whatever its
342
+ * `dependent:` is, in one write: if one refuses, it throws `RecordNotDestroyed` and nothing
343
+ * is destroyed. Resolves to the records.
344
+ */
345
+ destroy(...records: M[]): Promise<M[]>;
346
+ /**
347
+ * Removes every record of the association as `deleteAll()` does, by its `dependent:`, and
348
+ * forgets the records built through it: afterwards it reads as empty without a query.
349
+ */
350
+ clear(): Promise<void>;
351
+ /**
352
+ * Destroys every record of the association, callbacks and dependents included, whatever its
353
+ * `dependent:` is, in one write, as `destroy` does; then it reads as empty without a query.
354
+ * Resolves to the records.
355
+ */
356
+ destroyAll(): Promise<M[]>;
357
+ }
358
+ /**
359
+ * An association's scope, such as `(q) => q.order({ createdAt: "asc" })`: it receives
360
+ * the target's Relation, with its scopes, and returns a narrowed one.
361
+ */
362
+ type AssociationScope<C extends ModelClass> = (relation: Scoped<InstanceType<C>, ScopesOf<C>>) => unknown;
363
+ /** What an association declaration takes: the keys that link the Models, and a scope. */
364
+ interface AssociationOptions<C extends ModelClass = ModelClass> {
365
+ /**
366
+ * The attribute holding the link: on the owner for belongsTo, on the target otherwise.
367
+ * Inferred when left out: a belongsTo's name + `Id` (`author` → `authorId`),
368
+ * or for a hasMany/hasOne the owner's `modelName` + `Id` (`User` → `userId`).
369
+ */
370
+ foreignKey?: string;
371
+ /** The attribute the foreign key points at; defaults to the pointed-at Model's primary key. */
372
+ primaryKey?: string;
373
+ /** Narrows or orders the target's records for this association: `(q) => q.order(…)`. */
374
+ scope?: AssociationScope<C>;
375
+ /** What destroying the owner does to this association's records (hasMany and hasOne). */
376
+ dependent?: Dependent;
377
+ /**
378
+ * Saving the owner also saves this association's loaded records that changed, and destroys
379
+ * those marked with `markForDestruction()` (#37).
380
+ */
381
+ autosave?: true;
382
+ /**
383
+ * The target's association that points back (#62), whose record is this one, so records loaded
384
+ * or built through either side point at each other without a query: a hasMany's or hasOne's
385
+ * belongsTo, or a belongsTo's hasOne. Inferred when left out; `false` turns it off.
386
+ */
387
+ inverseOf?: string | false;
388
+ }
389
+ /**
390
+ * What an association through another takes (#59): `projects = hasMany(Project, { through:
391
+ * "assignments" })`. Its keys and `autosave` are its hops'; a hasMany's `dependent` acts on its
392
+ * join records (`ThroughDependent`).
393
+ */
394
+ interface ThroughOptions<C extends ModelClass = ModelClass> {
395
+ /** The owner's association it reaches its records through: one to the join Model. */
396
+ through: string;
397
+ /**
398
+ * The association of the `through` association's Model that reaches the records. Left out, it's
399
+ * the one named as this association, singular or plural (`projects` → `project`, `projects`).
400
+ */
401
+ source?: string;
402
+ /** Narrows or orders its records: `(q) => q.order(…)`. */
403
+ scope?: AssociationScope<C>;
404
+ }
405
+ /**
406
+ * What destroying the owner, and removing records with `delete`, do to a hasMany through
407
+ * another's join records (#434): destroy them, callbacks included, or delete their rows.
408
+ */
409
+ type ThroughDependent = "destroy" | "deleteAll";
410
+ /** What a hasMany's `dependent:` does to its records when the owner is destroyed. */
411
+ type HasManyDependent = "destroy" | "deleteAll" | "nullify" | "restrictWithException" | "restrictWithError";
412
+ /** What a hasOne's `dependent:` does to its record: `delete` in place of `deleteAll`. */
413
+ type HasOneDependent = "destroy" | "delete" | "nullify" | "restrictWithException" | "restrictWithError";
414
+ type Dependent = HasManyDependent | HasOneDependent;
415
+ /**
416
+ * `await post.author()`: the owning record, or null. `post.author.set(user)` points the post at
417
+ * another record, and `build`/`create` make a new one for it.
418
+ */
419
+ interface BelongsTo<C extends ModelClass> {
420
+ (): Promise<InstanceType<C> | null>;
421
+ set(record: InstanceType<C> | null): void;
422
+ build(attributes?: Partial<AttributesOf<InstanceType<C>>>): InstanceType<C>;
423
+ create(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
424
+ createOrThrow(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
425
+ }
426
+ /**
427
+ * `await remark.commentable()`: the record a polymorphic belongsTo points at (#60), of whichever
428
+ * listed Model its type names, or null. `remark.commentable.set(post)` points it at another,
429
+ * setting both the type and the key. There's no `build` or `create`: which Model to make isn't
430
+ * known.
431
+ */
432
+ interface PolymorphicBelongsTo<C extends ModelClass> {
433
+ (): Promise<InstanceType<C> | null>;
434
+ set(record: InstanceType<C> | null): void;
435
+ }
436
+ /**
437
+ * `await user.profile()`: the one associated record, or null. `await user.profile.set(profile)`
438
+ * gives the user another, and `build(attrs)` and `create(attrs)` make a new one pointing at the
439
+ * user. Each replaces the old record, removed by `dependent:` when the new one is written.
440
+ */
441
+ interface HasOne<C extends ModelClass> {
442
+ (): Promise<InstanceType<C> | null>;
443
+ set(record: InstanceType<C> | null): Promise<void>;
444
+ build(attributes?: Partial<AttributesOf<InstanceType<C>>>): InstanceType<C>;
445
+ create(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
446
+ createOrThrow(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
447
+ }
448
+ /**
449
+ * `user.posts()`: a Relation of the associated records, with the target's scopes, and the
450
+ * collection methods (`push`, `delete`, `destroy`, `clear`) that only the association itself has.
451
+ */
452
+ type HasMany<C extends ModelClass> = () => HasManyCollection<InstanceType<C>, ScopesOf<C>>;
453
+ /**
454
+ * `note.tags()` for an association through another (#59): a Relation of its records, which
455
+ * reads and preloads as any hasMany's, with the collection methods. Its writes go to its join
456
+ * records (#434): `push`, `build` and `create` make one, and `delete`, `destroy`, `clear`, and
457
+ * its own `deleteAll` and `destroyAll` remove them. Inserting and upserting, which make none, are typed `never`,
458
+ * so it's still a Relation, for `or`, `merge` and a batch's `updateAll`.
459
+ */
460
+ type HasManyThrough<C extends ModelClass> = () => Scoped<InstanceType<C>, ScopesOf<C>> & CollectionMethods<InstanceType<C>> & { readonly [W in ThroughWrite]: never; };
461
+ /** The writes a through association's own Relation refuses (#434): they make no join records. */
462
+ type ThroughWrite = "insert" | "insertAll" | "upsert" | "upsertAll";
463
+ /**
464
+ * `await mark.note()` for a hasOne through another (#59): its record, or null. `set(note)`
465
+ * points the owner's join record at another (#434); it has no `build` or `create`.
466
+ */
467
+ interface HasOneThrough<C extends ModelClass> {
468
+ (): Promise<InstanceType<C> | null>;
469
+ /**
470
+ * Points the owner's join record at `record`, saved at once on a saved owner, or builds one
471
+ * through the association it goes through; `null` destroys the join record.
472
+ */
473
+ set(record: InstanceType<C> | null): Promise<void>;
474
+ /** Type-only: marks the accessor, so a record method returning a Promise isn't one. */
475
+ readonly [throughTarget]: C;
476
+ }
477
+ declare const throughTarget: unique symbol;
478
+ /** What a hasMany accessor returns: its Relation, with the collection methods. */
479
+ type HasManyCollection<M extends Model, S = {}> = Scoped<M, S> & CollectionMethods<M>;
319
480
  /** One statement's result, the same on every database. */
320
481
  interface StatementResult {
321
482
  /** The rows it returned: a read's, or a write's `RETURNING`. */
@@ -375,10 +536,46 @@ declare class Statement<Row = never> {
375
536
  readonly [rowType]?: Row;
376
537
  }
377
538
  /**
378
- * What a new record is handed to, once its attributes are assigned and before it's saved (Rails'
379
- * block): `create({ email }, (user) => { user.role = "member" })`. Awaited where it's saved.
539
+ * What a new record is handed to, once its attributes are assigned and before it's saved:
540
+ * `create({ email }, (user) => { user.role = "member" })`. Awaited where it's saved.
380
541
  */
381
542
  type Init<M> = (record: M) => void | Promise<void>;
543
+ /** What a signed id is for, and how long it lasts: forever unless given. */
544
+ interface SignedIdOptions {
545
+ /** How long it lasts: `{ minutes: 15 }`. Give this or `expiresAt`. */
546
+ readonly expiresIn?: Duration;
547
+ /** When it stops finding its record. */
548
+ readonly expiresAt?: Date;
549
+ /** What it's for (`"login"`): `findSigned` finds its record only given the same. */
550
+ readonly purpose?: string;
551
+ }
552
+ /** What `findSigned` takes: the purpose the signed id was made for. */
553
+ interface FindSignedOptions {
554
+ readonly purpose?: string;
555
+ }
556
+ /** The finders by token every Relation has. */
557
+ declare abstract class TokenFinders<M extends Model> {
558
+ #private;
559
+ abstract findBy(conditions: never): Promise<M | null>;
560
+ /**
561
+ * The record a signed id finds (`await user.signedId()`), if this Model's secret signed it for
562
+ * the same `purpose` and it hasn't expired, and this Relation matches it; or null.
563
+ */
564
+ findSigned(signedId: unknown, options?: FindSignedOptions): Promise<M | null>;
565
+ /** Like `findSigned`, but throws `InvalidToken` for a signed id that isn't valid, and `RecordNotFound` when its record is gone. */
566
+ findSignedOrThrow(signedId: unknown, options?: FindSignedOptions): Promise<M>;
567
+ /**
568
+ * The record a token for `purpose` finds (`await user.generateTokenFor(purpose)`), if this
569
+ * Model's secret signed it, it hasn't expired, the value it depends on is unchanged, and this
570
+ * Relation matches it; or null. `TypeError` for a purpose the Model doesn't declare.
571
+ */
572
+ findByTokenFor(purpose: string, token: unknown): Promise<M | null>;
573
+ /**
574
+ * Like `findByTokenFor`, but throws `InvalidToken` for a token that isn't valid, and
575
+ * `RecordNotFound` when its record is gone or the value it depends on changed.
576
+ */
577
+ findByTokenForOrThrow(purpose: string, token: unknown): Promise<M>;
578
+ }
382
579
  /** Two or more of a Model's attributes, as `pluck` and `pick` take them for tuples. */
383
580
  type AttributeList<M extends Model> = readonly [keyof AttributesOf<M> & string, keyof AttributesOf<M> & string, ...(keyof AttributesOf<M> & string)[]];
384
581
  /** The types a sum or an average takes; a custom type stored as one of them too. */
@@ -469,6 +666,38 @@ interface TouchOptions {
469
666
  }
470
667
  /** `touch`'s arguments on record type `R`: its datetime attributes' names, then its options. */
471
668
  type TouchArguments<R> = DatetimeAttributeKey<R>[] | [...DatetimeAttributeKey<R>[], TouchOptions];
669
+ /** What `paginate()` takes: which page, how many records on it, and whether to count them all. */
670
+ interface PageOptions {
671
+ /** The page, from 1: a number, or untrusted text such as a query string's `"2"`. */
672
+ page?: number | string | null;
673
+ /** Records on a page, a number or text as `page` is. */
674
+ perPage?: number | string | null;
675
+ /** `false` skips the `COUNT`: the page has no `total` or `totalPages`. */
676
+ count?: boolean;
677
+ }
678
+ /** A page of records, from `paginate({ count: false })`: where it is, but no total. */
679
+ interface CountlessPage<M extends Model> {
680
+ records: M[];
681
+ page: number;
682
+ perPage: number;
683
+ hasNext: boolean;
684
+ hasPrevious: boolean;
685
+ }
686
+ /** A page of records, from `paginate()`, with the total it's a page of. */
687
+ interface Page<M extends Model> extends CountlessPage<M> {
688
+ total: number;
689
+ totalPages: number;
690
+ }
691
+ /** `paginate` as a static of every Model, typed for the class it's called on. */
692
+ interface PaginateStatic {
693
+ <C extends QueryableClass>(this: C, options: PageOptions & {
694
+ count: false;
695
+ }): Promise<CountlessPage<InstanceType<C>>>;
696
+ <C extends QueryableClass>(this: C, options?: PageOptions & {
697
+ count?: true;
698
+ }): Promise<Page<InstanceType<C>>>;
699
+ <C extends QueryableClass>(this: C, options: PageOptions): Promise<Page<InstanceType<C>> | CountlessPage<InstanceType<C>>>;
700
+ }
472
701
  /** What `findEach`, `findInBatches` and `inBatches` take. */
473
702
  interface IterationOptions {
474
703
  /** Records in each batch: each is one query. 1000 by default. */
@@ -488,7 +717,7 @@ type ScopeMethods<M extends Model, S> = { [K in keyof S]: S[K] extends ((this: n
488
717
  /** A Relation of Model records `M` with the Model's scope methods `S`. */
489
718
  type Scoped<M extends Model, S = {}> = [keyof S] extends [never] ? Relation<M, S> : Relation<M, S> & ScopeMethods<M, S>;
490
719
  /** A lazy, immutable description of a query against one Model. */
491
- declare class Relation<M extends Model, S = {}> {
720
+ declare class Relation<M extends Model, S = {}> extends TokenFinders<M> {
492
721
  #private;
493
722
  /** Type-only: the Model's scopes, so chained calls keep their scope methods. */
494
723
  readonly [scopeTypes]?: S;
@@ -501,21 +730,21 @@ declare class Relation<M extends Model, S = {}> {
501
730
  /** Negates the whole condition: `NOT (…)`. Rows where it is NULL are excluded too. */
502
731
  whereNot(conditions: Conditions<M> | SafeSql): Scoped<M, S>;
503
732
  /**
504
- * Replaces the conditions on these attributes with these, as Rails' `rewhere`: those on other
505
- * attributes, and fragments, are kept.
733
+ * Replaces the conditions on these attributes with these: those on other attributes, and
734
+ * fragments, are kept.
506
735
  */
507
736
  rewhere(conditions: Conditions<M>): Scoped<M, S>;
508
737
  /**
509
- * Drops parts of the query, as Rails' `unscope`: `unscope("order", "limit")`, or the conditions
738
+ * Drops parts of the query: `unscope("order", "limit")`, or the conditions
510
739
  * on some attributes, `unscope({ where: "role" })`. A default scope's are dropped too.
511
740
  */
512
741
  unscope(...parts: (QueryPart | {
513
742
  where: AttributeNames<M>;
514
743
  })[]): Scoped<M, S>;
515
- /** Keeps only these parts of the query, as Rails' `only`: `only("where", "order")`. */
744
+ /** Keeps only these parts of the query: `only("where", "order")`. */
516
745
  only(...parts: QueryPart[]): Scoped<M, S>;
517
746
  /**
518
- * Leaves these records out, by primary key, as Rails' `excluding`: `excluding(post)`, or
747
+ * Leaves these records out, by primary key: `excluding(post)`, or
519
748
  * `excluding(posts)`. A record not yet saved leaves nothing out.
520
749
  */
521
750
  excluding(...records: (M | readonly M[])[]): Scoped<M, S>;
@@ -529,7 +758,7 @@ declare class Relation<M extends Model, S = {}> {
529
758
  /**
530
759
  * ANDs `other`'s conditions onto this Relation's. For select, order, limit, offset and
531
760
  * distinct, a clause `other` sets explicitly replaces this one's; one it doesn't set is kept.
532
- * Orders are replaced, not concatenated (a deliberate difference from Rails). `other` may be a
761
+ * Orders are replaced, not concatenated, so a merged order reads as written. `other` may be a
533
762
  * Relation of a Model this one joins once (#24): its conditions apply to the joined table.
534
763
  */
535
764
  merge<T extends Model = M, O = S>(other: Relation<T, O>): Scoped<M, S>;
@@ -538,10 +767,10 @@ declare class Relation<M extends Model, S = {}> {
538
767
  * nulls: "last" } }`), or by an `sql` fragment expression. Repeated calls append.
539
768
  */
540
769
  order(spec: OrderSpec<M> | SafeSql): Scoped<M, S>;
541
- /** Replaces the order so far, as in Rails; `reorder()` removes it. */
770
+ /** Replaces the order so far; `reorder()` removes it. */
542
771
  reorder(spec?: OrderSpec<M> | SafeSql): Scoped<M, S>;
543
772
  /**
544
- * Orders by `attribute`'s place in `values`, then by any order after it, as Rails' `in_order_of`:
773
+ * Orders by `attribute`'s place in `values`, then by any order after it:
545
774
  * `inOrderOf("status", ["open", "paid"])`. Keeps only the records with one of them, unless
546
775
  * `filter: false`, which keeps the rest after them.
547
776
  */
@@ -582,14 +811,14 @@ declare class Relation<M extends Model, S = {}> {
582
811
  * wrote and the `returning` attributes of each (the primary key by default; `false` for none).
583
812
  * Skips validations and callbacks; declared defaults, generated ids, and timestamps apply, and
584
813
  * this Relation's equality conditions are inserted over the given attributes (#470). A
585
- * duplicate throws, unless `onDuplicate: "skip"` (Rails' `insert`). `b.insert` is the same
814
+ * duplicate throws, unless `onDuplicate: "skip"`. `b.insert` is the same
586
815
  * write, for a batch.
587
816
  */
588
817
  insert<const R extends Returning<M> | undefined = undefined>(attributes: Partial<AttributesOf<M>>, options?: InsertOptions<M> & {
589
818
  returning?: R;
590
819
  }): Promise<WriteResult<ReturnedRow<M, R>>>;
591
820
  /**
592
- * Inserts several rows with the same attributes now (Rails' `insert_all!`): in one statement,
821
+ * Inserts several rows with the same attributes now: in one statement,
593
822
  * or several in one atomic batch when they pass the database's cap on one value.
594
823
  */
595
824
  insertAll<const R extends Returning<M> | undefined = undefined>(rows: readonly Partial<AttributesOf<M>>[], options?: InsertOptions<M> & {
@@ -598,26 +827,26 @@ declare class Relation<M extends Model, S = {}> {
598
827
  /**
599
828
  * Inserts a row now, or updates it when it clashes with the unique index on `uniqueBy` (the
600
829
  * primary key by default): every given attribute and every value this Relation writes into the
601
- * row (#475), except the `uniqueBy` ones and `createdAt`, with `updatedAt` set, as Rails'
602
- * `upsert` does. Resolves as `insert` does, returning inserted and updated rows.
830
+ * row (#475), except the `uniqueBy` ones and `createdAt`, with `updatedAt` set.
831
+ * Resolves as `insert` does, returning inserted and updated rows.
603
832
  */
604
833
  upsert<const R extends Returning<M> | undefined = undefined>(attributes: Partial<AttributesOf<M>>, options?: UpsertOptions<M> & {
605
834
  returning?: R;
606
835
  }): Promise<WriteResult<ReturnedRow<M, R>>>;
607
- /** `upsert` for several rows with the same attributes, now (Rails' `upsert_all`). */
836
+ /** `upsert` for several rows with the same attributes, now. */
608
837
  upsertAll<const R extends Returning<M> | undefined = undefined>(rows: readonly Partial<AttributesOf<M>>[], options?: UpsertOptions<M> & {
609
838
  returning?: R;
610
839
  }): Promise<WriteResult<ReturnedRow<M, R>>>;
611
840
  /**
612
841
  * Updates every row this Relation matches, now, setting attribute values or an `sql`
613
842
  * fragment: ``updateAll(sql`${column("views")} = ${column("views")} + 1`)``. Resolves to the
614
- * number of rows updated. Skips validations and callbacks, and leaves `updatedAt` alone, as in
615
- * Rails. A `none()` Relation sends nothing and resolves to 0.
843
+ * number of rows updated. Skips validations and callbacks, and leaves `updatedAt` alone.
844
+ * A `none()` Relation sends nothing and resolves to 0.
616
845
  */
617
846
  updateAll(changes: Partial<AttributesOf<M>> | SafeSql): Promise<number>;
618
847
  /**
619
848
  * Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`) in every row this
620
- * Relation matches, in one statement, as Rails' `touch_all` (#50). Resolves to the number of
849
+ * Relation matches, in one statement (#50). Resolves to the number of
621
850
  * rows; skips what `updateAll` skips.
622
851
  */
623
852
  touchAll(...args: TouchArguments<M>): Promise<number>;
@@ -630,7 +859,7 @@ declare class Relation<M extends Model, S = {}> {
630
859
  /**
631
860
  * Deletes every row this Relation matches, now, resolving to the number of rows. On a hasMany
632
861
  * association itself (`user.posts().deleteAll()`), the rows' foreign key is set to NULL
633
- * instead unless its `dependent:` deletes, as in Rails. A `none()` Relation sends nothing and
862
+ * instead unless its `dependent:` deletes. A `none()` Relation sends nothing and
634
863
  * resolves to 0.
635
864
  */
636
865
  deleteAll(): Promise<number>;
@@ -656,7 +885,7 @@ declare class Relation<M extends Model, S = {}> {
656
885
  /**
657
886
  * The record with this primary key, keeping this Relation's conditions. With several ids,
658
887
  * `find(1, 2)` or `find([1, 2])`, the records in the ids' order (or this Relation's order,
659
- * if it has one), as Rails does; `RecordNotFound` if any is missing.
888
+ * if it has one); `RecordNotFound` if any is missing.
660
889
  */
661
890
  find(id: string | number): Promise<M>;
662
891
  find(ids: readonly (string | number)[]): Promise<M[]>;
@@ -731,17 +960,17 @@ declare class Relation<M extends Model, S = {}> {
731
960
  /** Groups the rows by attributes or `sql` fragments, for each group's calculations (#345). */
732
961
  group<const G extends GroupTerms<M>>(...terms: G): GroupedRelation<M, G>;
733
962
  /**
734
- * The number of records, as Rails' `size`: a loaded association's (built records included)
735
- * without a query; otherwise a `COUNT(*)`, plus an association's unsaved built records.
963
+ * The number of records: a loaded association's (built records included) without a query;
964
+ * otherwise a `COUNT(*)`, plus an association's unsaved built records.
736
965
  */
737
966
  size(): Promise<number>;
738
967
  /** Whether there are no records: a loaded association answers itself, else `!exists()`. */
739
968
  isEmpty(): Promise<boolean>;
740
- /** Whether there are any records: the opposite of `isEmpty()` (Rails' `any?`). */
969
+ /** Whether there are any records: the opposite of `isEmpty()`. */
741
970
  hasAny(): Promise<boolean>;
742
- /** Whether more than one record matches, as Rails' `many?`: one `COUNT` of at most two rows. */
971
+ /** Whether more than one record matches: one `COUNT` of at most two rows. */
743
972
  hasMoreThanOne(): Promise<boolean>;
744
- /** Whether exactly one record matches, as Rails' `one?`: one `COUNT` of at most two rows. */
973
+ /** Whether exactly one record matches: one `COUNT` of at most two rows. */
745
974
  hasExactlyOne(): Promise<boolean>;
746
975
  /** Whether any record matches, optionally with extra conditions. */
747
976
  exists(conditions?: Conditions<M> | SafeSql): Promise<boolean>;
@@ -780,7 +1009,7 @@ declare class Relation<M extends Model, S = {}> {
780
1009
  */
781
1010
  inBatches(options?: IterationOptions): AsyncIterable<Scoped<M, S>>;
782
1011
  /**
783
- * The SQL `toArray()` sends, and its bound values, without sending it (Rails' `to_sql`). Values
1012
+ * The SQL `toArray()` sends, and its bound values, without sending it. Values
784
1013
  * are never inlined into the SQL (ADR-0006), and none are redacted, filtered attributes included.
785
1014
  */
786
1015
  toSql(): QuerySql;
@@ -788,161 +1017,22 @@ declare class Relation<M extends Model, S = {}> {
788
1017
  [inspectCustom](depth: number, options: InspectOptions, inspect: Inspect): string;
789
1018
  toArray(): Promise<M[]>;
790
1019
  }
791
- /**
792
- * An association's scope, as Rails' `has_many :posts, -> { order(:created_at) }`: it receives
793
- * the target's Relation, with its scopes, and returns a narrowed one.
794
- */
795
- type AssociationScope<C extends ModelClass> = (relation: Scoped<InstanceType<C>, ScopesOf<C>>) => unknown;
796
- /** What an association declaration takes: the keys that link the Models, and a scope. */
797
- interface AssociationOptions<C extends ModelClass = ModelClass> {
798
- /**
799
- * The attribute holding the link: on the owner for belongsTo, on the target otherwise.
800
- * Inferred when left out, as Rails does: a belongsTo's name + `Id` (`author` → `authorId`),
801
- * or for a hasMany/hasOne the owner's `modelName` + `Id` (`User` → `userId`).
802
- */
803
- foreignKey?: string;
804
- /** The attribute the foreign key points at; defaults to the pointed-at Model's primary key. */
805
- primaryKey?: string;
806
- /** Narrows or orders the target's records for this association: `(q) => q.order(…)`. */
807
- scope?: AssociationScope<C>;
808
- /** What destroying the owner does to this association's records (hasMany and hasOne). */
809
- dependent?: Dependent;
810
- /**
811
- * Saving the owner also saves this association's loaded records that changed, and destroys
812
- * those marked with `markForDestruction()`, as Rails' `autosave: true` does (#37).
813
- */
814
- autosave?: true;
815
- /**
816
- * The target's association that points back (#62), whose record is this one, so records loaded
817
- * or built through either side point at each other without a query: a hasMany's or hasOne's
818
- * belongsTo, or a belongsTo's hasOne. Inferred when left out; `false` turns it off.
819
- */
820
- inverseOf?: string | false;
821
- }
822
- /**
823
- * What an association through another takes (#59): `projects = hasMany(Project, { through:
824
- * "assignments" })`. Its keys and `autosave` are its hops'; a hasMany's `dependent` acts on its
825
- * join records (`ThroughDependent`).
826
- */
827
- interface ThroughOptions<C extends ModelClass = ModelClass> {
828
- /** The owner's association it reaches its records through: one to the join Model. */
829
- through: string;
1020
+ /** What `generatesTokenFor` takes: how long its tokens last, and a value they depend on. */
1021
+ interface TokenForOptions<R> {
1022
+ /** How long a token lasts: `{ days: 1 }`. Forever unless given. */
1023
+ readonly expiresIn?: Duration;
830
1024
  /**
831
- * The association of the `through` association's Model that reaches the records. Left out, it's
832
- * the one named as this association, singular or plural (`projects` → `project`, `projects`).
1025
+ * A value of the record's that its tokens depend on (`(user) => user.email`): a token finds
1026
+ * its record only while the value is the same as when it was made. Compared as JSON; a
1027
+ * token holds a fingerprint of it, never the value.
833
1028
  */
834
- source?: string;
835
- /** Narrows or orders its records: `(q) => q.order(…)`. */
836
- scope?: AssociationScope<C>;
837
- }
838
- /**
839
- * What destroying the owner, and removing records with `delete`, do to a hasMany through
840
- * another's join records (#434): destroy them, callbacks included, or delete their rows.
841
- */
842
- type ThroughDependent = "destroy" | "deleteAll";
843
- /** Rails' `dependent:` strategies for a hasMany. */
844
- type HasManyDependent = "destroy" | "deleteAll" | "nullify" | "restrictWithException" | "restrictWithError";
845
- /** Rails' `dependent:` strategies for a hasOne: `delete` in place of `deleteAll`. */
846
- type HasOneDependent = "destroy" | "delete" | "nullify" | "restrictWithException" | "restrictWithError";
847
- type Dependent = HasManyDependent | HasOneDependent;
848
- /**
849
- * `await post.author()`: the owning record, or null. `post.author.set(user)` points the post at
850
- * another record (Rails' `post.author = user`), and `build`/`create` make a new one for it.
851
- */
852
- interface BelongsTo<C extends ModelClass> {
853
- (): Promise<InstanceType<C> | null>;
854
- set(record: InstanceType<C> | null): void;
855
- build(attributes?: Partial<AttributesOf<InstanceType<C>>>): InstanceType<C>;
856
- create(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
857
- createOrThrow(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
1029
+ readonly dependsOn?: (record: R) => unknown;
858
1030
  }
859
1031
  /**
860
- * `await remark.commentable()`: the record a polymorphic belongsTo points at (#60), of whichever
861
- * listed Model its type names, or null. `remark.commentable.set(post)` points it at another,
862
- * setting both the type and the key. There's no `build` or `create`: which Model to make isn't
863
- * known.
864
- */
865
- interface PolymorphicBelongsTo<C extends ModelClass> {
866
- (): Promise<InstanceType<C> | null>;
867
- set(record: InstanceType<C> | null): void;
868
- }
869
- /**
870
- * `await user.profile()`: the one associated record, or null. `await user.profile.set(profile)`
871
- * gives the user another (Rails' `user.profile = profile`), and `build(attrs)` and
872
- * `create(attrs)` make a new one pointing at the user (Rails' `build_profile`). Each replaces the
873
- * old record, removed by `dependent:` when the new one is written.
1032
+ * An around callback: `next` runs the rest of the write, resolving once the record's write is kept
1033
+ * and its inner callbacks have run.
874
1034
  */
875
- interface HasOne<C extends ModelClass> {
876
- (): Promise<InstanceType<C> | null>;
877
- set(record: InstanceType<C> | null): Promise<void>;
878
- build(attributes?: Partial<AttributesOf<InstanceType<C>>>): InstanceType<C>;
879
- create(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
880
- createOrThrow(attributes?: Partial<AttributesOf<InstanceType<C>>>): Promise<InstanceType<C>>;
881
- }
882
- /**
883
- * `user.posts()`: a Relation of the associated records, with the target's scopes, and the
884
- * collection methods (`push`, `delete`, `destroy`, `clear`) that only the association itself has.
885
- */
886
- type HasMany<C extends ModelClass> = () => HasManyCollection<InstanceType<C>, ScopesOf<C>>;
887
- /**
888
- * `note.tags()` for an association through another (#59): a Relation of its records, which
889
- * reads and preloads as any hasMany's, with the collection methods. Its writes go to its join
890
- * records (#434): `push`, `build` and `create` make one, and `delete`, `destroy`, `clear`, and
891
- * its own `deleteAll` and `destroyAll` remove them. Inserting and upserting, which make none, are typed `never`,
892
- * so it's still a Relation, for `or`, `merge` and a batch's `updateAll`.
893
- */
894
- type HasManyThrough<C extends ModelClass> = () => Scoped<InstanceType<C>, ScopesOf<C>> & CollectionMethods<InstanceType<C>> & { readonly [W in ThroughWrite]: never; };
895
- /** The writes a through association's own Relation refuses (#434): they make no join records. */
896
- type ThroughWrite = "insert" | "insertAll" | "upsert" | "upsertAll";
897
- /**
898
- * `await mark.note()` for a hasOne through another (#59): its record, or null. `set(note)`
899
- * points the owner's join record at another (#434); as in Rails, it has no `build` or `create`.
900
- */
901
- interface HasOneThrough<C extends ModelClass> {
902
- (): Promise<InstanceType<C> | null>;
903
- /**
904
- * Points the owner's join record at `record`, saved at once on a saved owner, or builds one
905
- * through the association it goes through; `null` destroys the join record.
906
- */
907
- set(record: InstanceType<C> | null): Promise<void>;
908
- /** Type-only: marks the accessor, so a record method returning a Promise isn't one. */
909
- readonly [throughTarget]: C;
910
- }
911
- declare const throughTarget: unique symbol;
912
- /** What a hasMany accessor returns: its Relation, with the collection methods. */
913
- type HasManyCollection<M extends Model, S = {}> = Scoped<M, S> & CollectionMethods<M>;
914
- /** What `paginate()` takes: which page, how many records on it, and whether to count them all. */
915
- interface PageOptions {
916
- /** The page, from 1: a number, or untrusted text such as a query string's `"2"`. */
917
- page?: number | string | null;
918
- /** Records on a page, a number or text as `page` is. */
919
- perPage?: number | string | null;
920
- /** `false` skips the `COUNT`: the page has no `total` or `totalPages`. */
921
- count?: boolean;
922
- }
923
- /** A page of records, from `paginate({ count: false })`: where it is, but no total. */
924
- interface CountlessPage<M extends Model> {
925
- records: M[];
926
- page: number;
927
- perPage: number;
928
- hasNext: boolean;
929
- hasPrevious: boolean;
930
- }
931
- /** A page of records, from `paginate()`, with the total it's a page of. */
932
- interface Page<M extends Model> extends CountlessPage<M> {
933
- total: number;
934
- totalPages: number;
935
- }
936
- /** `paginate` as a static of every Model, typed for the class it's called on. */
937
- interface PaginateStatic {
938
- <C extends QueryableClass>(this: C, options: PageOptions & {
939
- count: false;
940
- }): Promise<CountlessPage<InstanceType<C>>>;
941
- <C extends QueryableClass>(this: C, options?: PageOptions & {
942
- count?: true;
943
- }): Promise<Page<InstanceType<C>>>;
944
- <C extends QueryableClass>(this: C, options: PageOptions): Promise<Page<InstanceType<C>> | CountlessPage<InstanceType<C>>>;
945
- }
1035
+ type AroundCallback<R> = (record: R, next: () => Promise<void>) => unknown;
946
1036
  /** A validation context: `"create"`, `"update"`, or a name the app chooses (`"signup"`). */
947
1037
  type ValidationContext = "create" | "update" | (string & {});
948
1038
  /** One context, or several: of those `X` names, when it's a Model's. */
@@ -967,7 +1057,7 @@ interface SaveOptions {
967
1057
  /** A Model's Relation, as its statics return them: `Product.where(…)` is `Product.all().where(…)`. */
968
1058
  type RelationOf<C extends ModelClass> = Scoped<InstanceType<C>, ScopesOf<C>>;
969
1059
  /** The Relation methods every Model has as statics (besides the overloaded ones). */
970
- declare const relationMethods: readonly ["where", "whereNot", "rewhere", "unscope", "only", "excluding", "none", "or", "order", "reorder", "limit", "offset", "select", "distinct", "includes", "joins", "leftJoins", "createWith", "build", "insert", "insertAll", "upsert", "upsertAll", "updateAll", "touchAll", "deleteAll", "destroyAll", "destroyBy", "deleteBy", "create", "createOrThrow", "findBy", "findByOrThrow", "findSoleBy", "findOrCreateBy", "findOrCreateByOrThrow", "findOrInitializeBy", "createOrFindBy", "createOrFindByOrThrow", "first", "last", "take", "firstOrThrow", "lastOrThrow", "takeOrThrow", "sole", "count", "average", "size", "isEmpty", "hasAny", "hasMoreThanOne", "hasExactlyOne", "exists", "ids", "toArray", "toSql", "findEach", "findInBatches", "inBatches"];
1060
+ declare const relationMethods: readonly ["where", "whereNot", "rewhere", "unscope", "only", "excluding", "none", "or", "order", "reorder", "limit", "offset", "select", "distinct", "includes", "joins", "leftJoins", "createWith", "build", "insert", "insertAll", "upsert", "upsertAll", "updateAll", "touchAll", "deleteAll", "destroyAll", "destroyBy", "deleteBy", "create", "createOrThrow", "findBy", "findByOrThrow", "findSoleBy", "findSigned", "findSignedOrThrow", "findByTokenFor", "findByTokenForOrThrow", "findOrCreateBy", "findOrCreateByOrThrow", "findOrInitializeBy", "createOrFindBy", "createOrFindByOrThrow", "first", "last", "take", "firstOrThrow", "lastOrThrow", "takeOrThrow", "sole", "count", "average", "size", "isEmpty", "hasAny", "hasMoreThanOne", "hasExactlyOne", "exists", "ids", "toArray", "toSql", "findEach", "findInBatches", "inBatches"];
971
1061
  /** A Relation method with no overloads, by name. */
972
1062
  type RelationMethod = (typeof relationMethods)[number];
973
1063
  /**
@@ -996,7 +1086,7 @@ interface OverloadedStatics {
996
1086
  <C extends QueryableClass, K extends OrderedAttribute<InstanceType<C>> | SafeSql>(this: C, operation: "minimum" | "maximum", attribute: K): Promise<CalculatedValue<InstanceType<C>, K, unknown> | null>;
997
1087
  };
998
1088
  paginate: PaginateStatic;
999
- /** The class's Relation ordered by `attribute`'s place in `values` (#350), as Rails' `in_order_of`. */
1089
+ /** The class's Relation ordered by `attribute`'s place in `values` (#350). */
1000
1090
  inOrderOf: <C extends QueryableClass, K extends keyof AttributesOf<InstanceType<C>> & string>(this: C, attribute: K, values: readonly AttributesOf<InstanceType<C>>[K][], options?: InOrderOfOptions) => RelationOf<C>;
1001
1091
  group: <C extends QueryableClass, const G extends GroupTerms<InstanceType<C>>>(this: C, ...terms: G) => GroupedRelation<InstanceType<C>, G>;
1002
1092
  find: {
@@ -1060,6 +1150,11 @@ type CallbackStatic = <C extends AbstractModelClass>(this: C, callback: Callback
1060
1150
  * `this.beforeValidation((record) => …, { on: "create" })`.
1061
1151
  */
1062
1152
  type ValidationCallbackStatic = <C extends AbstractModelClass>(this: C, callback: Callback<InstanceType<C>>, options?: ValidationCallbackOptions<ContextOf<C>>) => void;
1153
+ /**
1154
+ * Declares a callback that runs synchronously as a record is loaded or built: nothing awaits it,
1155
+ * so its type refuses one that returns a promise (an `async` one), as running it does.
1156
+ */
1157
+ type SyncCallbackStatic = <C extends AbstractModelClass>(this: C, callback: (record: InstanceType<C>) => string | number | bigint | boolean | symbol | null | undefined) => void;
1063
1158
  /** Every callback kind as a static, each documented here, so its doc comment shows on hover. */
1064
1159
  interface CallbackStatics {
1065
1160
  /**
@@ -1095,6 +1190,33 @@ interface CallbackStatics {
1095
1190
  * its batch). Not for a validation failure or an `abort()`: nothing was sent then.
1096
1191
  */
1097
1192
  afterRollback: CallbackStatic;
1193
+ /**
1194
+ * Runs as a record is loaded from a row (#49): by a query, an association read, a preload or
1195
+ * `reload`, before `afterInitialize`. Synchronous: one that returns a promise throws `TypeError`.
1196
+ */
1197
+ afterFind: SyncCallbackStatic;
1198
+ /**
1199
+ * Runs as a record is built (after `build`'s `init`) or loaded (after `afterFind`) (#49).
1200
+ * Synchronous: one that returns a promise throws `TypeError`.
1201
+ */
1202
+ afterInitialize: SyncCallbackStatic;
1203
+ }
1204
+ /** An around callback static (#48): `this.aroundSave(async (record, next) => { …; await next(); … })`. */
1205
+ type AroundCallbackStatic = <C extends AbstractModelClass>(this: C, callback: AroundCallback<InstanceType<C>>) => void;
1206
+ /** The around callbacks as statics: each wraps the rest of a save or destroy (#48). */
1207
+ interface AroundStatics {
1208
+ /**
1209
+ * Wraps a save, after `beforeSave`: `await next()` runs `beforeCreate` or `beforeUpdate`, the
1210
+ * write, and `afterCreate` or `afterUpdate`; `afterSave` runs once it's finished. One that
1211
+ * doesn't call `next()` stops the save, as `abort()` does.
1212
+ */
1213
+ aroundSave: AroundCallbackStatic;
1214
+ /** Wraps a create, after `beforeCreate`: `await next()` runs the INSERT; then `afterCreate`. */
1215
+ aroundCreate: AroundCallbackStatic;
1216
+ /** Wraps an update, after `beforeUpdate`: `await next()` runs the UPDATE; then `afterUpdate`. */
1217
+ aroundUpdate: AroundCallbackStatic;
1218
+ /** Wraps a destroy, after `beforeDestroy`: `await next()` runs the DELETE; then `afterDestroy`. */
1219
+ aroundDestroy: AroundCallbackStatic;
1098
1220
  }
1099
1221
  /** The commit callbacks as statics: each runs after every after-callback of its write. */
1100
1222
  interface CommitStatics {
@@ -1109,12 +1231,49 @@ interface CommitStatics {
1109
1231
  /** Runs once a destroy is kept, after every after-callback. */
1110
1232
  afterDestroyCommit: CallbackStatic;
1111
1233
  }
1234
+ /** A static that finds a record by `password`'s reset token, typed `never` for a Model without one. */
1235
+ type ResetTokenStatic<Found> = <C extends QueryableClass>(this: C, token: PasswordResetTokenArgument<SpecsOf<InstanceType<C>>>) => Promise<InstanceType<C> | Found>;
1236
+ /** The finders by a secure password's reset token (#517), for `password`. */
1237
+ interface ResetTokenStatics {
1238
+ findByPasswordResetToken: ResetTokenStatic<null>;
1239
+ findByPasswordResetTokenOrThrow: ResetTokenStatic<never>;
1240
+ }
1112
1241
  /**
1113
1242
  * The class Model extends, for its statics' types only: at runtime it's empty, and
1114
1243
  * `defineStatics` puts the statics on Model itself, where scopes look for the names they
1115
1244
  * can't take.
1116
1245
  */
1117
- declare const ModelStatics: (abstract new () => object) & RelationStatics & OverloadedStatics & KeyedWriteStatics & CallbackStatics & CommitStatics;
1246
+ declare const ModelStatics: (abstract new () => object) & ResetTokenStatics & RelationStatics & OverloadedStatics & KeyedWriteStatics & CallbackStatics & AroundStatics & CommitStatics;
1247
+ /** What a Model's `signingSecret` reads secrets from: the Worker's env, by name. */
1248
+ type SigningEnv = Readonly<Record<string, string | undefined>>;
1249
+ /** What `signingSecret` returns: a secret, or a list of them, newest first; unset ones skipped. */
1250
+ type SigningSecrets = string | readonly (string | undefined)[] | undefined;
1251
+ /** The token methods Model's records have, and the secret their tokens are signed with. */
1252
+ declare abstract class RecordTokens extends ModelStatics {
1253
+ /**
1254
+ * The secret this Model's tokens are signed with, from the Worker's env (or `process.env`
1255
+ * outside a Worker): `SECRET_KEY_BASE` unless overridden, on the app's base class. A list
1256
+ * rotates secrets: the first signs, and every one verifies. Each is at least 32 bytes.
1257
+ */
1258
+ static signingSecret(env: SigningEnv): SigningSecrets;
1259
+ /**
1260
+ * Declares tokens for a purpose, in `static {}`: `this.generatesTokenFor("emailConfirmation", {
1261
+ * expiresIn: { days: 1 }, dependsOn: (user) => user.email })`. A record makes one with
1262
+ * `generateTokenFor(purpose)`, and `findByTokenFor(purpose, token)` finds it again until it
1263
+ * expires or the value it depends on changes. Declaring a purpose again replaces it.
1264
+ */
1265
+ static generatesTokenFor<C extends AbstractModelClass>(this: C, purpose: string, options?: TokenForOptions<InstanceType<C>>): void;
1266
+ /**
1267
+ * A token for `purpose`, which its Model declares with `generatesTokenFor`, for
1268
+ * `findByTokenFor` to find this saved record by. `RecordNotSaved` for a new record.
1269
+ */
1270
+ generateTokenFor(purpose: string): Promise<string>;
1271
+ /**
1272
+ * This saved record's primary key, signed with its Model's secret, for `findSigned` to find it
1273
+ * by: for a purpose, if given, and until it expires, if given. `RecordNotSaved` for a new record.
1274
+ */
1275
+ signedId(options?: SignedIdOptions): Promise<string>;
1276
+ }
1118
1277
  /**
1119
1278
  * The built-in type a spec names: `"integer"` for `"integer"` or `{ type: "integer" }`, and
1120
1279
  * `"custom"` for a custom type, given bare or as `{ type }`.
@@ -1141,7 +1300,7 @@ type BooleanAttributeKey<R> = AttributeKeyOf<R, "boolean">;
1141
1300
  * The record methods that change one attribute, between Model and its statics: Model's records
1142
1301
  * have them, and model.ts stays the record class's own.
1143
1302
  */
1144
- declare abstract class AttributeWrites extends ModelStatics {
1303
+ declare abstract class AttributeWrites extends RecordTokens {
1145
1304
  /** Adds `by` (one by default) to a number attribute, null counting as zero; doesn't save. */
1146
1305
  increment<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number): R;
1147
1306
  /** Takes `by` (one by default) from a number attribute, null counting as zero; doesn't save. */
@@ -1149,39 +1308,39 @@ declare abstract class AttributeWrites extends ModelStatics {
1149
1308
  /** Flips a boolean attribute, null becoming `true`; doesn't save. */
1150
1309
  toggle<R extends Model>(this: R, name: BooleanAttributeKey<R>): R;
1151
1310
  /**
1152
- * Writes these attributes straight to the row, with no validation, callback or `updatedAt`,
1153
- * and leaves the record clean for them, as Rails' `update_columns`. Resolves to whether there
1154
- * was a row to write. A new record is `RecordNotSaved`.
1311
+ * Writes these attributes straight to the row, with no validation, callback or `updatedAt`, and
1312
+ * leaves the record clean for them. Resolves to whether there was a row to write. A new record is
1313
+ * `RecordNotSaved`.
1155
1314
  */
1156
1315
  updateColumns<R extends Model>(this: R, attributes: Partial<AttributesOf<R>>): Promise<boolean>;
1157
1316
  /** `updateColumns` for one attribute. */
1158
1317
  updateColumn<R extends Model, K extends AttributeKey$1<R>>(this: R, name: K, value: AttributesOf<R>[K]): Promise<boolean>;
1159
1318
  /**
1160
1319
  * Adds `by` to a number attribute in the row, as `SET x = COALESCE(x, 0) + by`, so concurrent
1161
- * writes all count, with no validation, callback or `updatedAt`; the record then holds the
1162
- * row's new value. An unsaved change to it is added too, as Rails' `increment!`. With
1163
- * `{ touch }`, the same UPDATE sets `updatedAt` (and any datetime attributes named) to now, and
1164
- * the record holds them (#50). Resolves to whether there was a row to write.
1320
+ * writes all count, with no validation, callback or `updatedAt`; the record then holds the row's
1321
+ * new value. An unsaved change to it is added too. With `{ touch }`, the same UPDATE sets
1322
+ * `updatedAt` (and any datetime attributes named) to now, and the record holds them (#50).
1323
+ * Resolves to whether there was a row to write.
1165
1324
  */
1166
1325
  incrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number, { touch }?: CounterOptions<R>): Promise<boolean>;
1167
1326
  /** `incrementColumn`, taking `by` away. */
1168
1327
  decrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number, { touch }?: CounterOptions<R>): Promise<boolean>;
1169
1328
  /**
1170
- * Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`), straight to
1171
- * the row, with no validation or save callback, as Rails' `touch`. Resolves to whether there
1172
- * was a row to write.
1329
+ * Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`), straight to the
1330
+ * row, with no validation or save callback. Resolves to whether there was a row to write. Inside
1331
+ * its Model's `noTouching` block, it writes nothing (#496).
1173
1332
  */
1174
1333
  touch<R extends Model>(this: R, ...args: TouchArguments<R>): Promise<boolean>;
1175
1334
  /**
1176
1335
  * Writes a boolean attribute's flipped value straight to the row, as `updateColumn` does: no
1177
- * validation or callback, unlike Rails' `toggle!`, which runs the save callbacks.
1336
+ * validation or callback. Flip the attribute and `save()` to run the save callbacks.
1178
1337
  */
1179
1338
  toggleColumn<R extends Model>(this: R, name: BooleanAttributeKey<R>): Promise<boolean>;
1180
1339
  }
1181
1340
  /** What `updateCounters` adds to each number attribute: `{ viewCount: 1 }`. */
1182
1341
  type Counters<R> = { [K in NumberAttributeKey<R>]?: number; };
1183
1342
  /**
1184
- * What a counter's write also sets to now (#61), as Rails' `touch:`: `true` for `updatedAt`, or
1343
+ * What a counter's write also sets to now (#61): `true` for `updatedAt`, or
1185
1344
  * a datetime attribute's name, or several, set with `updatedAt`.
1186
1345
  */
1187
1346
  type Touch<R> = true | DatetimeAttributeKey<R> | readonly DatetimeAttributeKey<R>[];
@@ -1392,12 +1551,12 @@ type Permitted<C extends ModelClass, K extends string> = Partial<Pick<Attributes
1392
1551
  interface AttributeConversions<T> {
1393
1552
  /**
1394
1553
  * `input` as the attribute's JavaScript value, as assigning it would: strict, so `TypeError`
1395
- * naming the Model and attribute when it can't be. `null` stays `null`; `undefined` throws.
1554
+ * naming the Model and attribute when it can't be, and normalized (#354). `null` stays `null`; `undefined` throws.
1396
1555
  * Nothing is floored: a `Date` with milliseconds keeps them, whatever the attribute's `storage`.
1397
1556
  */
1398
1557
  readonly cast: (input: unknown) => T;
1399
1558
  /**
1400
- * `input`, cast, as D1 stores it: an ISO string, an integer for a `storage` attribute (seconds
1559
+ * `input`, cast and normalized, as D1 stores it: an ISO string, an integer for a `storage` attribute (seconds
1401
1560
  * are floored), `0` or `1`, JSON text, bytes for a `binary` attribute, or a custom type's value
1402
1561
  * as its stored type keeps it (#20). The value `column(attribute).value(input)` binds inside
1403
1562
  * an `sql` fragment; `undefined` throws as assigning it does.
@@ -1419,6 +1578,11 @@ interface AttributeConversions<T> {
1419
1578
  type FilterAttribute = string | RegExp;
1420
1579
  /** The value D1 binds. */
1421
1580
  declare function boundValue(param: unknown): unknown;
1581
+ /**
1582
+ * `S` as attribute specs: itself, or when it isn't (a spec that's a compile error), widened, so
1583
+ * `define` still gives a class to extend and the error stays on the spec.
1584
+ */
1585
+ type SpecsOrWidened<S> = S extends AttributeSpecs ? S : S & AttributeSpecs;
1422
1586
  /** An override written out: the parts of a spec it may change (not the column), any left out or `undefined` unchanged. */
1423
1587
  type SpecOverride = Partial<Omit<SpecObject, "column">>;
1424
1588
  /** One table in a generated schema: its attributes, and which is the primary key. */
@@ -1438,28 +1602,46 @@ type EnumOptions = Pick<SpecOverride, "prefix" | "suffix" | "scopes" | "instance
1438
1602
  type AttributeOverride = AttributeType | AnyCustomType | (Pick<SpecOverride, "null"> & {
1439
1603
  type?: "string";
1440
1604
  storage?: never;
1605
+ virtual?: false;
1441
1606
  /** Or `true`: a generated enum's names, with its methods; `false`: none of it (#64). */
1442
1607
  enum?: TextEnum | boolean;
1608
+ /** A random token, generated for a new record (#355). */
1609
+ secureToken?: boolean | SecureTokenOptions;
1443
1610
  } & EnumOptions & ValueSource) | (Pick<SpecOverride, "null" | "default"> & {
1444
1611
  type?: "integer";
1445
1612
  generateId?: false;
1446
1613
  storage?: never;
1614
+ virtual?: false;
1447
1615
  enum: IntegerEnum;
1448
1616
  } & EnumOptions) | (Pick<SpecOverride, "null" | "default"> & {
1449
1617
  type: Exclude<AttributeType, "string" | "datetime">;
1450
1618
  generateId?: false;
1451
1619
  storage?: never;
1452
1620
  enum?: never;
1621
+ virtual?: false;
1453
1622
  }) | (Pick<SpecOverride, "null" | "default" | "storage"> & {
1454
1623
  type: "datetime";
1455
1624
  generateId?: false;
1456
1625
  enum?: never;
1626
+ virtual?: false;
1457
1627
  }) | (Pick<SpecOverride, "null" | "default"> & {
1458
1628
  type: AnyCustomType;
1459
1629
  generateId?: false;
1460
1630
  storage?: never;
1461
1631
  enum?: never;
1462
- });
1632
+ virtual?: false;
1633
+ }) | VirtualAttribute | AttributeAlias | SecurePasswordDeclaration;
1634
+ /**
1635
+ * An attribute that isn't a column (#356): its type, and optionally nullability and a default,
1636
+ * the only keys an attribute with no column has.
1637
+ */
1638
+ type VirtualAttribute = Pick<SpecOverride, "null" | "default"> & {
1639
+ type: AttributeType | AnyCustomType;
1640
+ virtual: true;
1641
+ generateId?: never;
1642
+ storage?: never;
1643
+ enum?: never;
1644
+ };
1463
1645
  /** The type a spec declares, written either way. */
1464
1646
  type TypeOf<S> = S extends AttributeType | AnyCustomType ? S : S extends {
1465
1647
  type: infer T;
@@ -1505,9 +1687,18 @@ type Overridden<S, O> = O extends AttributeType | AnyCustomType ? {
1505
1687
  null: O extends {
1506
1688
  null: infer N extends boolean;
1507
1689
  } ? N : NullOf<S>;
1508
- } & KeptEnumKeys<S, O> & GivenEnumKeys<O> : S;
1509
- /** A table's attributes after its overrides: changed ones merged, ignored ones gone. */
1510
- type OverriddenSpecs<A, O> = { -readonly [K in keyof A as K extends keyof O ? (O[K] extends false ? never : K) : K]: K extends keyof O ? Overridden<A[K], O[K]> : A[K]; };
1690
+ } & KeptEnumKeys<S, O> & GivenEnumKeys<O> & Pick<O, "secureToken" & keyof O> : S;
1691
+ /**
1692
+ * A table's attributes after its overrides: changed ones merged, ignored ones gone, and virtual
1693
+ * ones (#356), aliases (#509) and secure passwords' (#355) added.
1694
+ */
1695
+ type OverriddenSpecs<A, O> = ColumnSpecs<A, WithoutAliases<O>> & AliasSpecs<ColumnSpecs<A, WithoutAliases<O>>, O>;
1696
+ /** A table's attributes after the overrides that aren't aliases. */
1697
+ type ColumnSpecs<A, O> = { -readonly [K in keyof A as K extends keyof O ? (O[K] extends false ? never : K) : K]: K extends keyof O ? Overridden<A[K], O[K]> : A[K]; } & VirtualSpecs<A, O> & SecurePasswordSpecs<O>;
1698
+ /** The virtual attributes an override declares (#356): those not in the table, as declared. */
1699
+ type VirtualSpecs<A, O> = { -readonly [K in keyof O as K extends keyof A ? never : O[K] extends {
1700
+ virtual: true;
1701
+ } ? K : never]: O[K]; };
1511
1702
  /** `S` as attribute specs, without widening it to an index signature (which would type any name). */
1512
1703
  type AsSpecs<S> = S extends AttributeSpecs ? S : never;
1513
1704
  /**
@@ -1604,7 +1795,7 @@ type AttributesOf<M> = M extends {
1604
1795
  readonly [attributeTypes]?: infer A;
1605
1796
  } ? A : never;
1606
1797
  /**
1607
- * The library's base class, as Rails' `ActiveRecord::Base`: an app's base class extends it, and
1798
+ * The library's base class: an app's base class extends it, and
1608
1799
  * methods, statics, callbacks and scopes declared there are shared by every Model built on it.
1609
1800
  * It has no table, so it's never used as a Model itself.
1610
1801
  */
@@ -1612,7 +1803,7 @@ declare class Model extends AttributeWrites {
1612
1803
  /** The table's name: inferred from `modelName` (`BlogPost` → `blog_posts`) unless set. */
1613
1804
  static table: string;
1614
1805
  /**
1615
- * The Model's name, as Rails' `model_name`: its class name unless set (`static modelName =
1806
+ * The Model's name: its class name unless set (`static modelName =
1616
1807
  * "BlogPost"`), so names inferred from it survive a bundler that renames classes.
1617
1808
  */
1618
1809
  static modelName: string;
@@ -1642,10 +1833,11 @@ declare class Model extends AttributeWrites {
1642
1833
  */
1643
1834
  static onQuery: QueryListener | undefined;
1644
1835
  /**
1645
- * Attributes whose values listeners and errors show as "[FILTERED]", as Rails'
1646
- * `filter_attributes`: an attribute whose snake_case name holds a string entry, lowercased
1647
- * or read in snake_case (`"apiKey"` as `api_key`), or matches a RegExp. Rails' defaults;
1648
- * replace them on the app's base class (#83).
1836
+ * Attributes whose values listeners and errors show as "[FILTERED]": an attribute
1837
+ * whose snake_case name holds a string entry, lowercased or read in snake_case (`"apiKey"` as
1838
+ * `api_key`), or matches a RegExp. The defaults cover common secret and personal names
1839
+ * (`password`, `token`, `email`, …); replace them on the app's base class (#83). A secure
1840
+ * password's attributes and digest, and a secure token, are filtered whatever it says (#355).
1649
1841
  */
1650
1842
  static filterAttributes: readonly FilterAttribute[];
1651
1843
  /**
@@ -1653,6 +1845,12 @@ declare class Model extends AttributeWrites {
1653
1845
  * names; none by default. `attributes()` still has them (#101).
1654
1846
  */
1655
1847
  static hiddenAttributes: readonly string[];
1848
+ /**
1849
+ * Runs `fn` with this Model's records not touched, nor those of the Models extending it
1850
+ * (`Model.noTouching` covers every Model): a belongsTo's `touch`
1851
+ * leaves them alone, and their `touch()` writes nothing. Resolves to what `fn` returns.
1852
+ */
1853
+ static noTouching<R>(fn: () => R | Promise<R>): Promise<R>;
1656
1854
  /** An attribute's name as error messages show it: from `humanAttributeNames`, or "Created at". */
1657
1855
  static humanAttributeName(attribute: string): string;
1658
1856
  /** Records on a page of `paginate()` when it isn't given `perPage` (#100). */
@@ -1673,51 +1871,70 @@ declare class Model extends AttributeWrites {
1673
1871
  * `class Visit extends Model.define({ path: "string" }) {}`. It's built on the class it's
1674
1872
  * called on, so a Model made with `ApplicationRecord.define({...})` shares the app's base.
1675
1873
  */
1676
- static define<B extends BaseClass, const A extends AttributeSpecs>(this: B, specs: A & ExactSpecs<A>): ModelBaseFor<A, B>;
1874
+ static define<B extends BaseClass, const A extends DeclaredAttributes>(this: B, specs: A & ExactSpecs<A>): ModelBaseFor<SpecsOrWidened<DefinedSpecs<WithSecurePasswords<A>>>, B>;
1677
1875
  /**
1678
- * Declares a scope, as Rails' `scope :active, -> { … }`: `static active = this.scope((q) =>
1876
+ * Declares a scope: `static active = this.scope((q) =>
1679
1877
  * q.where({ isActive: true }))`. It's a static (`User.active()`) and a Relation method
1680
1878
  * (`User.where(…).active()`), inherited like any static. Inside it, `q` has every Relation
1681
1879
  * method, but not the Model's other scopes (their types would refer to themselves).
1682
1880
  */
1683
1881
  static scope<C extends AbstractModelClass, A extends unknown[]>(this: C, body: (q: Relation<InstanceType<C>>, ...args: A) => Relation<InstanceType<C>>): ScopeStatic<A>;
1684
1882
  /**
1685
- * All of this Model's records, as Rails' `Product.all`: a Relation on the current database
1883
+ * All of this Model's records: a Relation on the current database
1686
1884
  * (the request's, set with `withDatabase`, or else the binding in its base class's schema).
1687
1885
  */
1688
1886
  static all<C extends QueryableClass>(this: C): Scoped<InstanceType<C>, ScopesOf<C>>;
1689
1887
  /**
1690
1888
  * Only the named attributes of untrusted input (a JSON body, `FormData` or
1691
- * `URLSearchParams`), as Rails' `params.permit`:
1889
+ * `URLSearchParams`):
1692
1890
  * `User.create(User.permit(await request.json(), "email", "name"))`. Every other key is
1693
1891
  * dropped, and each value is cast as assigning it would be.
1694
1892
  */
1695
1893
  static permit<C extends QueryableClass, K extends AttributeKey<InstanceType<C>>>(this: C, input: unknown, ...names: K[]): Permitted<C, K>;
1696
1894
  /**
1697
- * An enum's names, each with the value it's stored as, frozen (#340), as Rails' `Post.statuses`:
1895
+ * The record its other attributes find, if each secure password given is its own (#355):
1896
+ * `User.authenticateBy({ email, password })`, or null. When none is found, the password is
1897
+ * hashed anyway, so how long it takes doesn't say whether one exists. Without a secure
1898
+ * password, or an attribute to find the record by, it throws `TypeError`.
1899
+ */
1900
+ static authenticateBy<C extends QueryableClass>(this: C, attributes: AuthenticateByAttributes<SpecsOf<InstanceType<C>>, AttributesOf<InstanceType<C>>>): Promise<InstanceType<C> | null>;
1901
+ /**
1902
+ * An enum's names, each with the value it's stored as, frozen (#340):
1698
1903
  * `Post.enumValues("status")` is `{ draft: "draft", published: "published" }`.
1699
1904
  */
1700
1905
  static enumValues<C extends QueryableClass, K extends EnumAttributeKey<InstanceType<C>>>(this: C, attribute: K): EnumMapping<EnumOf<InstanceType<C>, K>>;
1701
1906
  /**
1702
- * An attribute's conversions, for SQL d1-record doesn't write, as Rails' `type_for_attribute`:
1907
+ * An attribute's conversions, for SQL the library doesn't write:
1703
1908
  * `Post.typeForAttribute("publishedAt").serialize(date)` is what `publishedAt` stores a `Date`
1704
- * as, whatever its `storage`; `cast` and `deserialize` go the other way.
1909
+ * as, whatever its `storage`; `cast` and `deserialize` go the other way. `cast` and `serialize`
1910
+ * normalize the value, as assigning it does (#354).
1705
1911
  */
1706
1912
  static typeForAttribute<C extends QueryableClass, K extends AttributeKey<InstanceType<C>>>(this: C, name: K): AttributeConversions<AttributesOf<InstanceType<C>>[K]>;
1707
1913
  /**
1708
- * Declares a default scope (#25), as Rails' `default_scope { … }`, in `static {}`:
1914
+ * `value` as assigning it to `name` keeps it: cast, then normalized (#354), so
1915
+ * `Account.normalizeValueFor("email", " Jane@Example.com")` is `"jane@example.com"`.
1916
+ */
1917
+ static normalizeValueFor<C extends QueryableClass, K extends AttributeKey<InstanceType<C>>>(this: C, name: K, value: unknown): AttributesOf<InstanceType<C>>[K];
1918
+ /**
1919
+ * Declares a default scope (#25), in `static {}`:
1709
1920
  * `this.defaultScope((q) => q.where({ deletedAt: null }))`. Every query on the Model, its
1710
1921
  * associations' included, starts from it, and new records take its equality values. Several
1711
1922
  * are applied in order; a subclass adds to its parent's. `unscoped()` leaves them out.
1712
1923
  */
1713
1924
  static defaultScope<C extends AbstractModelClass>(this: C, body: (q: Relation<InstanceType<C>>) => Relation<InstanceType<C>>): void;
1714
1925
  /**
1715
- * All of this Model's records without its default scopes (#25), as Rails' `Product.unscoped`,
1926
+ * All of this Model's records without its default scopes (#25),
1716
1927
  * on the current database. Only a static: a Relation keeps what it has.
1717
1928
  */
1718
1929
  static unscoped<C extends QueryableClass>(this: C): Scoped<InstanceType<C>, ScopesOf<C>>;
1719
1930
  /** Declares a validation, e.g. `this.validates("email", { presence: true })` in `static {}`. */
1720
1931
  static validates<C extends AbstractModelClass>(this: C, attribute: keyof AttributesOf<InstanceType<C>> & string, options: ValidationOptions<InstanceType<C>, ContextOf<C>>): void;
1932
+ /**
1933
+ * Declares a normalization (#354), e.g. `this.normalizes("email", { with: (email) =>
1934
+ * email.trim().toLowerCase() })` in `static {}`: each value assigned to the attribute, once
1935
+ * cast, becomes what `with` returns for it.
1936
+ */
1937
+ static normalizes<C extends AbstractModelClass, K extends AttributeKey<InstanceType<C>>>(this: C, attribute: K, options: NormalizeOptions<AttributesOf<InstanceType<C>>[K]>): void;
1721
1938
  /**
1722
1939
  * Declares that an association's records must be valid too, e.g.
1723
1940
  * `this.validatesAssociated("posts")` in `static {}`: an invalid one adds "is invalid" to the
@@ -1747,8 +1964,7 @@ declare class Model extends AttributeWrites {
1747
1964
  /** Whether the association is loaded: preloaded or already read, for the key held now. */
1748
1965
  isLoaded<K extends AssociationName<this>>(name: K): boolean;
1749
1966
  /**
1750
- * Loads the association again, replacing what's cached, and returns it: Rails'
1751
- * `reload_author`, or `user.posts.reload` for a hasMany.
1967
+ * Loads the association again, replacing what's cached, and returns its record or records.
1752
1968
  */
1753
1969
  reloadAssociation<K extends AssociationName<this>>(name: K): Promise<LoadedValue<this[K]>>;
1754
1970
  /** Why a callback last refused a save or destroy (`abort(reason)`); never copied into `errors`. */
@@ -1769,11 +1985,10 @@ declare class Model extends AttributeWrites {
1769
1985
  changes(): Changes;
1770
1986
  /** The changes the last successful save wrote; use it in after-save callbacks. */
1771
1987
  savedChanges(): Changes;
1772
- /** The attribute's value before its unsaved change, as stored (Rails' `attribute_was`). */
1988
+ /** The attribute's value before its unsaved change, as stored. */
1773
1989
  attributeWas<R extends Model, K extends AttributeKey<R>>(this: R, name: K): AttributesOf<R>[K];
1774
1990
  /**
1775
- * Whether the attribute has an unsaved change, optionally `from` and/or `to` given values
1776
- * (Rails' `attribute_changed?(name, from:, to:)`).
1991
+ * Whether the attribute has an unsaved change, optionally `from` and/or `to` given values.
1777
1992
  */
1778
1993
  isAttributeChanged<R extends Model, K extends AttributeKey<R>>(this: R, name: K, options?: ChangeOptions<AttributesOf<R>[K]>): boolean;
1779
1994
  /** Whether saving now would write a change to the attribute (for before-callbacks). */
@@ -1784,8 +1999,13 @@ declare class Model extends AttributeWrites {
1784
1999
  hasSavedChangeTo<R extends Model, K extends AttributeKey<R>>(this: R, name: K, options?: ChangeOptions<AttributesOf<R>[K]>): boolean;
1785
2000
  /** The attribute's value before the last save (its current stored value, if that didn't change it). */
1786
2001
  attributeBeforeLastSave<R extends Model, K extends AttributeKey<R>>(this: R, name: K): AttributesOf<R>[K];
1787
- /** Undoes unsaved changes to these attributes (all of them by default), as Rails' `restore_attributes`. */
2002
+ /** Undoes unsaved changes to these attributes (all of them by default). */
1788
2003
  restoreAttributes<R extends Model>(this: R, names?: readonly AttributeKey<R>[]): void;
2004
+ /**
2005
+ * Normalizes an attribute's value as assigning it again would (#354): for a value loaded from
2006
+ * a row stored before its normalization was declared, which loading leaves as it was.
2007
+ */
2008
+ normalizeAttribute<R extends Model>(this: R, name: AttributeKey<R>): void;
1789
2009
  /**
1790
2010
  * Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted,
1791
2011
  * or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as
@@ -1805,7 +2025,9 @@ declare class Model extends AttributeWrites {
1805
2025
  updateOrThrow(attributes: Partial<AttributesOf<this>>): Promise<true>;
1806
2026
  /**
1807
2027
  * Deletes the row and resolves to this record, now a read-only destroyed snapshot.
1808
- * A row that's already gone still counts. `false` means a `beforeDestroy` callback aborted.
2028
+ * A row that's already gone still counts. `false` means a `beforeDestroy` or `aroundDestroy`
2029
+ * callback aborted (or an `aroundDestroy` didn't call `next()`), or a `restrictWithError`
2030
+ * association refused.
1809
2031
  */
1810
2032
  destroy(): Promise<this | false>;
1811
2033
  /** Like `destroy()`, but throws `RecordNotDestroyed` instead of returning `false`. */
@@ -1814,7 +2036,7 @@ declare class Model extends AttributeWrites {
1814
2036
  reload(): Promise<this>;
1815
2037
  /**
1816
2038
  * Marks the record to be destroyed when its owner is saved, through an association declared
1817
- * `autosave: true`, as Rails' `mark_for_destruction` does. Nothing is written until then, and
2039
+ * `autosave: true`. Nothing is written until then, and
1818
2040
  * `reload()` clears the mark.
1819
2041
  */
1820
2042
  markForDestruction(): void;
@@ -1823,7 +2045,7 @@ declare class Model extends AttributeWrites {
1823
2045
  /** Not yet saved: built, or created but not persisted. */
1824
2046
  isNewRecord(): boolean;
1825
2047
  /**
1826
- * Whether its last save created it, as Rails' `previously_new_record?`: true in a create's
2048
+ * Whether its last save created it: true in a create's
1827
2049
  * after-callbacks and after it, false once it's saved again or destroyed.
1828
2050
  */
1829
2051
  isPreviouslyNewRecord(): boolean;
@@ -1831,13 +2053,21 @@ declare class Model extends AttributeWrites {
1831
2053
  isPersisted(): boolean;
1832
2054
  /** Deleted by this instance; a read-only snapshot of the row. */
1833
2055
  isDestroyed(): boolean;
2056
+ /**
2057
+ * Whether the record has the attribute `name` loaded: `false` for one
2058
+ * `select(...)` left out, whose read throws `MissingAttribute`, and for a name the Model doesn't
2059
+ * declare. A callback that runs for partial records, such as `afterFind`, checks it first.
2060
+ */
2061
+ hasAttribute(name: string): boolean;
1834
2062
  /** The record's attributes as a plain object of JavaScript values. */
1835
2063
  attributes(): Record<string, unknown>;
1836
2064
  /** Prints as `Name { attribute: value, … }` in a console, a log or a test failure (#104). */
1837
2065
  [inspectCustom](depth: number, options: InspectOptions, inspect: Inspect): string;
1838
2066
  /**
1839
2067
  * The loaded attributes as JSON-ready values (dates as ISO strings), without the Model's
1840
- * `hiddenAttributes`, for `Response.json(record)`.
2068
+ * `hiddenAttributes`, the virtual attributes its `confirmation` rules read, or its secrets: each
2069
+ * secure password, its confirmation, challenge and digest, and each secure token (#355), for
2070
+ * `Response.json(record)`.
1841
2071
  */
1842
2072
  toJSON(): Record<string, unknown>;
1843
2073
  }
@@ -1855,7 +2085,7 @@ type QueryableClass<M extends Model = Model> = ModelClass<M & {
1855
2085
  * What a generated declaration adds to a Model's records: its table's attributes `A`, with the
1856
2086
  * Model's `static attributes` overrides `O` applied, typed, and its enums' methods (#340).
1857
2087
  */
1858
- type TableAttributes<A extends AttributeSpecs, O = {}> = AttributeProperties<AsSpecs<OverriddenSpecs<A, O>>> & EnumMethods<OverriddenSpecs<A, O>> & {
2088
+ type TableAttributes<A extends AttributeSpecs, O = {}> = AttributeProperties<AsSpecs<OverriddenSpecs<A, O>>> & EnumMethods<OverriddenSpecs<A, O>> & SecurePasswordMethods<OverriddenSpecs<A, O>> & SecureTokenMethods<OverriddenSpecs<A, O>> & {
1859
2089
  readonly [attributeSpecs]: OverriddenSpecs<A, O>;
1860
2090
  readonly [attributeTypes]: AttributeProperties<AsSpecs<OverriddenSpecs<A, O>>>;
1861
2091
  };
@@ -1870,7 +2100,7 @@ type BaseClass = abstract new () => Model;
1870
2100
  * The base class `Model.define({...})` makes: records with the attributes `A`, built on `B` (the
1871
2101
  * library's base, or an app's), so they have its methods and statics too.
1872
2102
  */
1873
- type ModelBaseFor<A extends AttributeSpecs, B extends BaseClass = typeof Model> = (new () => InstanceType<B> & AttributeProperties<A> & EnumMethods<A> & {
2103
+ type ModelBaseFor<A extends AttributeSpecs, B extends BaseClass = typeof Model> = (new () => InstanceType<B> & AttributeProperties<A> & EnumMethods<A> & SecurePasswordMethods<A> & SecureTokenMethods<A> & {
1874
2104
  readonly [attributeTypes]: AttributeProperties<A>;
1875
2105
  readonly [attributeSpecs]: A;
1876
2106
  }) & Omit<B, "prototype"> & EnumStatics<A>;
@@ -1989,6 +2219,14 @@ interface ValidationOptions<R = never, X extends string = ValidationContext> {
1989
2219
  acceptance?: boolean | {
1990
2220
  accept: readonly unknown[];
1991
2221
  };
2222
+ /**
2223
+ * The value equals the virtual attribute named after it with `Confirmation`
2224
+ * (`emailConfirmation` for `email`), which must be declared; the failure is on that attribute,
2225
+ * "doesn't match Email". A null confirmation passes. `caseSensitive: false` ignores case.
2226
+ */
2227
+ confirmation?: boolean | {
2228
+ caseSensitive?: boolean;
2229
+ };
1992
2230
  /**
1993
2231
  * No other row has this value (checked in D1 through the record's Database). `scope` adds
1994
2232
  * attributes that must match too; `caseSensitive: false` compares with `lower()` (ASCII only).
@@ -2021,4 +2259,4 @@ interface ValidationOptions<R = never, X extends string = ValidationContext> {
2021
2259
  }
2022
2260
  /** The options of a `validatesAssociated(association, options)` call. */
2023
2261
  type AssociatedValidationOptions<R = never, X extends string = ValidationContext> = Pick<ValidationOptions<R, X>, "message" | "strict" | "if" | "unless" | "on" | "exceptOn">;
2024
- export { PolymorphicBelongsTo as $, databaseExecutor as A, Dialect as At, ValidationContexts as B, ComparisonOptions as Bt, QueryEvent as C, gte as Ct, SchemaAdapter as D, InOrderOfOptions as Dt, ConstraintFailure as E, QueryPart as Et, RecordStatement as F, SafeSql as Ft, BelongsTo as G, Page as H, NumberAttributeKey as I, column as It, HasManyDependent as J, HasMany as K, SaveOptions as L, sql$1 as Lt, BatchResults as M, Attribute as Mt, batch as N, ColumnReference as Nt, AnyDatabase as O, CompiledSql as Ot, Batch as P, ColumnValue as Pt, HasOneThrough as Q, ValidationCallbackOptions as R, Comparable as Rt, DatabaseExecutor as S, gt as St, Adapter as T, lte as Tt, PageOptions as U, CountlessPage as V, AssociationOptions as W, HasOne as X, HasManyThrough as Y, HasOneDependent as Z, TableSchema as _, OrderSpec as _t, ValidationOptions as a, Scoped as at, boundValue as b, Comparison as bt, AttributeErrorMessages as c, GroupedRelation as ct, RestrictMessages as d, Statement as dt, ThroughDependent as et, Model as f, WriteResult as ft, DatabaseSchema as g, InsertOptions as gt, TableAttributes as h, Conditions as ht, UniquenessOptions as i, ScopeMethods as it, BatchEntry as j, valueMark as jt, RelationsFor as k, QuerySql as kt, ErrorMessage as l, Init as lt, ScopeStatic as m, StatementResult as mt, LengthOptions as n, Relation as nt, Errors as o, IterationOptions as ot, ModelClass as p, Driver as pt, HasManyCollection as q, NumericalityOptions as r, Scope as rt, ValidationError as s, TouchOptions as st, AssociatedValidationOptions as t, ThroughOptions as tt, ErrorMessages as u, ReturnedRow as ut, TableSchemas as v, Returning as vt, QueryListener as w, lt as wt, AttributeConversions as x, between as xt, FilterAttribute as y, UpsertOptions as yt, ValidationContext as z, ComparisonBound as zt };
2262
+ export { TouchOptions as $, databaseExecutor as A, lt as At, SaveOptions as B, ColumnValue as Bt, QueryEvent as C, OrderSpec as Ct, SchemaAdapter as D, between as Dt, ConstraintFailure as E, Comparison as Et, RecordStatement as F, QuerySql as Ft, Relation as G, ComparisonBound as Gt, ValidationContext as H, column as Ht, DatetimeAttributeKey as I, Dialect as It, Scoped as J, Scope as K, ComparisonOptions as Kt, NumberAttributeKey as L, valueMark as Lt, BatchResults as M, QueryPart as Mt, batch as N, InOrderOfOptions as Nt, AnyDatabase as O, gt as Ot, Batch as P, CompiledSql as Pt, PageOptions as Q, SigningEnv as R, Attribute as Rt, DatabaseExecutor as S, InsertOptions as St, Adapter as T, UpsertOptions as Tt, ValidationContexts as U, sql$1 as Ut, ValidationCallbackOptions as V, SafeSql as Vt, TokenForOptions as W, Comparable as Wt, CountlessPage as X, IterationOptions as Y, Page as Z, TableSchema as _, HasOneThrough as _t, ValidationOptions as a, Statement as at, boundValue as b, ThroughOptions as bt, AttributeErrorMessages as c, StatementResult as ct, RestrictMessages as d, HasMany as dt, GroupedRelation as et, Model as f, HasManyCollection as ft, DatabaseSchema as g, HasOneDependent as gt, TableAttributes as h, HasOne as ht, UniquenessOptions as i, ReturnedRow as it, BatchEntry as j, lte as jt, RelationsFor as k, gte as kt, ErrorMessage as l, AssociationOptions as lt, ScopeStatic as m, HasManyThrough as mt, LengthOptions as n, SignedIdOptions as nt, Errors as o, WriteResult as ot, ModelClass as p, HasManyDependent as pt, ScopeMethods as q, NumericalityOptions as r, Init as rt, ValidationError as s, Driver as st, AssociatedValidationOptions as t, FindSignedOptions as tt, ErrorMessages as u, BelongsTo as ut, TableSchemas as v, PolymorphicBelongsTo as vt, QueryListener as w, Returning as wt, AttributeConversions as x, Conditions as xt, FilterAttribute as y, ThroughDependent as yt, SigningSecrets as z, ColumnReference as zt };