@forestfuture/active-record 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,6 +234,18 @@ interface QuerySql {
207
234
  sql: string;
208
235
  params: unknown[];
209
236
  }
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
+ };
210
249
  /** What Node's `util.inspect` passes a custom inspector; `src/` doesn't import Node's types. */
211
250
  interface InspectOptions {
212
251
  depth?: number | null;
@@ -218,7 +257,7 @@ type Inspect = (value: unknown, options?: InspectOptions) => string;
218
257
  declare const inspectCustom: unique symbol;
219
258
  /** What `inOrderOf` takes after its list: whether to keep only the records with a listed value. */
220
259
  interface InOrderOfOptions {
221
- /** 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. */
222
261
  filter?: boolean;
223
262
  }
224
263
  /** A part of a query `unscope` drops by name: `unscope("order")`. */
@@ -237,15 +276,15 @@ declare class Comparison<T = unknown> {
237
276
  }
238
277
  /** `attribute > value` */
239
278
  declare function gt<T>(value: T): Comparison<T>;
240
- /** `attribute >= value`, like Rails' endless range `value..` */
279
+ /** `attribute >= value`: everything from `value` on. */
241
280
  declare function gte<T>(value: T): Comparison<T>;
242
- /** `attribute < value`, like Rails' beginless range `...value` */
281
+ /** `attribute < value`: everything before `value`. */
243
282
  declare function lt<T>(value: T): Comparison<T>;
244
- /** `attribute <= value`, like Rails' beginless range `..value` */
283
+ /** `attribute <= value`: everything up to `value`, `value` included. */
245
284
  declare function lte<T>(value: T): Comparison<T>;
246
285
  /**
247
- * `attribute BETWEEN start AND end`, both ends included, like Rails' `start..end`. With
248
- * `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).
249
288
  */
250
289
  declare function between<T>(start: T, end: T, options?: {
251
290
  excludeEnd?: boolean;
@@ -285,16 +324,16 @@ type OrderSpec<M> = { [K in keyof AttributesOf<M>]?: OrderDirection | {
285
324
  direction: OrderDirection;
286
325
  nulls?: NullsPlacement;
287
326
  }; };
288
- /** What `user.posts()` has besides its Relation's methods, as Rails' collection proxy does. */
327
+ /** What `user.posts()` has besides its Relation's methods. */
289
328
  interface CollectionMethods<M extends Model> {
290
329
  /**
291
- * Adds records to the association (Rails' `<<`): sets each one's foreign key and saves them
330
+ * Adds records to the association: sets each one's foreign key and saves them
292
331
  * together, resolving to `false`, with nothing written, if one can't be saved.
293
332
  */
294
333
  push(...records: M[]): Promise<boolean>;
295
334
  /**
296
- * Removes records from the association by its `dependent:` strategy, as Rails' collection
297
- * `delete`: destroys them with `"destroy"`, deletes their rows with `"deleteAll"`, and
335
+ * Removes records from the association by its `dependent:` strategy:
336
+ * destroys them with `"destroy"`, deletes their rows with `"deleteAll"`, and
298
337
  * otherwise sets their foreign key to NULL. Resolves to the records.
299
338
  */
300
339
  delete(...records: M[]): Promise<M[]>;
@@ -317,7 +356,7 @@ interface CollectionMethods<M extends Model> {
317
356
  destroyAll(): Promise<M[]>;
318
357
  }
319
358
  /**
320
- * An association's scope, as Rails' `has_many :posts, -> { order(:created_at) }`: it receives
359
+ * An association's scope, such as `(q) => q.order({ createdAt: "asc" })`: it receives
321
360
  * the target's Relation, with its scopes, and returns a narrowed one.
322
361
  */
323
362
  type AssociationScope<C extends ModelClass> = (relation: Scoped<InstanceType<C>, ScopesOf<C>>) => unknown;
@@ -325,7 +364,7 @@ type AssociationScope<C extends ModelClass> = (relation: Scoped<InstanceType<C>,
325
364
  interface AssociationOptions<C extends ModelClass = ModelClass> {
326
365
  /**
327
366
  * The attribute holding the link: on the owner for belongsTo, on the target otherwise.
328
- * Inferred when left out, as Rails does: a belongsTo's name + `Id` (`author` → `authorId`),
367
+ * Inferred when left out: a belongsTo's name + `Id` (`author` → `authorId`),
329
368
  * or for a hasMany/hasOne the owner's `modelName` + `Id` (`User` → `userId`).
330
369
  */
331
370
  foreignKey?: string;
@@ -337,7 +376,7 @@ interface AssociationOptions<C extends ModelClass = ModelClass> {
337
376
  dependent?: Dependent;
338
377
  /**
339
378
  * Saving the owner also saves this association's loaded records that changed, and destroys
340
- * those marked with `markForDestruction()`, as Rails' `autosave: true` does (#37).
379
+ * those marked with `markForDestruction()` (#37).
341
380
  */
342
381
  autosave?: true;
343
382
  /**
@@ -368,14 +407,14 @@ interface ThroughOptions<C extends ModelClass = ModelClass> {
368
407
  * another's join records (#434): destroy them, callbacks included, or delete their rows.
369
408
  */
370
409
  type ThroughDependent = "destroy" | "deleteAll";
371
- /** Rails' `dependent:` strategies for a hasMany. */
410
+ /** What a hasMany's `dependent:` does to its records when the owner is destroyed. */
372
411
  type HasManyDependent = "destroy" | "deleteAll" | "nullify" | "restrictWithException" | "restrictWithError";
373
- /** Rails' `dependent:` strategies for a hasOne: `delete` in place of `deleteAll`. */
412
+ /** What a hasOne's `dependent:` does to its record: `delete` in place of `deleteAll`. */
374
413
  type HasOneDependent = "destroy" | "delete" | "nullify" | "restrictWithException" | "restrictWithError";
375
414
  type Dependent = HasManyDependent | HasOneDependent;
376
415
  /**
377
416
  * `await post.author()`: the owning record, or null. `post.author.set(user)` points the post at
378
- * another record (Rails' `post.author = user`), and `build`/`create` make a new one for it.
417
+ * another record, and `build`/`create` make a new one for it.
379
418
  */
380
419
  interface BelongsTo<C extends ModelClass> {
381
420
  (): Promise<InstanceType<C> | null>;
@@ -396,9 +435,8 @@ interface PolymorphicBelongsTo<C extends ModelClass> {
396
435
  }
397
436
  /**
398
437
  * `await user.profile()`: the one associated record, or null. `await user.profile.set(profile)`
399
- * gives the user another (Rails' `user.profile = profile`), and `build(attrs)` and
400
- * `create(attrs)` make a new one pointing at the user (Rails' `build_profile`). Each replaces the
401
- * old record, removed by `dependent:` when the new one is written.
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.
402
440
  */
403
441
  interface HasOne<C extends ModelClass> {
404
442
  (): Promise<InstanceType<C> | null>;
@@ -424,7 +462,7 @@ type HasManyThrough<C extends ModelClass> = () => Scoped<InstanceType<C>, Scopes
424
462
  type ThroughWrite = "insert" | "insertAll" | "upsert" | "upsertAll";
425
463
  /**
426
464
  * `await mark.note()` for a hasOne through another (#59): its record, or null. `set(note)`
427
- * points the owner's join record at another (#434); as in Rails, it has no `build` or `create`.
465
+ * points the owner's join record at another (#434); it has no `build` or `create`.
428
466
  */
429
467
  interface HasOneThrough<C extends ModelClass> {
430
468
  (): Promise<InstanceType<C> | null>;
@@ -498,10 +536,46 @@ declare class Statement<Row = never> {
498
536
  readonly [rowType]?: Row;
499
537
  }
500
538
  /**
501
- * What a new record is handed to, once its attributes are assigned and before it's saved (Rails'
502
- * 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.
503
541
  */
504
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
+ }
505
579
  /** Two or more of a Model's attributes, as `pluck` and `pick` take them for tuples. */
506
580
  type AttributeList<M extends Model> = readonly [keyof AttributesOf<M> & string, keyof AttributesOf<M> & string, ...(keyof AttributesOf<M> & string)[]];
507
581
  /** The types a sum or an average takes; a custom type stored as one of them too. */
@@ -643,7 +717,7 @@ type ScopeMethods<M extends Model, S> = { [K in keyof S]: S[K] extends ((this: n
643
717
  /** A Relation of Model records `M` with the Model's scope methods `S`. */
644
718
  type Scoped<M extends Model, S = {}> = [keyof S] extends [never] ? Relation<M, S> : Relation<M, S> & ScopeMethods<M, S>;
645
719
  /** A lazy, immutable description of a query against one Model. */
646
- declare class Relation<M extends Model, S = {}> {
720
+ declare class Relation<M extends Model, S = {}> extends TokenFinders<M> {
647
721
  #private;
648
722
  /** Type-only: the Model's scopes, so chained calls keep their scope methods. */
649
723
  readonly [scopeTypes]?: S;
@@ -656,21 +730,21 @@ declare class Relation<M extends Model, S = {}> {
656
730
  /** Negates the whole condition: `NOT (…)`. Rows where it is NULL are excluded too. */
657
731
  whereNot(conditions: Conditions<M> | SafeSql): Scoped<M, S>;
658
732
  /**
659
- * Replaces the conditions on these attributes with these, as Rails' `rewhere`: those on other
660
- * attributes, and fragments, are kept.
733
+ * Replaces the conditions on these attributes with these: those on other attributes, and
734
+ * fragments, are kept.
661
735
  */
662
736
  rewhere(conditions: Conditions<M>): Scoped<M, S>;
663
737
  /**
664
- * 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
665
739
  * on some attributes, `unscope({ where: "role" })`. A default scope's are dropped too.
666
740
  */
667
741
  unscope(...parts: (QueryPart | {
668
742
  where: AttributeNames<M>;
669
743
  })[]): Scoped<M, S>;
670
- /** Keeps only these parts of the query, as Rails' `only`: `only("where", "order")`. */
744
+ /** Keeps only these parts of the query: `only("where", "order")`. */
671
745
  only(...parts: QueryPart[]): Scoped<M, S>;
672
746
  /**
673
- * Leaves these records out, by primary key, as Rails' `excluding`: `excluding(post)`, or
747
+ * Leaves these records out, by primary key: `excluding(post)`, or
674
748
  * `excluding(posts)`. A record not yet saved leaves nothing out.
675
749
  */
676
750
  excluding(...records: (M | readonly M[])[]): Scoped<M, S>;
@@ -684,7 +758,7 @@ declare class Relation<M extends Model, S = {}> {
684
758
  /**
685
759
  * ANDs `other`'s conditions onto this Relation's. For select, order, limit, offset and
686
760
  * distinct, a clause `other` sets explicitly replaces this one's; one it doesn't set is kept.
687
- * 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
688
762
  * Relation of a Model this one joins once (#24): its conditions apply to the joined table.
689
763
  */
690
764
  merge<T extends Model = M, O = S>(other: Relation<T, O>): Scoped<M, S>;
@@ -693,10 +767,10 @@ declare class Relation<M extends Model, S = {}> {
693
767
  * nulls: "last" } }`), or by an `sql` fragment expression. Repeated calls append.
694
768
  */
695
769
  order(spec: OrderSpec<M> | SafeSql): Scoped<M, S>;
696
- /** Replaces the order so far, as in Rails; `reorder()` removes it. */
770
+ /** Replaces the order so far; `reorder()` removes it. */
697
771
  reorder(spec?: OrderSpec<M> | SafeSql): Scoped<M, S>;
698
772
  /**
699
- * 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:
700
774
  * `inOrderOf("status", ["open", "paid"])`. Keeps only the records with one of them, unless
701
775
  * `filter: false`, which keeps the rest after them.
702
776
  */
@@ -737,14 +811,14 @@ declare class Relation<M extends Model, S = {}> {
737
811
  * wrote and the `returning` attributes of each (the primary key by default; `false` for none).
738
812
  * Skips validations and callbacks; declared defaults, generated ids, and timestamps apply, and
739
813
  * this Relation's equality conditions are inserted over the given attributes (#470). A
740
- * duplicate throws, unless `onDuplicate: "skip"` (Rails' `insert`). `b.insert` is the same
814
+ * duplicate throws, unless `onDuplicate: "skip"`. `b.insert` is the same
741
815
  * write, for a batch.
742
816
  */
743
817
  insert<const R extends Returning<M> | undefined = undefined>(attributes: Partial<AttributesOf<M>>, options?: InsertOptions<M> & {
744
818
  returning?: R;
745
819
  }): Promise<WriteResult<ReturnedRow<M, R>>>;
746
820
  /**
747
- * 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,
748
822
  * or several in one atomic batch when they pass the database's cap on one value.
749
823
  */
750
824
  insertAll<const R extends Returning<M> | undefined = undefined>(rows: readonly Partial<AttributesOf<M>>[], options?: InsertOptions<M> & {
@@ -753,26 +827,26 @@ declare class Relation<M extends Model, S = {}> {
753
827
  /**
754
828
  * Inserts a row now, or updates it when it clashes with the unique index on `uniqueBy` (the
755
829
  * primary key by default): every given attribute and every value this Relation writes into the
756
- * row (#475), except the `uniqueBy` ones and `createdAt`, with `updatedAt` set, as Rails'
757
- * `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.
758
832
  */
759
833
  upsert<const R extends Returning<M> | undefined = undefined>(attributes: Partial<AttributesOf<M>>, options?: UpsertOptions<M> & {
760
834
  returning?: R;
761
835
  }): Promise<WriteResult<ReturnedRow<M, R>>>;
762
- /** `upsert` for several rows with the same attributes, now (Rails' `upsert_all`). */
836
+ /** `upsert` for several rows with the same attributes, now. */
763
837
  upsertAll<const R extends Returning<M> | undefined = undefined>(rows: readonly Partial<AttributesOf<M>>[], options?: UpsertOptions<M> & {
764
838
  returning?: R;
765
839
  }): Promise<WriteResult<ReturnedRow<M, R>>>;
766
840
  /**
767
841
  * Updates every row this Relation matches, now, setting attribute values or an `sql`
768
842
  * fragment: ``updateAll(sql`${column("views")} = ${column("views")} + 1`)``. Resolves to the
769
- * number of rows updated. Skips validations and callbacks, and leaves `updatedAt` alone, as in
770
- * 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.
771
845
  */
772
846
  updateAll(changes: Partial<AttributesOf<M>> | SafeSql): Promise<number>;
773
847
  /**
774
848
  * Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`) in every row this
775
- * 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
776
850
  * rows; skips what `updateAll` skips.
777
851
  */
778
852
  touchAll(...args: TouchArguments<M>): Promise<number>;
@@ -785,7 +859,7 @@ declare class Relation<M extends Model, S = {}> {
785
859
  /**
786
860
  * Deletes every row this Relation matches, now, resolving to the number of rows. On a hasMany
787
861
  * association itself (`user.posts().deleteAll()`), the rows' foreign key is set to NULL
788
- * 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
789
863
  * resolves to 0.
790
864
  */
791
865
  deleteAll(): Promise<number>;
@@ -811,7 +885,7 @@ declare class Relation<M extends Model, S = {}> {
811
885
  /**
812
886
  * The record with this primary key, keeping this Relation's conditions. With several ids,
813
887
  * `find(1, 2)` or `find([1, 2])`, the records in the ids' order (or this Relation's order,
814
- * if it has one), as Rails does; `RecordNotFound` if any is missing.
888
+ * if it has one); `RecordNotFound` if any is missing.
815
889
  */
816
890
  find(id: string | number): Promise<M>;
817
891
  find(ids: readonly (string | number)[]): Promise<M[]>;
@@ -886,17 +960,17 @@ declare class Relation<M extends Model, S = {}> {
886
960
  /** Groups the rows by attributes or `sql` fragments, for each group's calculations (#345). */
887
961
  group<const G extends GroupTerms<M>>(...terms: G): GroupedRelation<M, G>;
888
962
  /**
889
- * The number of records, as Rails' `size`: a loaded association's (built records included)
890
- * 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.
891
965
  */
892
966
  size(): Promise<number>;
893
967
  /** Whether there are no records: a loaded association answers itself, else `!exists()`. */
894
968
  isEmpty(): Promise<boolean>;
895
- /** Whether there are any records: the opposite of `isEmpty()` (Rails' `any?`). */
969
+ /** Whether there are any records: the opposite of `isEmpty()`. */
896
970
  hasAny(): Promise<boolean>;
897
- /** 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. */
898
972
  hasMoreThanOne(): Promise<boolean>;
899
- /** 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. */
900
974
  hasExactlyOne(): Promise<boolean>;
901
975
  /** Whether any record matches, optionally with extra conditions. */
902
976
  exists(conditions?: Conditions<M> | SafeSql): Promise<boolean>;
@@ -935,7 +1009,7 @@ declare class Relation<M extends Model, S = {}> {
935
1009
  */
936
1010
  inBatches(options?: IterationOptions): AsyncIterable<Scoped<M, S>>;
937
1011
  /**
938
- * 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
939
1013
  * are never inlined into the SQL (ADR-0006), and none are redacted, filtered attributes included.
940
1014
  */
941
1015
  toSql(): QuerySql;
@@ -943,6 +1017,17 @@ declare class Relation<M extends Model, S = {}> {
943
1017
  [inspectCustom](depth: number, options: InspectOptions, inspect: Inspect): string;
944
1018
  toArray(): Promise<M[]>;
945
1019
  }
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;
1024
+ /**
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.
1028
+ */
1029
+ readonly dependsOn?: (record: R) => unknown;
1030
+ }
946
1031
  /**
947
1032
  * An around callback: `next` runs the rest of the write, resolving once the record's write is kept
948
1033
  * and its inner callbacks have run.
@@ -972,7 +1057,7 @@ interface SaveOptions {
972
1057
  /** A Model's Relation, as its statics return them: `Product.where(…)` is `Product.all().where(…)`. */
973
1058
  type RelationOf<C extends ModelClass> = Scoped<InstanceType<C>, ScopesOf<C>>;
974
1059
  /** The Relation methods every Model has as statics (besides the overloaded ones). */
975
- 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"];
976
1061
  /** A Relation method with no overloads, by name. */
977
1062
  type RelationMethod = (typeof relationMethods)[number];
978
1063
  /**
@@ -1001,7 +1086,7 @@ interface OverloadedStatics {
1001
1086
  <C extends QueryableClass, K extends OrderedAttribute<InstanceType<C>> | SafeSql>(this: C, operation: "minimum" | "maximum", attribute: K): Promise<CalculatedValue<InstanceType<C>, K, unknown> | null>;
1002
1087
  };
1003
1088
  paginate: PaginateStatic;
1004
- /** 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). */
1005
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>;
1006
1091
  group: <C extends QueryableClass, const G extends GroupTerms<InstanceType<C>>>(this: C, ...terms: G) => GroupedRelation<InstanceType<C>, G>;
1007
1092
  find: {
@@ -1146,12 +1231,49 @@ interface CommitStatics {
1146
1231
  /** Runs once a destroy is kept, after every after-callback. */
1147
1232
  afterDestroyCommit: CallbackStatic;
1148
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
+ }
1149
1241
  /**
1150
1242
  * The class Model extends, for its statics' types only: at runtime it's empty, and
1151
1243
  * `defineStatics` puts the statics on Model itself, where scopes look for the names they
1152
1244
  * can't take.
1153
1245
  */
1154
- declare const ModelStatics: (abstract new () => object) & RelationStatics & OverloadedStatics & KeyedWriteStatics & CallbackStatics & AroundStatics & 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
+ }
1155
1277
  /**
1156
1278
  * The built-in type a spec names: `"integer"` for `"integer"` or `{ type: "integer" }`, and
1157
1279
  * `"custom"` for a custom type, given bare or as `{ type }`.
@@ -1178,7 +1300,7 @@ type BooleanAttributeKey<R> = AttributeKeyOf<R, "boolean">;
1178
1300
  * The record methods that change one attribute, between Model and its statics: Model's records
1179
1301
  * have them, and model.ts stays the record class's own.
1180
1302
  */
1181
- declare abstract class AttributeWrites extends ModelStatics {
1303
+ declare abstract class AttributeWrites extends RecordTokens {
1182
1304
  /** Adds `by` (one by default) to a number attribute, null counting as zero; doesn't save. */
1183
1305
  increment<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number): R;
1184
1306
  /** Takes `by` (one by default) from a number attribute, null counting as zero; doesn't save. */
@@ -1186,39 +1308,39 @@ declare abstract class AttributeWrites extends ModelStatics {
1186
1308
  /** Flips a boolean attribute, null becoming `true`; doesn't save. */
1187
1309
  toggle<R extends Model>(this: R, name: BooleanAttributeKey<R>): R;
1188
1310
  /**
1189
- * Writes these attributes straight to the row, with no validation, callback or `updatedAt`,
1190
- * and leaves the record clean for them, as Rails' `update_columns`. Resolves to whether there
1191
- * 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`.
1192
1314
  */
1193
1315
  updateColumns<R extends Model>(this: R, attributes: Partial<AttributesOf<R>>): Promise<boolean>;
1194
1316
  /** `updateColumns` for one attribute. */
1195
1317
  updateColumn<R extends Model, K extends AttributeKey$1<R>>(this: R, name: K, value: AttributesOf<R>[K]): Promise<boolean>;
1196
1318
  /**
1197
1319
  * Adds `by` to a number attribute in the row, as `SET x = COALESCE(x, 0) + by`, so concurrent
1198
- * writes all count, with no validation, callback or `updatedAt`; the record then holds the
1199
- * row's new value. An unsaved change to it is added too, as Rails' `increment!`. With
1200
- * `{ touch }`, the same UPDATE sets `updatedAt` (and any datetime attributes named) to now, and
1201
- * 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.
1202
1324
  */
1203
1325
  incrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number, { touch }?: CounterOptions<R>): Promise<boolean>;
1204
1326
  /** `incrementColumn`, taking `by` away. */
1205
1327
  decrementColumn<R extends Model>(this: R, name: NumberAttributeKey<R>, by?: number, { touch }?: CounterOptions<R>): Promise<boolean>;
1206
1328
  /**
1207
- * Sets `updatedAt`, and the datetime attributes named, to now (or `{ time }`), straight to
1208
- * the row, with no validation or save callback, as Rails' `touch`. Resolves to whether there
1209
- * was a row to write. Inside its Model's `noTouching` block, it writes nothing (#496).
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).
1210
1332
  */
1211
1333
  touch<R extends Model>(this: R, ...args: TouchArguments<R>): Promise<boolean>;
1212
1334
  /**
1213
1335
  * Writes a boolean attribute's flipped value straight to the row, as `updateColumn` does: no
1214
- * 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.
1215
1337
  */
1216
1338
  toggleColumn<R extends Model>(this: R, name: BooleanAttributeKey<R>): Promise<boolean>;
1217
1339
  }
1218
1340
  /** What `updateCounters` adds to each number attribute: `{ viewCount: 1 }`. */
1219
1341
  type Counters<R> = { [K in NumberAttributeKey<R>]?: number; };
1220
1342
  /**
1221
- * 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
1222
1344
  * a datetime attribute's name, or several, set with `updatedAt`.
1223
1345
  */
1224
1346
  type Touch<R> = true | DatetimeAttributeKey<R> | readonly DatetimeAttributeKey<R>[];
@@ -1429,12 +1551,12 @@ type Permitted<C extends ModelClass, K extends string> = Partial<Pick<Attributes
1429
1551
  interface AttributeConversions<T> {
1430
1552
  /**
1431
1553
  * `input` as the attribute's JavaScript value, as assigning it would: strict, so `TypeError`
1432
- * 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.
1433
1555
  * Nothing is floored: a `Date` with milliseconds keeps them, whatever the attribute's `storage`.
1434
1556
  */
1435
1557
  readonly cast: (input: unknown) => T;
1436
1558
  /**
1437
- * `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
1438
1560
  * are floored), `0` or `1`, JSON text, bytes for a `binary` attribute, or a custom type's value
1439
1561
  * as its stored type keeps it (#20). The value `column(attribute).value(input)` binds inside
1440
1562
  * an `sql` fragment; `undefined` throws as assigning it does.
@@ -1456,6 +1578,11 @@ interface AttributeConversions<T> {
1456
1578
  type FilterAttribute = string | RegExp;
1457
1579
  /** The value D1 binds. */
1458
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;
1459
1586
  /** An override written out: the parts of a spec it may change (not the column), any left out or `undefined` unchanged. */
1460
1587
  type SpecOverride = Partial<Omit<SpecObject, "column">>;
1461
1588
  /** One table in a generated schema: its attributes, and which is the primary key. */
@@ -1475,28 +1602,46 @@ type EnumOptions = Pick<SpecOverride, "prefix" | "suffix" | "scopes" | "instance
1475
1602
  type AttributeOverride = AttributeType | AnyCustomType | (Pick<SpecOverride, "null"> & {
1476
1603
  type?: "string";
1477
1604
  storage?: never;
1605
+ virtual?: false;
1478
1606
  /** Or `true`: a generated enum's names, with its methods; `false`: none of it (#64). */
1479
1607
  enum?: TextEnum | boolean;
1608
+ /** A random token, generated for a new record (#355). */
1609
+ secureToken?: boolean | SecureTokenOptions;
1480
1610
  } & EnumOptions & ValueSource) | (Pick<SpecOverride, "null" | "default"> & {
1481
1611
  type?: "integer";
1482
1612
  generateId?: false;
1483
1613
  storage?: never;
1614
+ virtual?: false;
1484
1615
  enum: IntegerEnum;
1485
1616
  } & EnumOptions) | (Pick<SpecOverride, "null" | "default"> & {
1486
1617
  type: Exclude<AttributeType, "string" | "datetime">;
1487
1618
  generateId?: false;
1488
1619
  storage?: never;
1489
1620
  enum?: never;
1621
+ virtual?: false;
1490
1622
  }) | (Pick<SpecOverride, "null" | "default" | "storage"> & {
1491
1623
  type: "datetime";
1492
1624
  generateId?: false;
1493
1625
  enum?: never;
1626
+ virtual?: false;
1494
1627
  }) | (Pick<SpecOverride, "null" | "default"> & {
1495
1628
  type: AnyCustomType;
1496
1629
  generateId?: false;
1497
1630
  storage?: never;
1498
1631
  enum?: never;
1499
- });
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
+ };
1500
1645
  /** The type a spec declares, written either way. */
1501
1646
  type TypeOf<S> = S extends AttributeType | AnyCustomType ? S : S extends {
1502
1647
  type: infer T;
@@ -1542,9 +1687,18 @@ type Overridden<S, O> = O extends AttributeType | AnyCustomType ? {
1542
1687
  null: O extends {
1543
1688
  null: infer N extends boolean;
1544
1689
  } ? N : NullOf<S>;
1545
- } & KeptEnumKeys<S, O> & GivenEnumKeys<O> : S;
1546
- /** A table's attributes after its overrides: changed ones merged, ignored ones gone. */
1547
- 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]; };
1548
1702
  /** `S` as attribute specs, without widening it to an index signature (which would type any name). */
1549
1703
  type AsSpecs<S> = S extends AttributeSpecs ? S : never;
1550
1704
  /**
@@ -1641,7 +1795,7 @@ type AttributesOf<M> = M extends {
1641
1795
  readonly [attributeTypes]?: infer A;
1642
1796
  } ? A : never;
1643
1797
  /**
1644
- * 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
1645
1799
  * methods, statics, callbacks and scopes declared there are shared by every Model built on it.
1646
1800
  * It has no table, so it's never used as a Model itself.
1647
1801
  */
@@ -1649,7 +1803,7 @@ declare class Model extends AttributeWrites {
1649
1803
  /** The table's name: inferred from `modelName` (`BlogPost` → `blog_posts`) unless set. */
1650
1804
  static table: string;
1651
1805
  /**
1652
- * 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 =
1653
1807
  * "BlogPost"`), so names inferred from it survive a bundler that renames classes.
1654
1808
  */
1655
1809
  static modelName: string;
@@ -1679,10 +1833,11 @@ declare class Model extends AttributeWrites {
1679
1833
  */
1680
1834
  static onQuery: QueryListener | undefined;
1681
1835
  /**
1682
- * Attributes whose values listeners and errors show as "[FILTERED]", as Rails'
1683
- * `filter_attributes`: an attribute whose snake_case name holds a string entry, lowercased
1684
- * or read in snake_case (`"apiKey"` as `api_key`), or matches a RegExp. Rails' defaults;
1685
- * 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).
1686
1841
  */
1687
1842
  static filterAttributes: readonly FilterAttribute[];
1688
1843
  /**
@@ -1692,7 +1847,7 @@ declare class Model extends AttributeWrites {
1692
1847
  static hiddenAttributes: readonly string[];
1693
1848
  /**
1694
1849
  * Runs `fn` with this Model's records not touched, nor those of the Models extending it
1695
- * (`Model.noTouching` covers every Model), as Rails' `no_touching`: a belongsTo's `touch`
1850
+ * (`Model.noTouching` covers every Model): a belongsTo's `touch`
1696
1851
  * leaves them alone, and their `touch()` writes nothing. Resolves to what `fn` returns.
1697
1852
  */
1698
1853
  static noTouching<R>(fn: () => R | Promise<R>): Promise<R>;
@@ -1716,51 +1871,70 @@ declare class Model extends AttributeWrites {
1716
1871
  * `class Visit extends Model.define({ path: "string" }) {}`. It's built on the class it's
1717
1872
  * called on, so a Model made with `ApplicationRecord.define({...})` shares the app's base.
1718
1873
  */
1719
- 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>;
1720
1875
  /**
1721
- * Declares a scope, as Rails' `scope :active, -> { … }`: `static active = this.scope((q) =>
1876
+ * Declares a scope: `static active = this.scope((q) =>
1722
1877
  * q.where({ isActive: true }))`. It's a static (`User.active()`) and a Relation method
1723
1878
  * (`User.where(…).active()`), inherited like any static. Inside it, `q` has every Relation
1724
1879
  * method, but not the Model's other scopes (their types would refer to themselves).
1725
1880
  */
1726
1881
  static scope<C extends AbstractModelClass, A extends unknown[]>(this: C, body: (q: Relation<InstanceType<C>>, ...args: A) => Relation<InstanceType<C>>): ScopeStatic<A>;
1727
1882
  /**
1728
- * 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
1729
1884
  * (the request's, set with `withDatabase`, or else the binding in its base class's schema).
1730
1885
  */
1731
1886
  static all<C extends QueryableClass>(this: C): Scoped<InstanceType<C>, ScopesOf<C>>;
1732
1887
  /**
1733
1888
  * Only the named attributes of untrusted input (a JSON body, `FormData` or
1734
- * `URLSearchParams`), as Rails' `params.permit`:
1889
+ * `URLSearchParams`):
1735
1890
  * `User.create(User.permit(await request.json(), "email", "name"))`. Every other key is
1736
1891
  * dropped, and each value is cast as assigning it would be.
1737
1892
  */
1738
1893
  static permit<C extends QueryableClass, K extends AttributeKey<InstanceType<C>>>(this: C, input: unknown, ...names: K[]): Permitted<C, K>;
1739
1894
  /**
1740
- * 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):
1741
1903
  * `Post.enumValues("status")` is `{ draft: "draft", published: "published" }`.
1742
1904
  */
1743
1905
  static enumValues<C extends QueryableClass, K extends EnumAttributeKey<InstanceType<C>>>(this: C, attribute: K): EnumMapping<EnumOf<InstanceType<C>, K>>;
1744
1906
  /**
1745
- * 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:
1746
1908
  * `Post.typeForAttribute("publishedAt").serialize(date)` is what `publishedAt` stores a `Date`
1747
- * 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).
1748
1911
  */
1749
1912
  static typeForAttribute<C extends QueryableClass, K extends AttributeKey<InstanceType<C>>>(this: C, name: K): AttributeConversions<AttributesOf<InstanceType<C>>[K]>;
1750
1913
  /**
1751
- * 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 {}`:
1752
1920
  * `this.defaultScope((q) => q.where({ deletedAt: null }))`. Every query on the Model, its
1753
1921
  * associations' included, starts from it, and new records take its equality values. Several
1754
1922
  * are applied in order; a subclass adds to its parent's. `unscoped()` leaves them out.
1755
1923
  */
1756
1924
  static defaultScope<C extends AbstractModelClass>(this: C, body: (q: Relation<InstanceType<C>>) => Relation<InstanceType<C>>): void;
1757
1925
  /**
1758
- * 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),
1759
1927
  * on the current database. Only a static: a Relation keeps what it has.
1760
1928
  */
1761
1929
  static unscoped<C extends QueryableClass>(this: C): Scoped<InstanceType<C>, ScopesOf<C>>;
1762
1930
  /** Declares a validation, e.g. `this.validates("email", { presence: true })` in `static {}`. */
1763
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;
1764
1938
  /**
1765
1939
  * Declares that an association's records must be valid too, e.g.
1766
1940
  * `this.validatesAssociated("posts")` in `static {}`: an invalid one adds "is invalid" to the
@@ -1790,8 +1964,7 @@ declare class Model extends AttributeWrites {
1790
1964
  /** Whether the association is loaded: preloaded or already read, for the key held now. */
1791
1965
  isLoaded<K extends AssociationName<this>>(name: K): boolean;
1792
1966
  /**
1793
- * Loads the association again, replacing what's cached, and returns it: Rails'
1794
- * `reload_author`, or `user.posts.reload` for a hasMany.
1967
+ * Loads the association again, replacing what's cached, and returns its record or records.
1795
1968
  */
1796
1969
  reloadAssociation<K extends AssociationName<this>>(name: K): Promise<LoadedValue<this[K]>>;
1797
1970
  /** Why a callback last refused a save or destroy (`abort(reason)`); never copied into `errors`. */
@@ -1812,11 +1985,10 @@ declare class Model extends AttributeWrites {
1812
1985
  changes(): Changes;
1813
1986
  /** The changes the last successful save wrote; use it in after-save callbacks. */
1814
1987
  savedChanges(): Changes;
1815
- /** The attribute's value before its unsaved change, as stored (Rails' `attribute_was`). */
1988
+ /** The attribute's value before its unsaved change, as stored. */
1816
1989
  attributeWas<R extends Model, K extends AttributeKey<R>>(this: R, name: K): AttributesOf<R>[K];
1817
1990
  /**
1818
- * Whether the attribute has an unsaved change, optionally `from` and/or `to` given values
1819
- * (Rails' `attribute_changed?(name, from:, to:)`).
1991
+ * Whether the attribute has an unsaved change, optionally `from` and/or `to` given values.
1820
1992
  */
1821
1993
  isAttributeChanged<R extends Model, K extends AttributeKey<R>>(this: R, name: K, options?: ChangeOptions<AttributesOf<R>[K]>): boolean;
1822
1994
  /** Whether saving now would write a change to the attribute (for before-callbacks). */
@@ -1827,8 +1999,13 @@ declare class Model extends AttributeWrites {
1827
1999
  hasSavedChangeTo<R extends Model, K extends AttributeKey<R>>(this: R, name: K, options?: ChangeOptions<AttributesOf<R>[K]>): boolean;
1828
2000
  /** The attribute's value before the last save (its current stored value, if that didn't change it). */
1829
2001
  attributeBeforeLastSave<R extends Model, K extends AttributeKey<R>>(this: R, name: K): AttributesOf<R>[K];
1830
- /** 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). */
1831
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;
1832
2009
  /**
1833
2010
  * Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted,
1834
2011
  * or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as
@@ -1859,7 +2036,7 @@ declare class Model extends AttributeWrites {
1859
2036
  reload(): Promise<this>;
1860
2037
  /**
1861
2038
  * Marks the record to be destroyed when its owner is saved, through an association declared
1862
- * `autosave: true`, as Rails' `mark_for_destruction` does. Nothing is written until then, and
2039
+ * `autosave: true`. Nothing is written until then, and
1863
2040
  * `reload()` clears the mark.
1864
2041
  */
1865
2042
  markForDestruction(): void;
@@ -1868,7 +2045,7 @@ declare class Model extends AttributeWrites {
1868
2045
  /** Not yet saved: built, or created but not persisted. */
1869
2046
  isNewRecord(): boolean;
1870
2047
  /**
1871
- * 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
1872
2049
  * after-callbacks and after it, false once it's saved again or destroyed.
1873
2050
  */
1874
2051
  isPreviouslyNewRecord(): boolean;
@@ -1877,7 +2054,7 @@ declare class Model extends AttributeWrites {
1877
2054
  /** Deleted by this instance; a read-only snapshot of the row. */
1878
2055
  isDestroyed(): boolean;
1879
2056
  /**
1880
- * Whether the record has the attribute `name` loaded (Rails' `has_attribute?`): `false` for one
2057
+ * Whether the record has the attribute `name` loaded: `false` for one
1881
2058
  * `select(...)` left out, whose read throws `MissingAttribute`, and for a name the Model doesn't
1882
2059
  * declare. A callback that runs for partial records, such as `afterFind`, checks it first.
1883
2060
  */
@@ -1888,7 +2065,9 @@ declare class Model extends AttributeWrites {
1888
2065
  [inspectCustom](depth: number, options: InspectOptions, inspect: Inspect): string;
1889
2066
  /**
1890
2067
  * The loaded attributes as JSON-ready values (dates as ISO strings), without the Model's
1891
- * `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)`.
1892
2071
  */
1893
2072
  toJSON(): Record<string, unknown>;
1894
2073
  }
@@ -1906,7 +2085,7 @@ type QueryableClass<M extends Model = Model> = ModelClass<M & {
1906
2085
  * What a generated declaration adds to a Model's records: its table's attributes `A`, with the
1907
2086
  * Model's `static attributes` overrides `O` applied, typed, and its enums' methods (#340).
1908
2087
  */
1909
- 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>> & {
1910
2089
  readonly [attributeSpecs]: OverriddenSpecs<A, O>;
1911
2090
  readonly [attributeTypes]: AttributeProperties<AsSpecs<OverriddenSpecs<A, O>>>;
1912
2091
  };
@@ -1921,7 +2100,7 @@ type BaseClass = abstract new () => Model;
1921
2100
  * The base class `Model.define({...})` makes: records with the attributes `A`, built on `B` (the
1922
2101
  * library's base, or an app's), so they have its methods and statics too.
1923
2102
  */
1924
- 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> & {
1925
2104
  readonly [attributeTypes]: AttributeProperties<A>;
1926
2105
  readonly [attributeSpecs]: A;
1927
2106
  }) & Omit<B, "prototype"> & EnumStatics<A>;
@@ -2040,6 +2219,14 @@ interface ValidationOptions<R = never, X extends string = ValidationContext> {
2040
2219
  acceptance?: boolean | {
2041
2220
  accept: readonly unknown[];
2042
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
+ };
2043
2230
  /**
2044
2231
  * No other row has this value (checked in D1 through the record's Database). `scope` adds
2045
2232
  * attributes that must match too; `caseSensitive: false` compares with `lower()` (ASCII only).
@@ -2072,4 +2259,4 @@ interface ValidationOptions<R = never, X extends string = ValidationContext> {
2072
2259
  }
2073
2260
  /** The options of a `validatesAssociated(association, options)` call. */
2074
2261
  type AssociatedValidationOptions<R = never, X extends string = ValidationContext> = Pick<ValidationOptions<R, X>, "message" | "strict" | "if" | "unless" | "on" | "exceptOn">;
2075
- export { ReturnedRow as $, databaseExecutor as A, QuerySql as At, ValidationContext as B, ComparisonBound as Bt, QueryEvent as C, gt as Ct, SchemaAdapter as D, QueryPart as Dt, ConstraintFailure as E, lte as Et, RecordStatement as F, ColumnValue as Ft, Scoped as G, Relation as H, DatetimeAttributeKey as I, SafeSql as It, Page as J, IterationOptions as K, NumberAttributeKey as L, column as Lt, BatchResults as M, valueMark as Mt, batch as N, Attribute as Nt, AnyDatabase as O, InOrderOfOptions as Ot, Batch as P, ColumnReference as Pt, Init as Q, SaveOptions as R, sql$1 as Rt, DatabaseExecutor as S, between as St, Adapter as T, lt as Tt, Scope as U, ValidationContexts as V, ComparisonOptions as Vt, ScopeMethods as W, TouchOptions as X, PageOptions as Y, GroupedRelation as Z, TableSchema as _, InsertOptions as _t, ValidationOptions as a, BelongsTo as at, boundValue as b, UpsertOptions as bt, AttributeErrorMessages as c, HasManyDependent as ct, RestrictMessages as d, HasOneDependent as dt, Statement as et, Model as f, HasOneThrough as ft, DatabaseSchema as g, Conditions as gt, TableAttributes as h, ThroughOptions as ht, UniquenessOptions as i, AssociationOptions as it, BatchEntry as j, Dialect as jt, RelationsFor as k, CompiledSql as kt, ErrorMessage as l, HasManyThrough as lt, ScopeStatic as m, ThroughDependent as mt, LengthOptions as n, Driver as nt, Errors as o, HasMany as ot, ModelClass as p, PolymorphicBelongsTo as pt, CountlessPage as q, NumericalityOptions as r, StatementResult as rt, ValidationError as s, HasManyCollection as st, AssociatedValidationOptions as t, WriteResult as tt, ErrorMessages as u, HasOne as ut, TableSchemas as v, OrderSpec as vt, QueryListener as w, gte as wt, AttributeConversions as x, Comparison as xt, FilterAttribute as y, Returning as yt, ValidationCallbackOptions as z, Comparable 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 };