@supatype/types 0.3.6 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"lexical.js","sourceRoot":"","sources":["../src/lexical.ts"],"names":[],"mappings":""}
1
+ {"version":3,"file":"lexical.js","sourceRoot":"","sources":["../src/lexical.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supatype/types",
3
- "version": "0.3.6",
3
+ "version": "0.7.0",
4
4
  "license": "MIT",
5
5
  "description": "Pure type primitives for Supatype RFC v2",
6
6
  "type": "module",
@@ -26,7 +26,7 @@
26
26
  "scripts": {
27
27
  "build": "tsc --project tsconfig.json",
28
28
  "dev": "tsc --project tsconfig.json --watch",
29
- "typecheck": "tsc --project tsconfig.json --noEmit && tsc --project tsconfig.test.json",
29
+ "typecheck": "tsc --project tests/tsconfig.json --noEmit",
30
30
  "test": "vitest run",
31
31
  "clean": "rm -rf dist *.tsbuildinfo"
32
32
  }
package/src/index.ts CHANGED
@@ -42,37 +42,73 @@ type Modifier<TName extends string, TInner> = {
42
42
  readonly __inner: TInner
43
43
  }
44
44
  type Relation<TName extends string, TInner> = Tagged<TInner, `relation:${TName}`>
45
+
46
+ /** How an identity column takes values: `always` refuses an explicit one, `by-default` accepts one. */
47
+ export type IdentityMode = "always" | "by-default"
48
+ /**
49
+ * Options every scalar field type takes as its last type argument.
50
+ *
51
+ * `generated` makes it a stored generated column: `GENERATED ALWAYS AS (expression) STORED`, the SQL
52
+ * written over the row's columns by their column names. The database computes it on every write and
53
+ * refuses to have it written, so the generated client types leave it out of inserts and updates.
54
+ *
55
+ * ```typescript
56
+ * total: Float<{ generated: "price * quantity" }>
57
+ * search: TSVector<{ generated: "to_tsvector('english', coalesce(title, ''))" }>
58
+ * ```
59
+ */
60
+ export interface ScalarFieldOptions {
61
+ generated?: string
62
+ }
63
+ /**
64
+ * {@link ScalarFieldOptions}, and for an integer field `identity`: `GENERATED ALWAYS AS IDENTITY`
65
+ * (`"always"`) or `GENERATED BY DEFAULT AS IDENTITY` (`"by-default"`). The database numbers the
66
+ * column from a sequence it owns; an insert leaves it out (and with `"always"` cannot give one).
67
+ *
68
+ * ```typescript
69
+ * id: PrimaryKey<Int<{ identity: "always" }>>
70
+ * ```
71
+ */
72
+ export interface IntegerFieldOptions extends ScalarFieldOptions {
73
+ identity?: IdentityMode
74
+ }
75
+ /**
76
+ * The options a field type was declared with, carried at the type level only. Optional, like
77
+ * {@link Tagged}'s label, so a plain value is still assignable to the field's type; the CLI reads the
78
+ * options from the declaration's syntax.
79
+ */
80
+ type FieldOptions<TOptions> = { readonly __fieldOptions?: TOptions }
45
81
  type Access<TName extends string, TShape = { readonly kind: TName }> = Tagged<TShape, `access:${TName}`>
46
82
 
47
- export type UUID = Primitive<"UUID", string>
48
- export type Email = Primitive<"Email", string>
49
- export type URL = Primitive<"URL", string>
83
+ export type UUID<O extends ScalarFieldOptions = {}> = Primitive<"UUID", string> & FieldOptions<O>
84
+ export type Email<O extends ScalarFieldOptions = {}> = Primitive<"Email", string> & FieldOptions<O>
85
+ export type URL<O extends ScalarFieldOptions = {}> = Primitive<"URL", string> & FieldOptions<O>
50
86
  /**
51
87
  * URL-safe slug stored as text. Optional type argument names the source field used
52
88
  * for auto-generation (DB trigger + Studio). Defaults to `"title"`.
53
89
  */
54
90
  export type Slug<TSource extends string = "title"> = Primitive<`Slug:${TSource}`, string>
55
- export type PhoneNumber = Primitive<"PhoneNumber", string>
56
- export type Markdown = Primitive<"Markdown", string>
57
- export type Color = Primitive<"Color", string>
58
- export type Int = Primitive<"Int", number>
59
- export type SmallInt = Primitive<"SmallInt", number>
60
- export type BigInt = Primitive<"BigInt", bigint>
61
- export type Float = Primitive<"Float", number>
91
+ export type PhoneNumber<O extends ScalarFieldOptions = {}> = Primitive<"PhoneNumber", string> & FieldOptions<O>
92
+ export type Markdown<O extends ScalarFieldOptions = {}> = Primitive<"Markdown", string> & FieldOptions<O>
93
+ export type Color<O extends ScalarFieldOptions = {}> = Primitive<"Color", string> & FieldOptions<O>
94
+ export type Int<O extends IntegerFieldOptions = {}> = Primitive<"Int", number> & FieldOptions<O>
95
+ export type SmallInt<O extends IntegerFieldOptions = {}> = Primitive<"SmallInt", number> & FieldOptions<O>
96
+ export type BigInt<O extends IntegerFieldOptions = {}> = Primitive<"BigInt", bigint> & FieldOptions<O>
97
+ export type Float<O extends ScalarFieldOptions = {}> = Primitive<"Float", number> & FieldOptions<O>
62
98
  export type Decimal<P extends number, S extends number> = Primitive<`Decimal:${P}:${S}`, string>
63
- export type Money = Primitive<"Money", string>
99
+ export type Money<O extends ScalarFieldOptions = {}> = Primitive<"Money", string> & FieldOptions<O>
64
100
  export type Vector<N extends number> = Primitive<`Vector:${N}`, number[]>
65
101
  export type JSON<T> = Primitive<"JSON", T>
66
- export type IPAddress = Primitive<"IPAddress", string>
67
- export type CIDR = Primitive<"CIDR", string>
68
- export type MacAddress = Primitive<"MacAddress", string>
69
- export type Bytea = Primitive<"Bytea", string>
70
- export type XML = Primitive<"XML", string>
71
- export type TSQuery = Primitive<"TSQuery", string>
72
- export type TSVector = Primitive<"TSVector", string>
73
- export type DateOnly = Primitive<"DateOnly", Date>
74
- export type DateTime = Primitive<"DateTime", Date>
75
- export type Timestamp = Primitive<"Timestamp", Date>
102
+ export type IPAddress<O extends ScalarFieldOptions = {}> = Primitive<"IPAddress", string> & FieldOptions<O>
103
+ export type CIDR<O extends ScalarFieldOptions = {}> = Primitive<"CIDR", string> & FieldOptions<O>
104
+ export type MacAddress<O extends ScalarFieldOptions = {}> = Primitive<"MacAddress", string> & FieldOptions<O>
105
+ export type Bytea<O extends ScalarFieldOptions = {}> = Primitive<"Bytea", string> & FieldOptions<O>
106
+ export type XML<O extends ScalarFieldOptions = {}> = Primitive<"XML", string> & FieldOptions<O>
107
+ export type TSQuery<O extends ScalarFieldOptions = {}> = Primitive<"TSQuery", string> & FieldOptions<O>
108
+ export type TSVector<O extends ScalarFieldOptions = {}> = Primitive<"TSVector", string> & FieldOptions<O>
109
+ export type DateOnly<O extends ScalarFieldOptions = {}> = Primitive<"DateOnly", Date> & FieldOptions<O>
110
+ export type DateTime<O extends ScalarFieldOptions = {}> = Primitive<"DateTime", Date> & FieldOptions<O>
111
+ export type Timestamp<O extends ScalarFieldOptions = {}> = Primitive<"Timestamp", Date> & FieldOptions<O>
76
112
  export type Geo = Primitive<"Geo", { type: "point" | "polygon" | "linestring"; coordinates: unknown }>
77
113
 
78
114
  /** Source text with the language it is written in. Stored as `JSONB`. */
@@ -111,7 +147,7 @@ export type Button = Primitive<"Button", ButtonValue>
111
147
  * - Lexical document: pass a JSON string literal or use `Default<RichText, '{"root":…}'>`
112
148
  */
113
149
  export type RichText<D extends string = never> = Primitive<
114
- D extends never ? "RichText" : `RichText:${D}`,
150
+ [D] extends [never] ? "RichText" : `RichText:${D}`,
115
151
  SerializedEditorState | string
116
152
  >
117
153
 
@@ -208,11 +244,17 @@ export type LocaleConfig<
208
244
  export type Localized<T> = Modifier<"Localized", Record<string, T>>
209
245
  /** Opt out of {@link LocalizedModel} auto-localization for a copy-like field. */
210
246
  export type NotLocalized<T> = Modifier<"NotLocalized", T>
247
+ /**
248
+ * One kind of entry in a {@link Blocks} field: `TName` is stored under `type` and the fields under
249
+ * `data`, `{ "type": "hero", "data": { "heading": { "en": "Hi" } } }`, which is what Studio's block
250
+ * editor writes. The fields read as a model's row does, so `Localized<string>` is the locale map and
251
+ * `Optional<T>` may be absent or null.
252
+ */
211
253
  export type Block<
212
254
  TName extends string = string,
213
255
  TFields extends Record<string, unknown> = Record<string, unknown>,
214
256
  TMeta extends { label?: string; icon?: string } = {},
215
- > = Primitive<`Block:${TName}`, { type: TName; meta?: TMeta } & TFields>
257
+ > = Primitive<`Block:${TName}`, { type: TName; data: SpreadOptionalModelFields<TFields>; meta?: TMeta }>
216
258
  export type Blocks<TBlock extends Block = Block> = Primitive<"Blocks", TBlock[]>
217
259
 
218
260
  /**
@@ -253,7 +295,28 @@ export type ComputedFrom<
253
295
  TSources extends string | readonly string[] = "title",
254
296
  > = Modifier<"ComputedFrom", TValue>
255
297
  export type PrimaryKey<T> = Modifier<"PrimaryKey", T>
256
- export type AutoIncrement<T extends number | bigint> = Modifier<"AutoIncrement", T>
298
+ /**
299
+ * An identity column: `Identity<number>` is `Int<{ identity: "always" }>`, `Identity<bigint,
300
+ * "by-default">` is `BigInt<{ identity: "by-default" }>`. `Identity<SmallInt>` declares a `SMALLINT`
301
+ * one (at the type level every integer field is a number, so it reads as `Int`).
302
+ */
303
+ export type Identity<
304
+ T extends number | bigint = number,
305
+ M extends IdentityMode = "always",
306
+ > = T extends bigint ? BigInt<{ identity: M }> : Int<{ identity: M }>
307
+ /**
308
+ * A stored generated column of type `T`: `Generated<string, "lower(name)">` is a text column the
309
+ * database computes as `lower(name)`. The same as `T`'s `{ generated }` option, for the types (such as
310
+ * `string`) that take none.
311
+ */
312
+ export type Generated<T, TExpression extends string> = T & FieldOptions<{ generated: TExpression }>
313
+ /**
314
+ * A column the database numbers, which an insert may also give: an identity column generated by
315
+ * default, `Identity<T, "by-default">`. It compiled to `SERIAL` before, and a serial column pushed
316
+ * then satisfies it: every push leaves it exactly as it is. An explicit {@link Identity} on such a
317
+ * column converts it to an identity column.
318
+ */
319
+ export type AutoIncrement<T extends number | bigint = number> = Identity<T, "by-default">
257
320
  /**
258
321
  * Column value is assigned by the database (trigger, `DEFAULT`, sequence, etc.).
259
322
  * Inserts may omit this field; generated client `Insert` types mark it optional.
@@ -411,34 +474,89 @@ export type Public = Access<"Public">
411
474
  export type Private = Access<"Private">
412
475
  export type LoggedIn = Access<"LoggedIn">
413
476
  export type SupatypeAuthUser = Primitive<"SupatypeAuthUser", { readonly system: "supatype:user" }>
414
- export type SupatypeAuthUserId = Primitive<"SupatypeAuthUserId", string>
477
+ /**
478
+ * What deleting a user does to the rows whose {@link SupatypeAuthUserId} field names them.
479
+ *
480
+ * - `"cascade"`: the rows are deleted with the user. Everything the user wrote goes, including
481
+ * content other people rely on, such as their comments in someone else's thread.
482
+ * - `"restrict"`: the user cannot be deleted while they still own a row. Deleting them in Studio is
483
+ * refused until their rows are deleted or handed to someone else.
484
+ * - `"setNull"`: the rows stay and the field becomes NULL, so only an `Optional` field takes it.
485
+ * Under owner rules (`Owner<"user_id">`) a row with no owner matches nobody, so nobody but the
486
+ * service role can edit or delete it afterwards.
487
+ */
488
+ export type AuthUserOnDelete = "cascade" | "restrict" | "setNull"
489
+ /** The options of {@link SupatypeAuthUserId}. */
490
+ export interface AuthUserIdOptions {
491
+ /**
492
+ * Links the field to its user in `auth.users` with a foreign key, and says what deleting the user
493
+ * does to the row. Left out, the field holds a user id with no foreign key.
494
+ */
495
+ onDelete?: AuthUserOnDelete
496
+ }
497
+ /**
498
+ * A user's id from `auth.users`, for an owner column such as `Comment.user_id` or a profile's `id`.
499
+ *
500
+ * It has no foreign key by default: the column holds the id and nothing stops the user being
501
+ * deleted from under it, which is also what lets a project that brings its own auth, or keeps its
502
+ * schema apart from `auth`, use it. A field opts in to a key per field with `onDelete`
503
+ * ({@link AuthUserOnDelete}):
504
+ *
505
+ * ```typescript
506
+ * user_id: SupatypeAuthUserId<{ onDelete: "cascade" }>
507
+ * editor_id: Optional<SupatypeAuthUserId<{ onDelete: "setNull" }>>
508
+ * ```
509
+ *
510
+ * A push with the option needs `auth.users` to exist, and every row's id to name a user in it: it
511
+ * refuses otherwise, and says which rows to fix.
512
+ */
513
+ export type SupatypeAuthUserId<O extends AuthUserIdOptions & OnlyKeysOf<O, AuthUserIdOptions> = {}> =
514
+ Primitive<"SupatypeAuthUserId", string> & FieldOptions<O>
515
+ /** Every key of `T` that `TAllowed` does not have, typed `never`, so an options object takes no others. */
516
+ type OnlyKeysOf<T, TAllowed> = { readonly [K in Exclude<keyof T, keyof TAllowed>]: never }
415
517
  type ModelFieldKeys<TModel> =
416
518
  TModel extends { readonly [SUPATYPE_MODEL]?: { readonly fields: infer TFields } }
417
519
  ? Extract<keyof TFields, string>
418
520
  : never
419
521
  type RelationFieldKeys<TFields extends Record<string, unknown>> = Extract<{
420
522
  [K in keyof TFields]-?: K extends string
421
- ? TFields[K] extends { readonly __relationKind: "relatedTo" }
523
+ ? NonNullable<UnwrapModelFieldType<TFields[K]>> extends { readonly __relationKind: "relatedTo" }
422
524
  ? K
423
525
  : never
424
526
  : never
425
527
  }[keyof TFields], string>
426
528
  type RelationOwnerKeys<TFields extends Record<string, unknown>> = Extract<{
427
529
  [K in keyof TFields]-?: K extends string
428
- ? TFields[K] extends { readonly __relationKind: "relatedTo" }
530
+ ? NonNullable<UnwrapModelFieldType<TFields[K]>> extends { readonly __relationKind: "relatedTo" }
429
531
  ? `${K}_id`
430
532
  : never
431
533
  : never
432
534
  }[keyof TFields], string>
433
- type SelfOwnerKey<TFields extends Record<string, unknown>> =
434
- "id" extends keyof TFields
435
- ? TFields["id"] extends SupatypeAuthUserId
436
- ? "id"
437
- : never
535
+ /** The declared types a row can be owned through: a column that holds a user id. */
536
+ type OwnerColumnTag = "primitive:UUID" | "primitive:SupatypeAuthUserId"
537
+ /**
538
+ * True when a field is declared `UUID` or `SupatypeAuthUserId`.
539
+ *
540
+ * Read from the presence of the tag's key, not by assignability: the tag is optional, so a plain
541
+ * `string` is assignable to `UUID` and would otherwise count as an owner column.
542
+ */
543
+ type IsOwnerColumn<V> = typeof SUPATYPE_TYPE extends keyof V
544
+ ? V extends { readonly [SUPATYPE_TYPE]?: { readonly tag: infer TTag } }
545
+ ? [TTag] extends [OwnerColumnTag]
546
+ ? true
547
+ : false
548
+ : false
549
+ : false
550
+ /** Fields declared `UUID` or `SupatypeAuthUserId`, `id` included, with modifiers (`Optional<UUID>`) unwrapped. */
551
+ type OwnerColumnKeys<TFields extends Record<string, unknown>> = Extract<{
552
+ [K in keyof TFields]-?: IsOwnerColumn<NonNullable<UnwrapModelFieldType<TFields[K]>>> extends true
553
+ ? K
438
554
  : never
555
+ }[keyof TFields], string>
556
+ /** What `Owner<"f">` may name: a UUID or auth-user-id column, or a relation's `<relation>_id` key. */
439
557
  type OwnerEligibleFieldKeys<TFields extends Record<string, unknown>> =
440
- RelationOwnerKeys<TFields> | SelfOwnerKey<TFields>
441
- type ModelRelationFieldKeys<TModel> =
558
+ RelationOwnerKeys<TFields> | OwnerColumnKeys<TFields>
559
+ type ModelOwnerFieldKeys<TModel> =
442
560
  TModel extends { readonly [SUPATYPE_MODEL]?: { readonly fields: infer TFields } }
443
561
  ? TFields extends Record<string, unknown>
444
562
  ? OwnerEligibleFieldKeys<TFields>
@@ -462,7 +580,7 @@ type AnySupatypeModel = {
462
580
  */
463
581
  export type Owner<
464
582
  TModelOrKey extends string | AnySupatypeModel,
465
- TKey extends TModelOrKey extends string ? string : ModelRelationFieldKeys<TModelOrKey> = TModelOrKey extends string
583
+ TKey extends TModelOrKey extends string ? string : ModelOwnerFieldKeys<TModelOrKey> = TModelOrKey extends string
466
584
  ? TModelOrKey
467
585
  : never,
468
586
  > = Access<"Owner", {
@@ -471,7 +589,7 @@ export type Owner<
471
589
  readonly __ownerModel?: TModelOrKey extends string ? never : TModelOrKey
472
590
  }>
473
591
  export type OwnerKey<TModel extends AnySupatypeModel> =
474
- ModelRelationFieldKeys<TModel>
592
+ ModelOwnerFieldKeys<TModel>
475
593
  export type OwnerOf<
476
594
  TModel extends AnySupatypeModel,
477
595
  TKey extends OwnerKey<TModel>,
@@ -770,7 +888,7 @@ export type Exists<TSource> = Access<"Exists", {
770
888
  type BoundOwnerForFields<TFields extends Record<string, unknown>> = Access<"Owner", {
771
889
  readonly kind: "Owner"
772
890
  readonly key: OwnerEligibleFieldKeys<TFields>
773
- readonly __ownerModel?: Model<TFields, any>
891
+ readonly __ownerModel?: Model<TFields, ModelMeta<TFields>>
774
892
  }>
775
893
  type BoundOwnerFromForFields<TFields extends Record<string, unknown>> = Access<"OwnerFrom", {
776
894
  readonly kind: "OwnerFrom"
@@ -938,10 +1056,24 @@ export type SpreadOptionalModelFields<TFields extends Record<string, unknown>> =
938
1056
  : never]?: UnwrapModelFieldType<TFields[K]>
939
1057
  }
940
1058
 
1059
+ /** The Postgres index methods a model index may use. `btree` when omitted. */
1060
+ export type IndexMethod = "btree" | "gin" | "gist" | "hnsw" | "brin"
1061
+
1062
+ /**
1063
+ * How an `hnsw` index on a `Vector` field measures nearness: pgvector's operator classes
1064
+ * `vector_cosine_ops`, `vector_l2_ops` and `vector_ip_ops`. `cosine` when omitted. A query ordered
1065
+ * by another distance does not use the index.
1066
+ */
1067
+ export type VectorDistance = "cosine" | "l2" | "innerProduct"
1068
+
941
1069
  export type ModelIndex = {
942
1070
  name?: string
943
1071
  fields: readonly string[]
944
1072
  unique?: true
1073
+ /** `gist` for `Geo` and `GeoPoint` fields, `hnsw` for `Vector` fields. */
1074
+ using?: IndexMethod
1075
+ /** For an `hnsw` index only. */
1076
+ distance?: VectorDistance
945
1077
  }
946
1078
 
947
1079
  export type ModelMeta<TFields extends Record<string, unknown>> = {
@@ -974,10 +1106,14 @@ export type ModelMeta<TFields extends Record<string, unknown>> = {
974
1106
  * without read is unrepresentable, otherwise a caller could round-trip away a
975
1107
  * value they were never shown.
976
1108
  *
977
- * **`INSERT` cannot evaluate a row-dependent write rule**: there is no row
978
- * yet, so the column falls back to its default instead of accepting the
979
- * submitted value. Use an identity-only rule (`Role<>`, `LoggedIn`,
980
- * `Claim<>`) for a column that must be settable at creation time.
1109
+ * **On `INSERT` a write rule is judged against the row being stored**,
1110
+ * defaults included, as RLS `WITH CHECK` is, so a row-dependent rule
1111
+ * (`Owner<"id">`, `OwnerFrom`, a membership) can pass on create: an
1112
+ * `owner_id DEFAULT auth.uid()` is what it reads. A value the rule allows is
1113
+ * stored; one it refuses fails the insert with `42501`. Sending nothing,
1114
+ * `NULL`, `DEFAULT` or the column default's own value stores the default
1115
+ * without judging the rule. On `UPDATE`, a field the caller cannot read keeps
1116
+ * its stored value, and a real change is judged by the write rule.
981
1117
  *
982
1118
  * Relations are named by their column (`author_id`), because that is what the
983
1119
  * restriction applies to: `author` is not a column at all.
package/src/lexical.ts CHANGED
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Lexical's serialized JSON: what a `RichText` column stores and what the editor in Studio and
3
+ * `@supatype/ui` saves. `SerializedLexicalNode` is the loose shape every node shares; the specific
4
+ * interfaces below describe the fields Lexical 0.43 writes for each node type those editors can
5
+ * produce, so renderers and readers work from one definition.
6
+ */
7
+
1
8
  export interface SerializedLexicalNode {
2
9
  type: string
3
10
  version: number
@@ -8,3 +15,63 @@ export interface SerializedLexicalNode {
8
15
  export interface SerializedEditorState {
9
16
  root: SerializedLexicalNode
10
17
  }
18
+
19
+ /** Block alignment, stored in an element node's `format` (empty when unset). */
20
+ export type ElementFormat = "" | "left" | "start" | "center" | "right" | "end" | "justify"
21
+
22
+ /** Fields every element node (root, paragraph, heading, quote, list, listitem, link, code) carries. */
23
+ export interface SerializedElementNode extends SerializedLexicalNode {
24
+ children: SerializedLexicalNode[]
25
+ direction: "ltr" | "rtl" | null
26
+ format: ElementFormat
27
+ indent: number
28
+ }
29
+
30
+ /**
31
+ * A run of text. `format` is a bit set: bold 1, italic 2, strikethrough 4, underline 8, code 16,
32
+ * subscript 32, superscript 64, highlight 128, lowercase 256, uppercase 512, capitalize 1024.
33
+ * `tab` and `code-highlight` nodes are text nodes under their own type.
34
+ */
35
+ export interface SerializedTextNode extends SerializedLexicalNode {
36
+ type: "text" | "tab" | "code-highlight"
37
+ text: string
38
+ format: number
39
+ detail: number
40
+ mode: "normal" | "token" | "segmented"
41
+ style: string
42
+ highlightType?: string | null
43
+ }
44
+
45
+ export interface SerializedHeadingNode extends SerializedElementNode {
46
+ type: "heading"
47
+ tag: "h1" | "h2" | "h3" | "h4" | "h5" | "h6"
48
+ }
49
+
50
+ export interface SerializedListNode extends SerializedElementNode {
51
+ type: "list"
52
+ listType: "bullet" | "number" | "check"
53
+ start: number
54
+ tag: "ul" | "ol"
55
+ }
56
+
57
+ /** A list entry. A nested list is a `listitem` whose only child is a `list`. */
58
+ export interface SerializedListItemNode extends SerializedElementNode {
59
+ type: "listitem"
60
+ value: number
61
+ checked?: boolean
62
+ }
63
+
64
+ /** `link` is set by an editor; `autolink` is detected from typed text and can be unlinked. */
65
+ export interface SerializedLinkNode extends SerializedElementNode {
66
+ type: "link" | "autolink"
67
+ url: string
68
+ rel: string | null
69
+ target: string | null
70
+ title: string | null
71
+ isUnlinked?: boolean
72
+ }
73
+
74
+ export interface SerializedCodeNode extends SerializedElementNode {
75
+ type: "code"
76
+ language?: string | null
77
+ }
@@ -0,0 +1,57 @@
1
+ import { describe, expectTypeOf, it } from "vitest"
2
+ import type {
3
+ AuthUserOnDelete,
4
+ Model,
5
+ Optional,
6
+ Owner,
7
+ RelatedTo,
8
+ SupatypeAuthUser,
9
+ SupatypeAuthUserId,
10
+ UUID,
11
+ } from "../src/index.js"
12
+
13
+ // An auth user id has no foreign key unless the field asks for one: `SupatypeAuthUserId<{ onDelete }>`.
14
+ describe("SupatypeAuthUserId<{ onDelete }>", () => {
15
+ it("takes the three delete behaviours, and nothing else", () => {
16
+ expectTypeOf<AuthUserOnDelete>().toEqualTypeOf<"cascade" | "restrict" | "setNull">()
17
+ expectTypeOf<SupatypeAuthUserId<{ onDelete: "cascade" }>>().toExtend<string>()
18
+ expectTypeOf<SupatypeAuthUserId<{ onDelete: "restrict" }>>().toExtend<string>()
19
+ expectTypeOf<Optional<SupatypeAuthUserId<{ onDelete: "setNull" }>>>().not.toBeNever()
20
+ // Without options it is the field it always was, with no key.
21
+ expectTypeOf<SupatypeAuthUserId>().toEqualTypeOf<SupatypeAuthUserId<{}>>()
22
+ expectTypeOf<string>().toExtend<SupatypeAuthUserId<{ onDelete: "cascade" }>>()
23
+ })
24
+
25
+ it("rejects a behaviour or an option it does not take", () => {
26
+ // @ts-expect-error "noAction" is not one of the delete behaviours
27
+ type NoAction = SupatypeAuthUserId<{ onDelete: "noAction" }>
28
+ // @ts-expect-error the behaviour is spelled setNull, as the schema spells options
29
+ type SnakeCase = SupatypeAuthUserId<{ onDelete: "set_null" }>
30
+ // @ts-expect-error an auth user id takes onDelete alone
31
+ type Generated = SupatypeAuthUserId<{ generated: "gen_random_uuid()" }>
32
+ // @ts-expect-error an auth user id takes onDelete alone, even beside it
33
+ type Extra = SupatypeAuthUserId<{ onDelete: "cascade"; onUpdate: "cascade" }>
34
+ // @ts-expect-error the options are an object
35
+ type Bare = SupatypeAuthUserId<"cascade">
36
+ expectTypeOf<[NoAction, SnakeCase, Generated, Extra, Bare]>().not.toBeNever()
37
+ })
38
+
39
+ it("is still an owner column, and RelatedTo<SupatypeAuthUser> is unchanged", () => {
40
+ type Comment = Model<{
41
+ id: UUID
42
+ user_id: SupatypeAuthUserId<{ onDelete: "cascade" }>
43
+ editor_id: Optional<SupatypeAuthUserId<{ onDelete: "setNull" }>>
44
+ author: RelatedTo<SupatypeAuthUser>
45
+ body: string
46
+ }, {
47
+ access: { update: Owner<"user_id">; delete: Owner<"editor_id"> }
48
+ }>
49
+ expectTypeOf<Comment["user_id"]>().toExtend<string>()
50
+ expectTypeOf<Comment>().toHaveProperty("author")
51
+
52
+ type Profile = Model<{ id: SupatypeAuthUserId<{ onDelete: "cascade" }>; name: string }, {
53
+ access: { update: Owner<"id"> }
54
+ }>
55
+ expectTypeOf<Profile>().toHaveProperty("id")
56
+ })
57
+ })
@@ -10,12 +10,11 @@ describe("BucketStorageAccess", () => {
10
10
  })
11
11
 
12
12
  it("accepts a fully declared bucket", () => {
13
- const crud = {} as {
13
+ expectTypeOf<{
14
14
  read: BucketPublic
15
15
  create: BucketLoggedIn
16
16
  update: BucketOwner
17
17
  delete: BucketOwner
18
- }
19
- expectTypeOf(crud).toExtend<BucketStorageAccess>()
18
+ }>().toExtend<BucketStorageAccess>()
20
19
  })
21
20
  })
@@ -0,0 +1,60 @@
1
+ import { describe, expectTypeOf, it } from "vitest"
2
+ import type {
3
+ AutoIncrement,
4
+ BigInt,
5
+ Float,
6
+ Generated,
7
+ Identity,
8
+ Int,
9
+ Model,
10
+ Optional,
11
+ PrimaryKey,
12
+ SmallInt,
13
+ TSVector,
14
+ } from "../src/index.js"
15
+
16
+ // The options form is the root: `Int<{ identity }>`, `Float<{ generated }>`. The aliases resolve to
17
+ // exactly it, so a schema may use either and the two read the same everywhere.
18
+ describe("identity and generated columns", () => {
19
+ it("resolves the aliases to the options form", () => {
20
+ expectTypeOf<Identity<number>>().toEqualTypeOf<Int<{ identity: "always" }>>()
21
+ expectTypeOf<Identity<bigint, "by-default">>().toEqualTypeOf<BigInt<{ identity: "by-default" }>>()
22
+ expectTypeOf<Identity>().toEqualTypeOf<Int<{ identity: "always" }>>()
23
+ expectTypeOf<AutoIncrement<number>>().toEqualTypeOf<Identity<number, "by-default">>()
24
+ expectTypeOf<AutoIncrement<bigint>>().toEqualTypeOf<BigInt<{ identity: "by-default" }>>()
25
+ })
26
+
27
+ it("keeps the value type of the column", () => {
28
+ expectTypeOf<Int<{ identity: "always" }>>().toExtend<number>()
29
+ expectTypeOf<BigInt<{ identity: "by-default" }>>().toExtend<bigint>()
30
+ expectTypeOf<Generated<string, "lower(name)">>().toExtend<string>()
31
+ expectTypeOf<Float<{ generated: "price * qty" }>>().toExtend<number>()
32
+ // A plain value is still assignable, as for every field type.
33
+ expectTypeOf<number>().toExtend<Int<{ identity: "always" }>>()
34
+ expectTypeOf<string>().toExtend<Generated<string, "lower(name)">>()
35
+ })
36
+
37
+ it("rejects options a type does not take", () => {
38
+ // @ts-expect-error identity is for integer fields only
39
+ type NotAnInteger = Float<{ identity: "always" }>
40
+ // @ts-expect-error the modes are "always" and "by-default"
41
+ type NoSuchMode = Int<{ identity: "sometimes" }>
42
+ // @ts-expect-error an expression is SQL text
43
+ type NotText = TSVector<{ generated: 1 }>
44
+ // @ts-expect-error an identity column is an integer
45
+ type NotNumbered = Identity<string>
46
+ expectTypeOf<[NotAnInteger, NoSuchMode, NotText, NotNumbered]>().not.toBeNever()
47
+ })
48
+
49
+ it("reads as an ordinary column on the model's row", () => {
50
+ type Post = Model<{
51
+ id: PrimaryKey<Identity<number>>
52
+ rank: SmallInt<{ identity: "by-default" }>
53
+ title: string
54
+ title_lower: Optional<Generated<string, "lower(title)">>
55
+ }>
56
+ expectTypeOf<Post["id"]>().toExtend<number>()
57
+ expectTypeOf<Post["rank"]>().toExtend<number>()
58
+ expectTypeOf<NonNullable<Post["title_lower"]>>().toExtend<string>()
59
+ })
60
+ })