@supatype/types 0.1.6 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +10 -8
- package/.turbo/turbo-typecheck.log +2 -2
- package/dist/index.d.ts +432 -26
- package/dist/index.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +524 -70
- package/tests/modifier-unwrap.test.ts +41 -0
- package/tests/primitives.test.ts +52 -85
- package/tests/relation-cycles.test.ts +50 -0
- package/tsconfig.test.json +26 -0
- package/tsconfig.tsbuildinfo +1 -1
package/src/index.ts
CHANGED
|
@@ -3,14 +3,46 @@ import type { SerializedEditorState } from "./lexical.js"
|
|
|
3
3
|
declare const SUPATYPE_TYPE: unique symbol
|
|
4
4
|
declare const SUPATYPE_MODEL: unique symbol
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
/**
|
|
7
|
+
* A value type wearing a compile-time label.
|
|
8
|
+
*
|
|
9
|
+
* Named for what it does rather than the community's "branded types" idiom, which reads as content
|
|
10
|
+
* vocabulary in a package that also exports `Block`, `Blocks` and `Localized`.
|
|
11
|
+
*
|
|
12
|
+
* The phantom property is **optional**, which is what keeps values usable: `id.toUpperCase()` works and
|
|
13
|
+
* a plain string can be assigned to a `UUID`. It also means the label is not reliably *detectable* — any
|
|
14
|
+
* type structurally satisfies a tag whose only property is optional — so this is for things that are
|
|
15
|
+
* values (`UUID`, an access rule, the model marker) and never for field declarations. Declarations use
|
|
16
|
+
* a required discriminator instead; see `Modifier`.
|
|
17
|
+
*
|
|
18
|
+
* Two differently-tagged types do repel each other (`Email` is not a `UUID`), but only because
|
|
19
|
+
* `exactOptionalPropertyTypes` is on. Erased at runtime: no value ever carries the property.
|
|
20
|
+
*/
|
|
21
|
+
type Tagged<TShape, TTag extends string> = TShape & {
|
|
7
22
|
readonly [SUPATYPE_TYPE]?: { readonly tag: TTag }
|
|
8
23
|
}
|
|
9
24
|
|
|
10
|
-
type Primitive<TName extends string, TShape> =
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
25
|
+
type Primitive<TName extends string, TShape> = Tagged<TShape, `primitive:${TName}`>
|
|
26
|
+
/**
|
|
27
|
+
* A field *declaration* wrapper — `Optional<string>`, `Unique<Slug>`, `Localized<RichText>`.
|
|
28
|
+
*
|
|
29
|
+
* **Nominal, with a required discriminator**, unlike `Tagged`. Nobody ever holds a value of type
|
|
30
|
+
* `Optional<string>`: you declare a field with it and read the row shape `Model<>` derives, so this does
|
|
31
|
+
* not need to be assignable to its own inner type — and making it so was the cause of three defects.
|
|
32
|
+
*
|
|
33
|
+
* As an intersection carrying an optional tag, every type satisfied `Modifier<Name, infer _>`: a plain
|
|
34
|
+
* `string` reported as `Optional`, so unwrapping never reached a fixed point (`TS2589` on reading any
|
|
35
|
+
* optional field), `Optional<FileAsset<B>>` collapsed to `never`, and stacked modifiers lost their tag
|
|
36
|
+
* to an intersection so only structural matching could see the outer one. A required property is
|
|
37
|
+
* exactly what the relation types already use (`__relationKind`), which is why relation detection was
|
|
38
|
+
* never broken.
|
|
39
|
+
*/
|
|
40
|
+
type Modifier<TName extends string, TInner> = {
|
|
41
|
+
readonly __modifier: TName
|
|
42
|
+
readonly __inner: TInner
|
|
43
|
+
}
|
|
44
|
+
type Relation<TName extends string, TInner> = Tagged<TInner, `relation:${TName}`>
|
|
45
|
+
type Access<TName extends string, TShape = { readonly kind: TName }> = Tagged<TShape, `access:${TName}`>
|
|
14
46
|
|
|
15
47
|
export type UUID = Primitive<"UUID", string>
|
|
16
48
|
export type Email = Primitive<"Email", string>
|
|
@@ -43,10 +75,19 @@ export type DateTime = Primitive<"DateTime", Date>
|
|
|
43
75
|
export type Timestamp = Primitive<"Timestamp", Date>
|
|
44
76
|
export type Geo = Primitive<"Geo", { type: "point" | "polygon" | "linestring"; coordinates: unknown }>
|
|
45
77
|
|
|
78
|
+
/** Source text with the language it is written in. Stored as `JSONB`. */
|
|
46
79
|
export type Code<Lang extends string = string> = Primitive<"Code", { lang: Lang; source: string }>
|
|
47
80
|
export type Duration = Primitive<"Duration", { ms: number }>
|
|
48
81
|
export type GeoPoint = Primitive<"GeoPoint", { lat: number; lng: number }>
|
|
49
|
-
|
|
82
|
+
/**
|
|
83
|
+
* An amount in minor units with the currency it is denominated in. Stored as `JSONB`.
|
|
84
|
+
*
|
|
85
|
+
* `amount` is a **string**, like {@link Money} and {@link Decimal}, because the value crosses the
|
|
86
|
+
* wire as JSON: `bigint` cannot be serialised (`JSON.stringify(1n)` throws) and `number` loses
|
|
87
|
+
* integers past 2^53. Use {@link Money} or {@link Decimal} instead when you want a numeric column
|
|
88
|
+
* to sum and index — this type keeps the currency with the amount, which a scalar column cannot.
|
|
89
|
+
*/
|
|
90
|
+
export type Currency<Code extends string = string> = Primitive<"Currency", { amount: string; code: Code }>
|
|
50
91
|
|
|
51
92
|
/** Link target for {@link Button}. */
|
|
52
93
|
export type ButtonTarget = "_self" | "_blank"
|
|
@@ -239,20 +280,58 @@ export type WithSoftDelete<T extends Record<string, unknown>> = T & SoftDelete
|
|
|
239
280
|
export type WithPublishable<T extends Record<string, unknown>> = T & Publishable
|
|
240
281
|
|
|
241
282
|
export type OnDelete = "cascade" | "setNull" | "restrict" | "noAction"
|
|
283
|
+
export type OnUpdate = OnDelete
|
|
284
|
+
/**
|
|
285
|
+
* Options on a relation field.
|
|
286
|
+
*
|
|
287
|
+
* Only what the extractor reads. `inverse` used to be declared here and was honoured by nothing,
|
|
288
|
+
* which is worse than absent: it type-checked, so a schema could name an inverse relation and get
|
|
289
|
+
* silence. The inverse side is declared as its own `HasMany<…>` / `HasOne<…>` field instead.
|
|
290
|
+
*/
|
|
242
291
|
export type RelationOptions = {
|
|
292
|
+
/** `NOT NULL` on the foreign key column. */
|
|
243
293
|
required?: boolean
|
|
244
294
|
onDelete?: OnDelete
|
|
245
|
-
|
|
295
|
+
onUpdate?: OnUpdate
|
|
296
|
+
/** `ManyToMany` only — the junction table's name, instead of one derived from the two models. */
|
|
297
|
+
through?: string
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* The target model, held behind a property so that resolving a relation field does not resolve the
|
|
301
|
+
* model it points at.
|
|
302
|
+
*
|
|
303
|
+
* Two models that name each other — a `HasOne` and its `RelatedTo`, or a `RelatedTo` both ways —
|
|
304
|
+
* used to fail with `TS2589: Type instantiation is excessively deep`. `Model<F>` spreads `F` through
|
|
305
|
+
* a mapped type that probes every field (`[V] extends [Modifier<"Optional", …>]`), and probing
|
|
306
|
+
* `RelatedTo<Post>` = `Post & …` meant expanding `Post`, which was still being defined. The
|
|
307
|
+
* collection relations escaped it: `Comment[]` is decidable without expanding `Comment`, so
|
|
308
|
+
* `HasMany` and `ManyToMany` are left as they were and only the one-ish relations defer here.
|
|
309
|
+
*
|
|
310
|
+
* Nothing needs a relation field's value type — the target's *identity* carries the relation, the
|
|
311
|
+
* generated client types carry the row shapes, and the CLI reads these declarations as syntax
|
|
312
|
+
* rather than resolving them. So the target moves into a phantom property, where TypeScript leaves
|
|
313
|
+
* it alone until something asks.
|
|
314
|
+
*/
|
|
315
|
+
export interface RelationTarget<T> {
|
|
316
|
+
readonly __relationTarget?: T
|
|
246
317
|
}
|
|
247
|
-
export type RelatedTo<T, TOptions extends RelationOptions = {}> = Relation<
|
|
318
|
+
export type RelatedTo<T, TOptions extends RelationOptions = {}> = Relation<
|
|
319
|
+
"RelatedTo",
|
|
320
|
+
RelationTarget<T>
|
|
321
|
+
> & {
|
|
248
322
|
readonly __relationOptions?: TOptions
|
|
249
323
|
readonly __relationKind: "relatedTo"
|
|
250
324
|
}
|
|
325
|
+
// `HasMany` and `ManyToMany` keep the plain `T[]`: an array is already decidable without expanding
|
|
326
|
+
// its element, which is why the collection relations never hit the recursion in the first place.
|
|
251
327
|
export type HasMany<T, TOptions extends RelationOptions = {}> = Relation<"HasMany", T[]> & {
|
|
252
328
|
readonly __relationOptions?: TOptions
|
|
253
329
|
readonly __relationKind: "hasMany"
|
|
254
330
|
}
|
|
255
|
-
export type HasOne<T, TOptions extends RelationOptions = {}> = Relation<
|
|
331
|
+
export type HasOne<T, TOptions extends RelationOptions = {}> = Relation<
|
|
332
|
+
"HasOne",
|
|
333
|
+
RelationTarget<T> | null
|
|
334
|
+
> & {
|
|
256
335
|
readonly __relationOptions?: TOptions
|
|
257
336
|
readonly __relationKind: "hasOne"
|
|
258
337
|
}
|
|
@@ -335,6 +414,223 @@ export type OwnerFrom<TRelationField extends string> = Access<"OwnerFrom", {
|
|
|
335
414
|
readonly relation: TRelationField
|
|
336
415
|
}>
|
|
337
416
|
export type Role<R extends string = string> = Access<"Role", { readonly kind: "Role"; readonly role: R }>
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* OR-composition: access is granted when **any** listed rule matches.
|
|
420
|
+
*
|
|
421
|
+
* Without this, rules are a closed set of single shapes and the commonest real
|
|
422
|
+
* requirement — "an admin, or the owner" — cannot be written at all. Every rule
|
|
423
|
+
* is combinable, including nested `Any`.
|
|
424
|
+
*
|
|
425
|
+
* ```typescript
|
|
426
|
+
* access: { update: Any<[Role<"admin">, Owner<"author_id">]> }
|
|
427
|
+
* ```
|
|
428
|
+
*
|
|
429
|
+
* Compiles to the rules joined with `OR`. An empty list is rejected at extract
|
|
430
|
+
* time rather than compiling to a policy that grants nothing.
|
|
431
|
+
*/
|
|
432
|
+
export type Any<TRules extends readonly unknown[]> = Access<"Any", {
|
|
433
|
+
readonly kind: "Any"
|
|
434
|
+
readonly rules: TRules
|
|
435
|
+
}>
|
|
436
|
+
|
|
437
|
+
/** AND-composition: access needs **every** listed rule to match. */
|
|
438
|
+
export type All<TRules extends readonly unknown[]> = Access<"All", {
|
|
439
|
+
readonly kind: "All"
|
|
440
|
+
readonly rules: TRules
|
|
441
|
+
}>
|
|
442
|
+
|
|
443
|
+
/** Negation. `Not<Role<"banned">>` grants access to everyone but that role. */
|
|
444
|
+
export type Not<TRule> = Access<"Not", { readonly kind: "Not"; readonly rule: TRule }>
|
|
445
|
+
|
|
446
|
+
// ─── Operands ────────────────────────────────────────────────────────────────
|
|
447
|
+
//
|
|
448
|
+
// The values a comparison can name. A bare string is a column on the model the
|
|
449
|
+
// rule is attached to; everything else is one of these.
|
|
450
|
+
|
|
451
|
+
/** The signed-in user's id. Compiles to `auth.uid()`, evaluated once per query. */
|
|
452
|
+
export type AuthUid = Access<"AuthUid", { readonly kind: "AuthUid" }>
|
|
453
|
+
|
|
454
|
+
/** The caller's role. Compiles to `auth.role()`, evaluated once per query. */
|
|
455
|
+
export type AuthRole = Access<"AuthRole", { readonly kind: "AuthRole" }>
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* A nested JWT claim, by dotted path: `Claim<"app_metadata.tier">`.
|
|
459
|
+
*
|
|
460
|
+
* This is the developer's own namespace — whatever your application puts in its
|
|
461
|
+
* tokens. A missing claim is SQL NULL, so comparing against one that is absent
|
|
462
|
+
* denies rather than erroring.
|
|
463
|
+
*/
|
|
464
|
+
export type Claim<TPath extends string> = Access<"Claim", {
|
|
465
|
+
readonly kind: "Claim"
|
|
466
|
+
readonly path: TPath
|
|
467
|
+
}>
|
|
468
|
+
|
|
469
|
+
/** A constant. Bare strings in a comparison mean *columns*, so literals are explicit. */
|
|
470
|
+
export type Literal<TValue extends string | number | boolean> = Access<"Literal", {
|
|
471
|
+
readonly kind: "Literal"
|
|
472
|
+
readonly value: TValue
|
|
473
|
+
}>
|
|
474
|
+
|
|
475
|
+
// ─── Time ────────────────────────────────────────────────────────────────────
|
|
476
|
+
//
|
|
477
|
+
// A closed set of temporal operands. Closed on purpose: it keeps `now()` (which is
|
|
478
|
+
// STABLE, and evaluated once per query) as the only clock a rule can read.
|
|
479
|
+
// `clock_timestamp()` is VOLATILE and would make the generated affordance
|
|
480
|
+
// functions' STABLE declaration a lie.
|
|
481
|
+
//
|
|
482
|
+
// There is deliberately no literal-timestamp operand. "Publish at 09:00 next
|
|
483
|
+
// Tuesday" is *data* — the row carries `published_at`, and the rule is the same for
|
|
484
|
+
// every row: `Lte<"published_at", Now>`. The policy re-evaluates per query, so the
|
|
485
|
+
// row starts matching at 09:00 with no cron and no publish worker.
|
|
486
|
+
|
|
487
|
+
/** Transaction start time (`now()`). */
|
|
488
|
+
export type Now = Access<"Now", { readonly kind: "Now" }>
|
|
489
|
+
|
|
490
|
+
/** Units for {@link Ago} / {@link FromNow}. Plural only — Postgres accepts both. */
|
|
491
|
+
export type TimeUnit =
|
|
492
|
+
| "seconds"
|
|
493
|
+
| "minutes"
|
|
494
|
+
| "hours"
|
|
495
|
+
| "days"
|
|
496
|
+
| "weeks"
|
|
497
|
+
| "months"
|
|
498
|
+
| "years"
|
|
499
|
+
|
|
500
|
+
/** Granularity for {@link StartOf}. */
|
|
501
|
+
export type TruncUnit = "day" | "week" | "month" | "year"
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* The start of the current day, week, month or year — `date_trunc(unit, now())`.
|
|
505
|
+
*
|
|
506
|
+
* `Gte<"created_at", StartOf<"week">>` is "created since Monday".
|
|
507
|
+
*/
|
|
508
|
+
export type StartOf<TUnit extends TruncUnit> = Access<"StartOf", {
|
|
509
|
+
readonly kind: "StartOf"
|
|
510
|
+
readonly unit: TUnit
|
|
511
|
+
}>
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* A duration before now: `Ago<30, "days">` is `now() - INTERVAL '30 days'`.
|
|
515
|
+
*
|
|
516
|
+
* Two arguments rather than one `"30 days"` string, for two reasons. A template
|
|
517
|
+
* literal `` `${number} ${TimeUnit}` `` accepts `"-5 days"`, `"0.5 days"` and
|
|
518
|
+
* `"1e3 days"` — the last is not valid interval syntax, so it type-checks and fails
|
|
519
|
+
* at push. And TypeScript cannot enumerate `${number}`, so a template literal offers
|
|
520
|
+
* **no autocomplete**; this form completes the unit properly.
|
|
521
|
+
*
|
|
522
|
+
* The amount must be a positive integer — for the other direction use
|
|
523
|
+
* {@link FromNow}, which reads correctly rather than relying on a double negative.
|
|
524
|
+
*/
|
|
525
|
+
export type Ago<TAmount extends number, TUnit extends TimeUnit> = Access<"Ago", {
|
|
526
|
+
readonly kind: "Ago"
|
|
527
|
+
readonly amount: TAmount
|
|
528
|
+
readonly unit: TUnit
|
|
529
|
+
}>
|
|
530
|
+
|
|
531
|
+
/** A duration after now: `FromNow<7, "days">` is `now() + INTERVAL '7 days'`. */
|
|
532
|
+
export type FromNow<TAmount extends number, TUnit extends TimeUnit> = Access<"FromNow", {
|
|
533
|
+
readonly kind: "FromNow"
|
|
534
|
+
readonly amount: TAmount
|
|
535
|
+
readonly unit: TUnit
|
|
536
|
+
}>
|
|
537
|
+
|
|
538
|
+
// ─── Comparisons ─────────────────────────────────────────────────────────────
|
|
539
|
+
|
|
540
|
+
type Comparison<TName extends string, TLeft, TRight> = Access<TName, {
|
|
541
|
+
readonly kind: TName
|
|
542
|
+
readonly left: TLeft
|
|
543
|
+
readonly right: TRight
|
|
544
|
+
}>
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* `Eq<"author_id", AuthUid>` — the row's `author_id` equals the caller.
|
|
548
|
+
*
|
|
549
|
+
* A bare string on either side is a column name; use `Literal<…>` for a constant,
|
|
550
|
+
* so `Eq<"status", Literal<"published">>` cannot be confused with a comparison
|
|
551
|
+
* between two columns.
|
|
552
|
+
*/
|
|
553
|
+
export type Eq<TLeft, TRight> = Comparison<"Eq", TLeft, TRight>
|
|
554
|
+
export type Neq<TLeft, TRight> = Comparison<"Neq", TLeft, TRight>
|
|
555
|
+
export type Gt<TLeft, TRight> = Comparison<"Gt", TLeft, TRight>
|
|
556
|
+
export type Gte<TLeft, TRight> = Comparison<"Gte", TLeft, TRight>
|
|
557
|
+
export type Lt<TLeft, TRight> = Comparison<"Lt", TLeft, TRight>
|
|
558
|
+
export type Lte<TLeft, TRight> = Comparison<"Lte", TLeft, TRight>
|
|
559
|
+
export type Like<TLeft, TRight> = Comparison<"Like", TLeft, TRight>
|
|
560
|
+
|
|
561
|
+
/**
|
|
562
|
+
* `IsNull<"deleted_at">` / `NotNull<"published_at">`.
|
|
563
|
+
*
|
|
564
|
+
* Separate from `Eq`, because SQL null comparison is not equality: `col = NULL`
|
|
565
|
+
* is null, never true, so writing it that way would deny everything silently.
|
|
566
|
+
*/
|
|
567
|
+
export type IsNull<TOperand> = Access<"IsNull", { readonly kind: "IsNull"; readonly operand: TOperand }>
|
|
568
|
+
export type NotNull<TOperand> = Access<"NotNull", { readonly kind: "NotNull"; readonly operand: TOperand }>
|
|
569
|
+
|
|
570
|
+
// ─── Membership ──────────────────────────────────────────────────────────────
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* Rows of another table, narrowed by a rule: the source for a membership test.
|
|
574
|
+
*
|
|
575
|
+
* ```typescript
|
|
576
|
+
* type MySites = Rows<"user_sites", "site_id", Eq<"user_id", AuthUid>>
|
|
577
|
+
* ```
|
|
578
|
+
*
|
|
579
|
+
* The `Where` rule is evaluated against `user_sites`, not against the model the
|
|
580
|
+
* access rule is attached to — it is what makes this *the caller's* sites rather
|
|
581
|
+
* than every row in the join table.
|
|
582
|
+
*
|
|
583
|
+
* Because the join column is named here, the engine emits the index for it. The
|
|
584
|
+
* classic RLS performance trap is a membership subquery scanning an unindexed join
|
|
585
|
+
* table once per row tested; naming it makes that generated infrastructure.
|
|
586
|
+
*/
|
|
587
|
+
export type Rows<
|
|
588
|
+
TTable extends string,
|
|
589
|
+
TColumn extends string,
|
|
590
|
+
TWhere = never,
|
|
591
|
+
> = Access<"Rows", {
|
|
592
|
+
readonly kind: "Rows"
|
|
593
|
+
readonly table: TTable
|
|
594
|
+
readonly column: TColumn
|
|
595
|
+
readonly where: TWhere
|
|
596
|
+
}>
|
|
597
|
+
|
|
598
|
+
/** A fixed set, for `In<"status", Values<["draft", "review"]>>`. */
|
|
599
|
+
export type Values<TItems extends readonly (string | number | boolean)[]> = Access<"Values", {
|
|
600
|
+
readonly kind: "Values"
|
|
601
|
+
readonly values: TItems
|
|
602
|
+
}>
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* `In<"site_id", MySites>` — the row's column appears in the source set.
|
|
606
|
+
*
|
|
607
|
+
* Compiles to a semi-join (`EXISTS`), not `IN (SELECT …)`, so the planner stops at
|
|
608
|
+
* the first match per row instead of materialising the set. Sources are `Rows<>`,
|
|
609
|
+
* `Claim<>` (a claim holding an array) or `Values<>`.
|
|
610
|
+
*/
|
|
611
|
+
export type In<TColumn extends string, TSource> = Access<"In", {
|
|
612
|
+
readonly kind: "In"
|
|
613
|
+
readonly column: TColumn
|
|
614
|
+
readonly source: TSource
|
|
615
|
+
}>
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* The source set is non-empty, independent of any column.
|
|
619
|
+
*
|
|
620
|
+
* `In<>` asks "is this row's value in the set", which is a different question.
|
|
621
|
+
* Guarding on `Exists<>` is what makes "an editor *who has sites* may see their
|
|
622
|
+
* sites or unassigned rows" mean what it says — without it, an editor with no sites
|
|
623
|
+
* still matches the unassigned branch:
|
|
624
|
+
*
|
|
625
|
+
* ```typescript
|
|
626
|
+
* type MySites = Rows<"user_sites", "site_id", Eq<"user_id", AuthUid>>
|
|
627
|
+
* All<[Role<"editor">, Exists<MySites>, Any<[In<"site_id", MySites>, IsNull<"site_id">]>]>
|
|
628
|
+
* ```
|
|
629
|
+
*/
|
|
630
|
+
export type Exists<TSource> = Access<"Exists", {
|
|
631
|
+
readonly kind: "Exists"
|
|
632
|
+
readonly source: TSource
|
|
633
|
+
}>
|
|
338
634
|
type BoundOwnerForFields<TFields extends Record<string, unknown>> = Access<"Owner", {
|
|
339
635
|
readonly kind: "Owner"
|
|
340
636
|
readonly key: OwnerEligibleFieldKeys<TFields>
|
|
@@ -345,18 +641,96 @@ type BoundOwnerFromForFields<TFields extends Record<string, unknown>> = Access<"
|
|
|
345
641
|
readonly relation: RelationFieldKeys<TFields>
|
|
346
642
|
}>
|
|
347
643
|
|
|
348
|
-
/**
|
|
349
|
-
|
|
644
|
+
/**
|
|
645
|
+
* The composable half of the DSL — every shape that takes other rules or operands
|
|
646
|
+
* as arguments.
|
|
647
|
+
*
|
|
648
|
+
* Written with `unknown` arguments rather than a recursive constraint. TypeScript
|
|
649
|
+
* cannot thread the model's field names down through a tuple of nested rules
|
|
650
|
+
* without instantiation-depth failures on the deeper compositions, so a column
|
|
651
|
+
* named inside a composition is checked by Postgres when the policy is created,
|
|
652
|
+
* not by the editor. The named shapes below stay bound to the model's fields, so
|
|
653
|
+
* the common `Owner<…>` typo is still caught where it always was.
|
|
654
|
+
*/
|
|
655
|
+
type ComposedAccessRule =
|
|
656
|
+
| Any<readonly unknown[]>
|
|
657
|
+
| All<readonly unknown[]>
|
|
658
|
+
| Not<unknown>
|
|
659
|
+
| Eq<unknown, unknown>
|
|
660
|
+
| Neq<unknown, unknown>
|
|
661
|
+
| Gt<unknown, unknown>
|
|
662
|
+
| Gte<unknown, unknown>
|
|
663
|
+
| Lt<unknown, unknown>
|
|
664
|
+
| Lte<unknown, unknown>
|
|
665
|
+
| Like<unknown, unknown>
|
|
666
|
+
| IsNull<unknown>
|
|
667
|
+
| NotNull<unknown>
|
|
668
|
+
| In<string, unknown>
|
|
669
|
+
| Exists<unknown>
|
|
350
670
|
|
|
351
|
-
|
|
671
|
+
/**
|
|
672
|
+
* Any rule that may stand as an access predicate for a model.
|
|
673
|
+
*
|
|
674
|
+
* The named shapes stay bound to `TFields` so `Owner<"athor_id">` is still a typo
|
|
675
|
+
* the editor catches; the composed shapes are open, per the note above.
|
|
676
|
+
*/
|
|
677
|
+
export type AccessRuleFor<TFields extends Record<string, unknown>> =
|
|
678
|
+
| Public
|
|
679
|
+
| Private
|
|
680
|
+
| LoggedIn
|
|
681
|
+
| Owner<OwnerEligibleFieldKeys<TFields>>
|
|
682
|
+
| OwnerFrom<RelationFieldKeys<TFields>>
|
|
683
|
+
| BoundOwnerForFields<TFields>
|
|
684
|
+
| BoundOwnerFromForFields<TFields>
|
|
685
|
+
| Role<string>
|
|
686
|
+
| ComposedAccessRule
|
|
352
687
|
|
|
353
|
-
|
|
688
|
+
/**
|
|
689
|
+
* `update` as a plain rule, or split into its two halves.
|
|
690
|
+
*
|
|
691
|
+
* `using` picks which existing rows may be modified, `check` constrains what they
|
|
692
|
+
* may become. Unambiguous against a bare rule because every rule carries a `kind`
|
|
693
|
+
* and this object does not.
|
|
694
|
+
*/
|
|
695
|
+
type UpdateAccessFor<TFields extends Record<string, unknown>> =
|
|
696
|
+
| AccessRuleFor<TFields>
|
|
697
|
+
| {
|
|
698
|
+
readonly using: AccessRuleFor<TFields>
|
|
699
|
+
readonly check?: AccessRuleFor<TFields>
|
|
700
|
+
}
|
|
354
701
|
|
|
355
|
-
|
|
702
|
+
/**
|
|
703
|
+
* Which modifier a declaration is, or `never` for anything that is not one.
|
|
704
|
+
*
|
|
705
|
+
* Reads the required discriminator, so a plain type answers `never` rather than claiming to be whatever
|
|
706
|
+
* was asked. The bracketed comparison matters: `never` is assignable to everything, so a bare
|
|
707
|
+
* `ModifierNameOf<V> extends TName` would report *true* for every unwrapped value.
|
|
708
|
+
*/
|
|
709
|
+
type ModifierNameOf<V> = V extends { readonly __modifier: infer TName extends string } ? TName : never
|
|
710
|
+
type ModifierInnerOf<V> = V extends { readonly __inner: infer TInner } ? TInner : never
|
|
711
|
+
type IsModifier<V, TName extends string> = [ModifierNameOf<V>] extends [TName] ? true : false
|
|
356
712
|
|
|
357
|
-
type
|
|
713
|
+
type IsModifierOptional<V> = IsModifier<V, "Optional">
|
|
714
|
+
type InferOptionalInner<V> = ModifierInnerOf<V>
|
|
715
|
+
type IsModifierLocalized<V> = IsModifier<V, "Localized">
|
|
716
|
+
type InferLocalizedInner<V> = ModifierInnerOf<V>
|
|
717
|
+
type IsModifierNotLocalized<V> = IsModifier<V, "NotLocalized">
|
|
718
|
+
type InferNotLocalizedInner<V> = ModifierInnerOf<V>
|
|
358
719
|
|
|
359
|
-
|
|
720
|
+
/**
|
|
721
|
+
* Whether a field's key is optional on the row — `Optional` anywhere in the stack, not just outermost.
|
|
722
|
+
*
|
|
723
|
+
* `Unique<Optional<string>>` is as nullable as `Optional<Unique<string>>`. The old structural check
|
|
724
|
+
* could only see the outer wrapper, so which one you wrote decided whether the key was optional.
|
|
725
|
+
*/
|
|
726
|
+
type HasOptionalModifier<V> = V extends {
|
|
727
|
+
readonly __modifier: infer TName extends string
|
|
728
|
+
readonly __inner: infer TInner
|
|
729
|
+
}
|
|
730
|
+
? TName extends "Optional"
|
|
731
|
+
? true
|
|
732
|
+
: HasOptionalModifier<TInner>
|
|
733
|
+
: false
|
|
360
734
|
|
|
361
735
|
type ImageAssetLocalizedOption<V> =
|
|
362
736
|
V extends ImageAsset<infer _B, infer O> ? (O extends { localized: true } ? true : false) : false
|
|
@@ -364,15 +738,22 @@ type ImageAssetLocalizedOption<V> =
|
|
|
364
738
|
type FileAssetLocalizedOption<V> =
|
|
365
739
|
V extends FileAsset<infer _B, infer O> ? (O extends { localized: true } ? true : false) : false
|
|
366
740
|
|
|
367
|
-
/**
|
|
741
|
+
/**
|
|
742
|
+
* Apply default localization to copy-like fields (used by {@link LocalizedModel}).
|
|
743
|
+
*
|
|
744
|
+
* Walks *through* any modifier and rebuilds it around the localized inner, so `Unique<string>` becomes
|
|
745
|
+
* `Unique<Localized<string>>`. It used to reach the `V extends string` branch for such a field — a
|
|
746
|
+
* modifier was structurally its own inner type — and return a bare `Localized<string>`, silently
|
|
747
|
+
* dropping the `Unique`.
|
|
748
|
+
*/
|
|
368
749
|
type ApplyAutoLocalizedField<V> =
|
|
369
|
-
|
|
370
|
-
?
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
: IsModifierLocalized<V> extends true
|
|
750
|
+
V extends { readonly __modifier: infer TName extends string; readonly __inner: infer TInner }
|
|
751
|
+
? TName extends "NotLocalized"
|
|
752
|
+
? TInner
|
|
753
|
+
: TName extends "Localized"
|
|
374
754
|
? V
|
|
375
|
-
:
|
|
755
|
+
: { readonly __modifier: TName; readonly __inner: ApplyAutoLocalizedField<TInner> }
|
|
756
|
+
: V extends string
|
|
376
757
|
? Localized<string>
|
|
377
758
|
: V extends RichText
|
|
378
759
|
? Localized<RichText>
|
|
@@ -390,26 +771,31 @@ type ApplyAutoLocalizedFields<TFields extends Record<string, unknown>> = {
|
|
|
390
771
|
[K in keyof TFields]: ApplyAutoLocalizedField<TFields[K]>
|
|
391
772
|
}
|
|
392
773
|
|
|
393
|
-
/**
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
774
|
+
/**
|
|
775
|
+
* The value a declared field reads as on the row: every modifier peeled off, whatever it is.
|
|
776
|
+
*
|
|
777
|
+
* Unbounded and still terminating, because each step removes one wrapper — `__inner` is strictly
|
|
778
|
+
* smaller than the type it came from. The previous version needed a depth cap to escape a recursion
|
|
779
|
+
* that could not converge, and a cap that runs out returns a half-unwrapped type rather than an error.
|
|
780
|
+
*
|
|
781
|
+
* Every modifier, not the three that used to be special-cased: a declaration is no longer structurally
|
|
782
|
+
* its own inner type, so `Unique<Slug>` would otherwise surface on the row as the wrapper object rather
|
|
783
|
+
* than as a string. `Localized<T>` needs no case of its own — its inner already *is* the locale record.
|
|
784
|
+
*/
|
|
785
|
+
type UnwrapModelFieldType<V> = V extends { readonly __modifier: string; readonly __inner: infer TInner }
|
|
786
|
+
? UnwrapModelFieldType<TInner>
|
|
787
|
+
: V
|
|
402
788
|
|
|
403
789
|
/** Row shape from `TFields`: `Optional<…>` → `key?: Inner` (`Inner` includes `null`). */
|
|
404
790
|
export type SpreadOptionalModelFields<TFields extends Record<string, unknown>> =
|
|
405
791
|
keyof TFields extends never
|
|
406
792
|
? {}
|
|
407
793
|
: {
|
|
408
|
-
[K in keyof TFields as
|
|
794
|
+
[K in keyof TFields as HasOptionalModifier<TFields[K]> extends true ? never : K]: UnwrapModelFieldType<
|
|
409
795
|
TFields[K]
|
|
410
796
|
>
|
|
411
797
|
} & {
|
|
412
|
-
[K in keyof TFields as
|
|
798
|
+
[K in keyof TFields as HasOptionalModifier<TFields[K]> extends true
|
|
413
799
|
? K extends keyof TFields & (string | number)
|
|
414
800
|
? K
|
|
415
801
|
: never
|
|
@@ -424,42 +810,60 @@ export type ModelIndex = {
|
|
|
424
810
|
|
|
425
811
|
export type ModelMeta<TFields extends Record<string, unknown>> = {
|
|
426
812
|
access?: {
|
|
427
|
-
read?:
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
813
|
+
read?: AccessRuleFor<TFields>
|
|
814
|
+
create?: AccessRuleFor<TFields>
|
|
815
|
+
update?: UpdateAccessFor<TFields>
|
|
816
|
+
delete?: AccessRuleFor<TFields>
|
|
817
|
+
/**
|
|
818
|
+
* Per-column rules, narrowing the table rules for one field.
|
|
819
|
+
*
|
|
820
|
+
* ```typescript
|
|
821
|
+
* access: {
|
|
822
|
+
* read: Public,
|
|
823
|
+
* fields: { salary: { read: Owner<"user_id">, write: Role<"admin"> } },
|
|
824
|
+
* }
|
|
825
|
+
* ```
|
|
826
|
+
*
|
|
827
|
+
* The **full rule language** applies, row-dependent rules included. A caller who
|
|
828
|
+
* may not read the column gets `null` rather than a 403, because `SELECT *` names
|
|
829
|
+
* every column and a revoked one would take the whole table down with it. Column
|
|
830
|
+
* privileges are layered underneath for writes only, as defence in depth.
|
|
831
|
+
*
|
|
832
|
+
* Enforced one of two ways, chosen from what the database can do: the
|
|
833
|
+
* `supatype_mask` extension rewrites every reference to the column in the planner,
|
|
834
|
+
* and where the extension cannot be loaded — most managed Postgres — the same
|
|
835
|
+
* expression is carried by generated views in an `api` schema instead.
|
|
836
|
+
*
|
|
837
|
+
* A `write` rule is compiled conjoined with the field's `read` rule, so write
|
|
838
|
+
* without read is unrepresentable — otherwise a caller could round-trip away a
|
|
839
|
+
* value they were never shown.
|
|
840
|
+
*
|
|
841
|
+
* **`INSERT` cannot evaluate a row-dependent write rule**: there is no row
|
|
842
|
+
* yet, so the column falls back to its default instead of accepting the
|
|
843
|
+
* submitted value. Use an identity-only rule (`Role<>`, `LoggedIn`,
|
|
844
|
+
* `Claim<>`) for a column that must be settable at creation time.
|
|
845
|
+
*
|
|
846
|
+
* Relations are named by their column (`author_id`), because that is what the
|
|
847
|
+
* restriction applies to — `author` is not a column at all.
|
|
848
|
+
*
|
|
849
|
+
* Neither tier half-enforces: a push never applies a schema whose restrictions do
|
|
850
|
+
* not exist. They differ in one place — under the view tier an aggregate over a
|
|
851
|
+
* masked column returns the sum of the rows the caller may read, where the
|
|
852
|
+
* extension raises an error. Unreachable through the API, since PostgREST ships
|
|
853
|
+
* with aggregates disabled.
|
|
854
|
+
*
|
|
855
|
+
* A column restricted from nearly everyone and queried often is still better off
|
|
856
|
+
* in its own table — masking costs a predicate call per row and cannot use the
|
|
857
|
+
* column's index.
|
|
858
|
+
*/
|
|
859
|
+
fields?: {
|
|
860
|
+
// Relations are named by their column (`author_id`), because that is what a
|
|
861
|
+
// privilege is granted on — `author` is not a column at all.
|
|
862
|
+
readonly [K in (keyof TFields & string) | RelationOwnerKeys<TFields>]?: {
|
|
863
|
+
readonly read?: AccessRuleFor<TFields>
|
|
864
|
+
readonly write?: AccessRuleFor<TFields>
|
|
865
|
+
}
|
|
866
|
+
}
|
|
463
867
|
}
|
|
464
868
|
tableName?: string
|
|
465
869
|
searchable?: readonly string[]
|
|
@@ -473,6 +877,56 @@ export type ModelMeta<TFields extends Record<string, unknown>> = {
|
|
|
473
877
|
softDelete?: boolean
|
|
474
878
|
/** When true, copy-like fields default to localized (same as {@link LocalizedModel}). */
|
|
475
879
|
autoLocalize?: true
|
|
880
|
+
/**
|
|
881
|
+
* Lifecycle hooks — an **edge function** run by the API at a write boundary.
|
|
882
|
+
*
|
|
883
|
+
* ```typescript
|
|
884
|
+
* hooks: {
|
|
885
|
+
* beforeChange: "moderate-post",
|
|
886
|
+
* afterChange: { function: "index-post", timeout: 5000 },
|
|
887
|
+
* }
|
|
888
|
+
* ```
|
|
889
|
+
*
|
|
890
|
+
* The value names a function directory under your project's `functions/`, and the name is
|
|
891
|
+
* checked when you push — a hook that silently never fires because of a typo is the failure
|
|
892
|
+
* this feature must not have. `supatype push` also generates a typed handler signature per
|
|
893
|
+
* hooked model, so `row` is the model's real column set rather than `unknown`.
|
|
894
|
+
*
|
|
895
|
+
* **A hook is not a security boundary.** It fires for writes through the API; direct SQL,
|
|
896
|
+
* seeds, migrations and anything holding `service_role` bypass it. Invariants belong in
|
|
897
|
+
* {@link ModelMeta.access}, a `CHECK`, or a generated column — all of which apply to every
|
|
898
|
+
* writer. A hook is for the work that is genuinely application logic: enrichment,
|
|
899
|
+
* notification, indexing, a validation the database cannot express.
|
|
900
|
+
*
|
|
901
|
+
* `beforeChange` and `beforeDelete` are called before the write reaches Postgres and can
|
|
902
|
+
* reject it (any `4xx` from the function) or replace its body. `afterChange` and
|
|
903
|
+
* `afterDelete` run once the write has succeeded and cannot change it.
|
|
904
|
+
*/
|
|
905
|
+
hooks?: {
|
|
906
|
+
readonly beforeChange?: ModelHook
|
|
907
|
+
readonly afterChange?: ModelHook
|
|
908
|
+
readonly beforeDelete?: ModelHook
|
|
909
|
+
readonly afterDelete?: ModelHook
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/** A hook: a function name, or that name with per-hook options. */
|
|
914
|
+
export type ModelHook = string | ModelHookOptions
|
|
915
|
+
|
|
916
|
+
export type ModelHookOptions = {
|
|
917
|
+
/** Function directory under the project's `functions/`. */
|
|
918
|
+
readonly function: string
|
|
919
|
+
/** Milliseconds before the hook is abandoned. Default 2000. */
|
|
920
|
+
readonly timeout?: number
|
|
921
|
+
/**
|
|
922
|
+
* What it means when the hook **does not answer** — a timeout, a connection failure, a `5xx`,
|
|
923
|
+
* or a body that cannot be parsed. A `4xx` is not this: that is the hook working correctly and
|
|
924
|
+
* saying no, and it reaches the caller as the status the hook chose.
|
|
925
|
+
*
|
|
926
|
+
* Defaults to `"reject"` before a write (a validation hook that stopped running must not let
|
|
927
|
+
* writes through) and `"log"` after one (the write already happened; there is nothing to fail).
|
|
928
|
+
*/
|
|
929
|
+
readonly onUnavailable?: "reject" | "log"
|
|
476
930
|
}
|
|
477
931
|
|
|
478
932
|
/** Shorthand for singleton globals — `Model<Fields, GlobalMeta<Fields>>`. */
|