@supatype/client 0.3.6 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +69 -30
  3. package/.turbo/turbo-typecheck.log +2 -2
  4. package/LICENSE +1 -1
  5. package/dist/auth-redirect.d.ts +48 -0
  6. package/dist/auth-redirect.d.ts.map +1 -0
  7. package/dist/auth-redirect.js +70 -0
  8. package/dist/auth-redirect.js.map +1 -0
  9. package/dist/auth.d.ts +86 -4
  10. package/dist/auth.d.ts.map +1 -1
  11. package/dist/auth.js +383 -275
  12. package/dist/auth.js.map +1 -1
  13. package/dist/bindings.d.ts +16 -0
  14. package/dist/bindings.d.ts.map +1 -0
  15. package/dist/bindings.js +13 -0
  16. package/dist/bindings.js.map +1 -0
  17. package/dist/caller-types.d.ts +18 -0
  18. package/dist/caller-types.d.ts.map +1 -0
  19. package/dist/caller-types.js +22 -0
  20. package/dist/caller-types.js.map +1 -0
  21. package/dist/draft-create.d.ts +12 -0
  22. package/dist/draft-create.d.ts.map +1 -0
  23. package/dist/draft-create.js +47 -0
  24. package/dist/draft-create.js.map +1 -0
  25. package/dist/draft-models-registry.d.ts +27 -0
  26. package/dist/draft-models-registry.d.ts.map +1 -0
  27. package/dist/draft-models-registry.js +61 -0
  28. package/dist/draft-models-registry.js.map +1 -0
  29. package/dist/error-codes-doc.d.ts +1 -1
  30. package/dist/error-codes-doc.d.ts.map +1 -1
  31. package/dist/error-codes-doc.js +42 -34
  32. package/dist/error-codes-doc.js.map +1 -1
  33. package/dist/errors.d.ts +102 -60
  34. package/dist/errors.d.ts.map +1 -1
  35. package/dist/errors.js +69 -28
  36. package/dist/errors.js.map +1 -1
  37. package/dist/exact-response.d.ts.map +1 -1
  38. package/dist/exact-response.js +2 -1
  39. package/dist/exact-response.js.map +1 -1
  40. package/dist/exact-values.d.ts +2 -0
  41. package/dist/exact-values.d.ts.map +1 -1
  42. package/dist/exact-values.js +12 -10
  43. package/dist/exact-values.js.map +1 -1
  44. package/dist/fetch-with-retry.d.ts +21 -6
  45. package/dist/fetch-with-retry.d.ts.map +1 -1
  46. package/dist/fetch-with-retry.js +67 -53
  47. package/dist/fetch-with-retry.js.map +1 -1
  48. package/dist/field-kinds-registry.d.ts +11 -3
  49. package/dist/field-kinds-registry.d.ts.map +1 -1
  50. package/dist/field-kinds-registry.js +10 -6
  51. package/dist/field-kinds-registry.js.map +1 -1
  52. package/dist/filters.d.ts +51 -0
  53. package/dist/filters.d.ts.map +1 -0
  54. package/dist/filters.js +117 -0
  55. package/dist/filters.js.map +1 -0
  56. package/dist/generated-client.d.ts +7 -0
  57. package/dist/generated-client.d.ts.map +1 -0
  58. package/dist/generated-client.js +7 -0
  59. package/dist/generated-client.js.map +1 -0
  60. package/dist/graphql-document.d.ts +39 -0
  61. package/dist/graphql-document.d.ts.map +1 -0
  62. package/dist/graphql-document.js +228 -0
  63. package/dist/graphql-document.js.map +1 -0
  64. package/dist/graphql-json.d.ts +56 -0
  65. package/dist/graphql-json.d.ts.map +1 -0
  66. package/dist/graphql-json.js +220 -0
  67. package/dist/graphql-json.js.map +1 -0
  68. package/dist/graphql-transport.d.ts +28 -0
  69. package/dist/graphql-transport.d.ts.map +1 -0
  70. package/dist/graphql-transport.js +77 -0
  71. package/dist/graphql-transport.js.map +1 -0
  72. package/dist/index.d.ts +103 -40
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +170 -165
  75. package/dist/index.js.map +1 -1
  76. package/dist/json.d.ts +61 -0
  77. package/dist/json.d.ts.map +1 -0
  78. package/dist/json.js +83 -0
  79. package/dist/json.js.map +1 -0
  80. package/dist/jwt.d.ts +16 -0
  81. package/dist/jwt.d.ts.map +1 -0
  82. package/dist/jwt.js +37 -0
  83. package/dist/jwt.js.map +1 -0
  84. package/dist/live-preview.d.ts +23 -0
  85. package/dist/live-preview.d.ts.map +1 -0
  86. package/dist/live-preview.js +28 -0
  87. package/dist/live-preview.js.map +1 -0
  88. package/dist/mutation-request.d.ts +17 -0
  89. package/dist/mutation-request.d.ts.map +1 -0
  90. package/dist/mutation-request.js +41 -0
  91. package/dist/mutation-request.js.map +1 -0
  92. package/dist/preview.d.ts.map +1 -1
  93. package/dist/preview.js +8 -6
  94. package/dist/preview.js.map +1 -1
  95. package/dist/query-cache.d.ts.map +1 -1
  96. package/dist/query-cache.js +19 -13
  97. package/dist/query-cache.js.map +1 -1
  98. package/dist/query.d.ts +108 -29
  99. package/dist/query.d.ts.map +1 -1
  100. package/dist/query.js +294 -224
  101. package/dist/query.js.map +1 -1
  102. package/dist/realtime.d.ts +57 -2
  103. package/dist/realtime.d.ts.map +1 -1
  104. package/dist/realtime.js +300 -88
  105. package/dist/realtime.js.map +1 -1
  106. package/dist/select-types.d.ts +99 -0
  107. package/dist/select-types.d.ts.map +1 -0
  108. package/dist/select-types.js +2 -0
  109. package/dist/select-types.js.map +1 -0
  110. package/dist/storage.d.ts +81 -11
  111. package/dist/storage.d.ts.map +1 -1
  112. package/dist/storage.js +137 -38
  113. package/dist/storage.js.map +1 -1
  114. package/dist/table-subscription.d.ts +69 -0
  115. package/dist/table-subscription.d.ts.map +1 -0
  116. package/dist/table-subscription.js +93 -0
  117. package/dist/table-subscription.js.map +1 -0
  118. package/dist/types.d.ts +98 -5
  119. package/dist/types.d.ts.map +1 -1
  120. package/dist/types.js +6 -1
  121. package/dist/types.js.map +1 -1
  122. package/package.json +6 -2
  123. package/src/auth-redirect.ts +90 -0
  124. package/src/auth.ts +434 -281
  125. package/src/bindings.ts +22 -0
  126. package/src/caller-types.ts +27 -0
  127. package/src/draft-create.ts +51 -0
  128. package/src/draft-models-registry.ts +81 -0
  129. package/src/error-codes-doc.ts +44 -35
  130. package/src/errors.ts +72 -28
  131. package/src/exact-response.ts +2 -1
  132. package/src/exact-values.ts +16 -9
  133. package/src/fetch-with-retry.ts +80 -70
  134. package/src/field-kinds-registry.ts +22 -9
  135. package/src/filters.ts +133 -0
  136. package/src/generated-client.ts +6 -0
  137. package/src/graphql-document.ts +234 -0
  138. package/src/graphql-json.ts +243 -0
  139. package/src/graphql-transport.ts +97 -0
  140. package/src/index.ts +289 -208
  141. package/src/json.ts +117 -0
  142. package/src/jwt.ts +37 -0
  143. package/src/live-preview.ts +37 -0
  144. package/src/mutation-request.ts +66 -0
  145. package/src/preview.ts +9 -11
  146. package/src/query-cache.ts +19 -16
  147. package/src/query.ts +389 -270
  148. package/src/realtime.ts +333 -90
  149. package/src/select-types.ts +184 -0
  150. package/src/storage.ts +223 -44
  151. package/src/table-subscription.ts +160 -0
  152. package/src/types.ts +104 -5
  153. package/tests/auth-error-codes.test.ts +53 -0
  154. package/tests/auth-errors.test.ts +84 -0
  155. package/tests/auth-events.test.ts +136 -0
  156. package/tests/auth-url-session.test.ts +204 -0
  157. package/tests/auth.test.ts +187 -26
  158. package/tests/count.test.ts +60 -0
  159. package/tests/data-plane-auth.test.ts +21 -46
  160. package/tests/draft-insert.integration.test.ts +118 -0
  161. package/tests/draft-insert.test.ts +225 -0
  162. package/tests/draft-profile.test.ts +55 -84
  163. package/tests/draft-update.integration.test.ts +122 -0
  164. package/tests/draft-update.test.ts +174 -0
  165. package/tests/dynamic-headers.test.ts +45 -0
  166. package/tests/entry-points.test.ts +42 -0
  167. package/tests/exact-response.test.ts +4 -4
  168. package/tests/exact-values.test.ts +14 -25
  169. package/tests/field-kinds-registry.test.ts +3 -3
  170. package/tests/filters.test.ts +146 -0
  171. package/tests/graphql-json.test.ts +199 -0
  172. package/tests/helpers/mock-websocket.ts +44 -11
  173. package/tests/helpers/oauth-binding.ts +92 -0
  174. package/tests/helpers/signup-binding.ts +73 -0
  175. package/tests/helpers/socket-swap.ts +142 -0
  176. package/tests/mfa-totp-integration.test.ts +13 -20
  177. package/tests/postgrest-error-codes.test.ts +85 -0
  178. package/tests/query-cache.test.ts +116 -117
  179. package/tests/query.test.ts +29 -31
  180. package/tests/rate-limit-integration.test.ts +4 -12
  181. package/tests/realtime-ack-ref.test.ts +112 -0
  182. package/tests/realtime-exact-values.test.ts +2 -4
  183. package/tests/realtime-presence.test.ts +75 -0
  184. package/tests/realtime-session-auth.test.ts +2 -4
  185. package/tests/realtime-shared-channel.test.ts +209 -0
  186. package/tests/realtime-swap-status.test.ts +62 -0
  187. package/tests/retry-integration.test.ts +3 -8
  188. package/tests/retry-policy.test.ts +166 -0
  189. package/tests/rpc-resend.test.ts +24 -0
  190. package/tests/server-bodies.test.ts +187 -0
  191. package/tests/serverless.test.ts +2 -2
  192. package/tests/signed-url-absolute.test.ts +2 -5
  193. package/tests/storage-object-shape.test.ts +101 -0
  194. package/tests/storage-quota-integration.test.ts +7 -9
  195. package/tests/storage-reference-url.test.ts +51 -0
  196. package/tests/storage-upload-browser.test.ts +71 -0
  197. package/tests/storage-upload-limit-integration.test.ts +17 -31
  198. package/tests/storage-url-encoding.test.ts +52 -0
  199. package/tests/subscribe-frame.test.ts +5 -11
  200. package/tests/support/blob.ts +10 -0
  201. package/tests/support/fetch-mock.ts +64 -0
  202. package/tests/support/storage-object.ts +37 -0
  203. package/tests/table-subscribe.test.ts +41 -14
  204. package/tests/table-subscription.test.ts +105 -0
  205. package/tests/table-transport.test.ts +94 -0
  206. package/tests/tsconfig.json +1 -1
  207. package/tests/types.test.ts +153 -1
  208. package/tsconfig.json +1 -1
  209. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,184 @@
1
+ /**
2
+ * The row a select string returns, read from the string itself.
3
+ *
4
+ * `select("*, author:authors(*)")` used to be typed as the table's row whatever the string said, so
5
+ * a caller embedding a relation had to declare the joined shape by hand and keep it in step with the
6
+ * string. That is a second copy of the query, and the type said nothing when the two drifted. This
7
+ * reads PostgREST's select grammar at the type level and resolves each embedded resource through the
8
+ * `Relationships` the generator writes for every table.
9
+ *
10
+ * What is understood: `*`, columns, `alias:column`, `column::cast`, JSON paths (`data->a->>b`),
11
+ * embedded resources (`rel(...)`, `alias:rel(...)`, nested) with `!inner` and a foreign-key column
12
+ * hint (`rel!author_id(...)`), in both directions of a foreign key and through a junction table.
13
+ *
14
+ * A to-one embed is `Row | null` unless it is `!inner`. A foreign key that is NOT NULL does not make
15
+ * the embed non-null: row level security can hide the referenced row while the referencing one stays
16
+ * readable, and PostgREST then returns `null` for it. `!inner` drops such rows instead, so there the
17
+ * embed is the row.
18
+ *
19
+ * A name the schema does not have becomes a {@link SelectError} rather than `unknown`, so the mistake
20
+ * surfaces where the value is used, with the reason in the type.
21
+ */
22
+ import type { TableDef } from "./types.js"
23
+
24
+ /** One foreign key, as the generator describes it on the table that holds it. */
25
+ export interface TableRelationship {
26
+ columns: readonly string[]
27
+ isOneToOne: boolean
28
+ referencedRelation: string
29
+ referencedColumns: readonly string[]
30
+ }
31
+
32
+ /** What a select string named that the schema does not have, with the reason. */
33
+ export interface SelectError<TMessage extends string> {
34
+ readonly selectError: TMessage
35
+ }
36
+
37
+ type Tables = Record<string, TableDef>
38
+
39
+ /** The row `select(columns)` resolves to on table `TName`. */
40
+ export type SelectRow<TTables extends Tables, TName extends string, TColumns extends string> =
41
+ string extends TColumns
42
+ ? RowOf<TTables, TName>
43
+ : ParseFields<TTables, TName, SplitTopLevel<TColumns>>
44
+
45
+ // ─── Grammar ──────────────────────────────────────────────────────────────────
46
+
47
+ type Space = " " | "\n" | "\t" | "\r"
48
+ type TrimStart<S extends string> = S extends `${infer C}${infer R}` ? (C extends Space ? TrimStart<R> : S) : S
49
+ type TrimEnd<S extends string> = S extends `${infer R}${Space}` ? TrimEnd<R> : S
50
+ type Trim<S extends string> = TrimEnd<TrimStart<S>>
51
+
52
+ type Push<TAcc extends string[], TItem extends string> = Trim<TItem> extends "" ? TAcc : [...TAcc, Trim<TItem>]
53
+
54
+ /** Split on the commas outside any parentheses: `a, b(c, d)` is two fields, not three. */
55
+ type SplitTopLevel<
56
+ S extends string,
57
+ TDepth extends 0[] = [],
58
+ TCurrent extends string = "",
59
+ TAcc extends string[] = [],
60
+ > = S extends `${infer C}${infer Rest}`
61
+ ? C extends "("
62
+ ? SplitTopLevel<Rest, [...TDepth, 0], `${TCurrent}${C}`, TAcc>
63
+ : C extends ")"
64
+ ? SplitTopLevel<Rest, TDepth extends [0, ...infer Outer extends 0[]] ? Outer : [], `${TCurrent}${C}`, TAcc>
65
+ : C extends ","
66
+ ? TDepth extends []
67
+ ? SplitTopLevel<Rest, TDepth, "", Push<TAcc, TCurrent>>
68
+ : SplitTopLevel<Rest, TDepth, `${TCurrent}${C}`, TAcc>
69
+ : SplitTopLevel<Rest, TDepth, `${TCurrent}${C}`, TAcc>
70
+ : Push<TAcc, TCurrent>
71
+
72
+ type Simplify<T> = { [K in keyof T]: T[K] } & {}
73
+
74
+ type ParseFields<TTables extends Tables, TName extends string, TFields extends string[]> =
75
+ TFields extends ["*"]
76
+ ? RowOf<TTables, TName>
77
+ : Simplify<MergeFields<TTables, TName, TFields>>
78
+
79
+ type MergeFields<TTables extends Tables, TName extends string, TFields extends string[], TAcc = unknown> =
80
+ TFields extends [infer F extends string, ...infer Rest extends string[]]
81
+ ? MergeFields<TTables, TName, Rest, TAcc & ParseField<TTables, TName, F>>
82
+ : TAcc
83
+
84
+ /** `alias:body`, where the alias is what comes before the first `:` unless that is a cast's `::`. */
85
+ type ParseField<TTables extends Tables, TName extends string, F extends string> =
86
+ F extends "*"
87
+ ? RowOf<TTables, TName>
88
+ : F extends `${infer Alias}:${infer Body}`
89
+ ? Body extends `:${string}`
90
+ ? Unaliased<TTables, TName, F>
91
+ : Alias extends `${string}(${string}`
92
+ ? Unaliased<TTables, TName, F>
93
+ : { [K in Trim<Alias>]: FieldType<TTables, TName, Trim<Body>> }
94
+ : Unaliased<TTables, TName, F>
95
+
96
+ type Unaliased<TTables extends Tables, TName extends string, F extends string> = {
97
+ [K in NaturalName<F>]: FieldType<TTables, TName, F>
98
+ }
99
+
100
+ /** The key PostgREST gives an unaliased field: the resource, the column, or a JSON path's last key. */
101
+ type NaturalName<F extends string> =
102
+ F extends `${infer Resource}(${string}` ? ResourceName<Trim<Resource>>
103
+ : F extends `${infer Column}::${string}` ? NaturalName<Column>
104
+ : F extends `${string}->>${infer Rest}` ? NaturalName<Rest>
105
+ : F extends `${string}->${infer Rest}` ? NaturalName<Rest>
106
+ : F
107
+
108
+ type FieldType<TTables extends Tables, TName extends string, Body extends string> =
109
+ Body extends `${infer Resource}(${infer Inner})`
110
+ ? Embed<TTables, TName, Trim<Resource>, Inner>
111
+ : ColumnType<RowOf<TTables, TName>, TName, Body>
112
+
113
+ /** The column a field reads, without its cast (`::text`) or JSON path (`->a->>b`). */
114
+ type BaseColumn<B extends string> =
115
+ B extends `${infer C}::${string}` ? BaseColumn<C> : B extends `${infer C}->${string}` ? C : B
116
+
117
+ /** A plain column is its row type; a cast or a JSON path reads a value the schema cannot type. */
118
+ type ColumnType<TRow, TName extends string, Body extends string> =
119
+ BaseColumn<Body> extends infer C extends string
120
+ ? C extends keyof TRow
121
+ ? Body extends C ? TRow[C] : unknown
122
+ : SelectError<`column '${C}' does not exist on '${TName}'`>
123
+ : never
124
+
125
+ // ─── Embedded resources ───────────────────────────────────────────────────────
126
+
127
+ type ResourceName<R extends string> = R extends `${infer Name}!${string}` ? Name : R
128
+
129
+ /** `rel!inner!author_id`: the `!` modifiers after a resource name, in any order. */
130
+ type Modifiers<R extends string> = R extends `${string}!${infer Rest}` ? SplitBang<Rest> : never
131
+ type SplitBang<S extends string> = S extends `${infer Head}!${infer Rest}` ? Head | SplitBang<Rest> : S
132
+ type ColumnHint<R extends string> = Exclude<Modifiers<R>, "inner" | "left">
133
+
134
+ type Embed<TTables extends Tables, TName extends string, TResource extends string, Inner extends string> =
135
+ string extends keyof TTables
136
+ ? unknown
137
+ : ResourceName<TResource> extends infer Target extends string
138
+ ? Target extends keyof TTables
139
+ ? Shape<
140
+ Cardinality<TTables, TName, Target, ColumnHint<TResource>>,
141
+ SelectRow<TTables, Target, Inner>,
142
+ "inner" extends Modifiers<TResource> ? true : false,
143
+ `'${TName}' has no relationship to '${Target}'`
144
+ >
145
+ : SelectError<`'${Target}' is not a table`>
146
+ : never
147
+
148
+ type Shape<TKind, TRow, TInner extends boolean, TMessage extends string> =
149
+ TKind extends "one" ? (TInner extends true ? TRow : TRow | null)
150
+ : TKind extends "many" ? TRow[]
151
+ : SelectError<TMessage>
152
+
153
+ type RowOf<TTables extends Tables, TName extends string> = TTables[TName] extends { Row: infer R } ? R : never
154
+
155
+ type RelationshipsOf<TDef> =
156
+ TDef extends { Relationships: infer R extends readonly unknown[] } ? R[number] : never
157
+
158
+ /** The relationships of `From` naming `To`, narrowed to the hinted column when there is one. */
159
+ type Referencing<TTables extends Tables, From extends string, To extends string, Hint> = Extract<
160
+ RelationshipsOf<TTables[From]>,
161
+ [Hint] extends [never]
162
+ ? { referencedRelation: To }
163
+ : { referencedRelation: To; columns: readonly [Hint & string, ...string[]] }
164
+ >
165
+
166
+ /** A table holding foreign keys to both sides: the junction of a many-to-many. */
167
+ type Junction<TTables extends Tables, From extends string, To extends string> = {
168
+ [J in keyof TTables & string]: [Referencing<TTables, J, From, never>] extends [never]
169
+ ? never
170
+ : [Referencing<TTables, J, To, never>] extends [never]
171
+ ? never
172
+ : J
173
+ }[keyof TTables & string]
174
+
175
+ /**
176
+ * How many rows an embed returns. The key on this side is to-one; the key on the other side is
177
+ * to-many unless it is unique; a junction holding keys to both is to-many.
178
+ */
179
+ type Cardinality<TTables extends Tables, From extends string, To extends string, Hint> =
180
+ [Referencing<TTables, From, To, Hint>] extends [never]
181
+ ? [Referencing<TTables, To, From, Hint>] extends [never]
182
+ ? [Junction<TTables, From, To>] extends [never] ? "none" : "many"
183
+ : Referencing<TTables, To, From, Hint> extends { isOneToOne: true } ? "one" : "many"
184
+ : "one"
package/src/storage.ts CHANGED
@@ -1,14 +1,80 @@
1
1
  import type { SupatypeError } from "./types.js"
2
+ import { transportFailure } from "./errors.js"
3
+ import { plainFetch, type RequestTransport } from "./fetch-with-retry.js"
4
+ import {
5
+ isArrayOf,
6
+ isBoolean,
7
+ isJsonObject,
8
+ isNumber,
9
+ isShape,
10
+ isString,
11
+ nullable,
12
+ readJson,
13
+ readJsonObject,
14
+ type Guard,
15
+ } from "./json.js"
2
16
 
17
+ /**
18
+ * An object path as it goes into a URL: each segment encoded, the `/` between them kept, since the
19
+ * server matches the path on it. Interpolated as given, a name holding `?` or `#` cut the URL short.
20
+ */
21
+ function encodeObjectPath(path: string): string {
22
+ return path.split("/").map(encodeURIComponent).join("/")
23
+ }
24
+
25
+ /**
26
+ * An object as `list()` answers it, field for field (packages/storage/src/routes/objects.ts,
27
+ * `listedObject`), named relative to the folder listed. A null is sent as null, never left out.
28
+ */
3
29
  export interface StorageObject {
4
30
  id: string
5
- name: string
6
31
  bucket_id: string
7
- owner?: string | undefined
32
+ name: string
33
+ /** The uploader's user id; null for an object stored without one, such as by the service role. */
34
+ owner: string | null
35
+ metadata: Record<string, unknown> | null
8
36
  created_at: string
9
37
  updated_at: string
10
38
  last_accessed_at: string
11
- metadata?: Record<string, unknown> | undefined
39
+ /** The object's size in bytes, from its metadata; null when the metadata records none. */
40
+ size: number | null
41
+ /** The content type it was stored with, from its metadata; null when the metadata records none. */
42
+ mimetype: string | null
43
+ }
44
+
45
+ /**
46
+ * A subfolder as `list()` answers it: only its bucket and its name, relative to the folder listed.
47
+ * It has no row of its own, so every other field is null.
48
+ */
49
+ export interface StorageFolder {
50
+ id: null
51
+ bucket_id: string
52
+ name: string
53
+ owner: null
54
+ metadata: null
55
+ created_at: null
56
+ updated_at: null
57
+ last_accessed_at: null
58
+ size: null
59
+ mimetype: null
60
+ }
61
+
62
+ /** What `list()` answers: a folder's subfolders, then its objects. */
63
+ export type StorageListEntry = StorageObject | StorageFolder
64
+
65
+ /** What to list besides the folder: a page, and a search of the entries' names. */
66
+ export interface ListOptions {
67
+ /** Entries per page; the server's default is 100. */
68
+ limit?: number | undefined
69
+ offset?: number | undefined
70
+ /** Matched case-insensitively against each entry's name; every character is literal. */
71
+ search?: string | undefined
72
+ }
73
+
74
+ /** What `remove()` answers for each object it removed: one the caller may not delete is absent. */
75
+ export interface RemovedObject {
76
+ name: string
77
+ bucket_id: string
12
78
  }
13
79
 
14
80
  export interface TransformOptions {
@@ -19,6 +85,17 @@ export interface TransformOptions {
19
85
  resize?: "cover" | "contain" | "fill" | "inside" | "outside" | undefined
20
86
  }
21
87
 
88
+ /**
89
+ * What an `ImageAsset` or `FileAsset` column stores: the bucket and path `upload()` wrote to.
90
+ * Studio also records `mimeType` and `size` when it does the upload.
91
+ */
92
+ export interface StorageReference {
93
+ bucket: string
94
+ path: string
95
+ mimeType?: string | undefined
96
+ size?: number | undefined
97
+ }
98
+
22
99
  export interface StorageBucketMeta {
23
100
  id: string
24
101
  name: string
@@ -32,9 +109,91 @@ export interface StorageBucketMeta {
32
109
  /** Resolved fresh per request, so a session that arrives later is used. */
33
110
  export type AuthHeaders = () => Promise<Record<string, string>>
34
111
 
112
+ /**
113
+ * A bucket as the storage service lists it (`SELECT *` on storage.buckets).
114
+ *
115
+ * `file_size_limit` is a Postgres bigint, which node-postgres sends as a string, so the limit
116
+ * arrived as `"1048576"` where `StorageBucketMeta` promises a number. It is read as a number here.
117
+ */
118
+ const isBucketRows = isArrayOf(
119
+ isShape({
120
+ id: isString,
121
+ name: isString,
122
+ public: isBoolean,
123
+ file_size_limit: nullable((value: unknown): value is number | string => isNumber(value) || isString(value)),
124
+ allowed_mime_types: nullable(isArrayOf(isString)),
125
+ created_at: isString,
126
+ updated_at: isString,
127
+ }),
128
+ )
129
+
130
+ async function readBuckets(res: Response): Promise<StorageBucketMeta[]> {
131
+ const rows = await readJson(res, isBucketRows)
132
+ return rows.map((row) => ({
133
+ id: row.id,
134
+ name: row.name,
135
+ public: row.public,
136
+ file_size_limit: row.file_size_limit === null ? null : Number(row.file_size_limit),
137
+ allowed_mime_types: row.allowed_mime_types,
138
+ created_at: row.created_at,
139
+ updated_at: row.updated_at,
140
+ }))
141
+ }
142
+
143
+ const isNull = (value: unknown): value is null => value === null
144
+
145
+ /** A subfolder entry: null in every field but its bucket and name. */
146
+ const isStorageFolder: Guard<StorageFolder> = isShape({
147
+ id: isNull,
148
+ bucket_id: isString,
149
+ name: isString,
150
+ owner: isNull,
151
+ metadata: isNull,
152
+ created_at: isNull,
153
+ updated_at: isNull,
154
+ last_accessed_at: isNull,
155
+ size: isNull,
156
+ mimetype: isNull,
157
+ })
158
+
159
+ /** An object entry: every declared field, checked. */
160
+ const isStorageObject: Guard<StorageObject> = isShape({
161
+ id: isString,
162
+ bucket_id: isString,
163
+ name: isString,
164
+ owner: nullable(isString),
165
+ metadata: nullable(isJsonObject),
166
+ created_at: isString,
167
+ updated_at: isString,
168
+ last_accessed_at: isString,
169
+ size: nullable(isNumber),
170
+ mimetype: nullable(isString),
171
+ })
172
+
173
+ /** The boundary between a `list` answer and `StorageListEntry`: every declared field, checked. */
174
+ const isStorageEntries: Guard<StorageListEntry[]> = isArrayOf(
175
+ (value: unknown): value is StorageListEntry => isStorageFolder(value) || isStorageObject(value),
176
+ )
177
+
178
+ /** A total count header as a number, or null when it is absent or not a count. */
179
+ function countHeader(res: Response): number | null {
180
+ const count = res.headers.get("X-Total-Count")
181
+ return count !== null && /^\d+$/.test(count) ? Number(count) : null
182
+ }
183
+
184
+ /** The boundary between a `remove` answer and `RemovedObject`. */
185
+ const isRemovedObjects: Guard<RemovedObject[]> = isArrayOf(isShape({ name: isString, bucket_id: isString }))
186
+
187
+ /** A refusal's reason: the body's `message`, else its `error`, else `fallback`. */
188
+ async function storageRefusal(res: Response, fallback: string): Promise<string> {
189
+ const body = await readJsonObject(res)
190
+ return String(body["message"] ?? body["error"] ?? fallback)
191
+ }
192
+
35
193
  export class StorageClient {
36
194
  private readonly url: string
37
195
  private readonly headers: AuthHeaders
196
+ private readonly send: RequestTransport
38
197
 
39
198
  /**
40
199
  * Headers are asked for per request, not captured here.
@@ -47,26 +206,44 @@ export class StorageClient {
47
206
  * Every other client on this object already took the same function. Storage was the one that did
48
207
  * not.
49
208
  */
50
- constructor(url: string, headers: AuthHeaders) {
209
+ constructor(url: string, headers: AuthHeaders, transport: RequestTransport = plainFetch) {
210
+ this.send = transport
51
211
  this.url = url
52
212
  this.headers = headers
53
213
  }
54
214
 
55
215
  from(bucket: string): BucketClient {
56
- return new BucketClient(this.url, bucket, this.headers)
216
+ return new BucketClient(this.url, bucket, this.headers, this.send)
217
+ }
218
+
219
+ /**
220
+ * The public URL of what an `ImageAsset` or `FileAsset` column holds.
221
+ *
222
+ * The column stores a {@link StorageReference}, never a URL: a stored URL goes stale and bakes in
223
+ * the host, and the bucket and path rebuild it anywhere. This is that rebuild, so a component can
224
+ * write `src={supatype.storage.publicUrl(speaker.headshot)}` instead of reading a `url` field that
225
+ * is not there. Pass `transform` for a derivative resized or re-encoded on read.
226
+ *
227
+ * Null for an empty column or a reference without a bucket or path. Only meaningful for a public
228
+ * bucket; a private one needs `from(bucket).createSignedUrl(path)`.
229
+ */
230
+ publicUrl(
231
+ reference: StorageReference | null | undefined,
232
+ options?: { transform?: TransformOptions | undefined } | undefined,
233
+ ): string | null {
234
+ if (reference === null || reference === undefined) return null
235
+ const { bucket, path } = reference
236
+ if (typeof bucket !== "string" || bucket === "" || typeof path !== "string" || path === "") return null
237
+ return this.from(bucket).getPublicUrl(path, options).data.publicUrl
57
238
  }
58
239
 
59
240
  async listBuckets(): Promise<{ data: StorageBucketMeta[] | null; error: SupatypeError | null }> {
60
241
  try {
61
- const res = await fetch(`${this.url}/bucket`, { headers: await this.headers() })
62
- if (!res.ok) {
63
- const err = await res.json().catch(() => ({ message: "Error" })) as { message?: string }
64
- return { data: null, error: { message: err.message ?? "Failed to list buckets" } }
65
- }
66
- const data = await res.json() as StorageBucketMeta[]
67
- return { data, error: null }
242
+ const res = await this.send(`${this.url}/bucket`, { headers: await this.headers() })
243
+ if (!res.ok) return { data: null, error: { message: await storageRefusal(res, "Failed to list buckets") } }
244
+ return { data: await readBuckets(res), error: null }
68
245
  } catch (e) {
69
- return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
246
+ return { data: null, error: transportFailure(e) }
70
247
  }
71
248
  }
72
249
 
@@ -82,18 +259,15 @@ export class StorageClient {
82
259
  ...(options?.fileSizeLimit !== undefined && { file_size_limit: options.fileSizeLimit }),
83
260
  ...(options?.allowedMimeTypes !== undefined && { allowed_mime_types: options.allowedMimeTypes }),
84
261
  }
85
- const res = await fetch(`${this.url}/bucket`, {
262
+ const res = await this.send(`${this.url}/bucket`, {
86
263
  method: "POST",
87
264
  headers: { ...(await this.headers()), "Content-Type": "application/json" },
88
265
  body: JSON.stringify(body),
89
266
  })
90
- if (!res.ok) {
91
- const err = await res.json().catch(() => ({ message: "Error" })) as { message?: string }
92
- return { data: null, error: { message: err.message ?? "Failed to create bucket" } }
93
- }
267
+ if (!res.ok) return { data: null, error: { message: await storageRefusal(res, "Failed to create bucket") } }
94
268
  return { data: { name }, error: null }
95
269
  } catch (e) {
96
- return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
270
+ return { data: null, error: transportFailure(e) }
97
271
  }
98
272
  }
99
273
  }
@@ -102,8 +276,10 @@ export class BucketClient {
102
276
  private readonly url: string
103
277
  private readonly bucket: string
104
278
  private readonly headers: AuthHeaders
279
+ private readonly send: RequestTransport
105
280
 
106
- constructor(url: string, bucket: string, headers: AuthHeaders) {
281
+ constructor(url: string, bucket: string, headers: AuthHeaders, transport: RequestTransport = plainFetch) {
282
+ this.send = transport
107
283
  this.url = url
108
284
  this.bucket = bucket
109
285
  this.headers = headers
@@ -122,14 +298,13 @@ export class BucketClient {
122
298
  if (options?.upsert === true) {
123
299
  headers["x-upsert"] = "true"
124
300
  }
125
- const res = await fetch(`${this.url}/object/${this.bucket}/${path}`, {
301
+ const res = await this.send(`${this.url}/object/${this.bucket}/${encodeObjectPath(path)}`, {
126
302
  method: "POST",
127
303
  headers,
128
304
  body: file,
129
305
  })
130
306
  if (!res.ok) {
131
- const err = await res.json().catch(() => ({ message: "Upload failed" })) as Record<string, unknown>
132
- return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Upload failed"), status: res.status } }
307
+ return { data: null, error: { message: await storageRefusal(res, "Upload failed"), status: res.status } }
133
308
  }
134
309
  return { data: { path }, error: null }
135
310
  }
@@ -139,10 +314,9 @@ export class BucketClient {
139
314
  options?: { transform?: TransformOptions | undefined } | undefined,
140
315
  ): Promise<{ data: Blob | null; error: SupatypeError | null }> {
141
316
  const url = this.buildObjectUrl("authenticated", path, options?.transform)
142
- const res = await fetch(url, { headers: await this.headers() })
317
+ const res = await this.send(url, { headers: await this.headers() })
143
318
  if (!res.ok) {
144
- const err = await res.json().catch(() => ({ message: "Download failed" })) as Record<string, unknown>
145
- return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Download failed"), status: res.status } }
319
+ return { data: null, error: { message: await storageRefusal(res, "Download failed"), status: res.status } }
146
320
  }
147
321
  const blob = await res.blob()
148
322
  return { data: blob, error: null }
@@ -176,16 +350,17 @@ export class BucketClient {
176
350
  path: string,
177
351
  expiresIn: number,
178
352
  ): Promise<{ data: { signedUrl: string } | null; error: SupatypeError | null }> {
179
- const res = await fetch(`${this.url}/object/sign/${this.bucket}/${path}`, {
353
+ const res = await this.send(`${this.url}/object/sign/${this.bucket}/${encodeObjectPath(path)}`, {
180
354
  method: "POST",
355
+ // Signing creates nothing on the server, so a second request is harmless.
356
+ idempotent: true,
181
357
  headers: { ...(await this.headers()), "Content-Type": "application/json" },
182
358
  body: JSON.stringify({ expiresIn }),
183
359
  })
184
360
  if (!res.ok) {
185
- const err = await res.json().catch(() => ({ message: "Failed to create signed URL" })) as Record<string, unknown>
186
- return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Failed to create signed URL"), status: res.status } }
361
+ return { data: null, error: { message: await storageRefusal(res, "Failed to create signed URL"), status: res.status } }
187
362
  }
188
- const json = await res.json() as { signedURL: string }
363
+ const json = await readJson(res, isShape({ signedURL: isString }))
189
364
  return { data: { signedUrl: this.absoluteObjectUrl(json.signedURL) }, error: null }
190
365
  }
191
366
 
@@ -205,40 +380,44 @@ export class BucketClient {
205
380
  return { data: results, error: null }
206
381
  }
207
382
 
208
- async remove(paths: string[]): Promise<{ data: StorageObject[] | null; error: SupatypeError | null }> {
209
- const res = await fetch(`${this.url}/object/${this.bucket}`, {
383
+ async remove(paths: string[]): Promise<{ data: RemovedObject[] | null; error: SupatypeError | null }> {
384
+ const res = await this.send(`${this.url}/object/${this.bucket}`, {
210
385
  method: "DELETE",
211
386
  headers: { ...(await this.headers()), "Content-Type": "application/json" },
212
387
  body: JSON.stringify({ prefixes: paths }),
213
388
  })
214
389
  if (!res.ok) {
215
- const err = await res.json().catch(() => ({ message: "Delete failed" })) as Record<string, unknown>
216
- return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Delete failed"), status: res.status } }
390
+ return { data: null, error: { message: await storageRefusal(res, "Delete failed"), status: res.status } }
217
391
  }
218
- const json = await res.json() as StorageObject[]
219
- return { data: json, error: null }
392
+ return { data: await readJson(res, isRemovedObjects), error: null }
220
393
  }
221
394
 
395
+ /**
396
+ * The folder `prefix` names ("" or none for the bucket root): its subfolders, then its objects, each
397
+ * named relative to it. `count` is how many entries match in all, before `limit` and `offset`,
398
+ * or null from a server that does not send it.
399
+ */
222
400
  async list(
223
401
  prefix?: string | undefined,
224
- options?: { limit?: number | undefined; offset?: number | undefined } | undefined,
225
- ): Promise<{ data: StorageObject[] | null; error: SupatypeError | null }> {
402
+ options?: ListOptions | undefined,
403
+ ): Promise<{ data: StorageListEntry[] | null; count: number | null; error: SupatypeError | null }> {
226
404
  const body: Record<string, unknown> = {
227
405
  ...(prefix !== undefined && { prefix }),
406
+ ...(options?.search !== undefined && { search: options.search }),
228
407
  ...(options?.limit !== undefined && { limit: options.limit }),
229
408
  ...(options?.offset !== undefined && { offset: options.offset }),
230
409
  }
231
- const res = await fetch(`${this.url}/object/list/${this.bucket}`, {
410
+ const res = await this.send(`${this.url}/object/list/${this.bucket}`, {
232
411
  method: "POST",
412
+ // A read that happens to be sent as POST.
413
+ idempotent: true,
233
414
  headers: { ...(await this.headers()), "Content-Type": "application/json" },
234
415
  body: JSON.stringify(body),
235
416
  })
236
417
  if (!res.ok) {
237
- const err = await res.json().catch(() => ({ message: "List failed" })) as Record<string, unknown>
238
- return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "List failed"), status: res.status } }
418
+ return { data: null, count: null, error: { message: await storageRefusal(res, "List failed"), status: res.status } }
239
419
  }
240
- const json = await res.json() as StorageObject[]
241
- return { data: json, error: null }
420
+ return { data: await readJson(res, isStorageEntries), count: countHeader(res), error: null }
242
421
  }
243
422
 
244
423
  // ─── Internal ───────────────────────────────────────────────────────────────
@@ -248,7 +427,7 @@ export class BucketClient {
248
427
  path: string,
249
428
  transform?: TransformOptions | undefined,
250
429
  ): string {
251
- let url = `${this.url}/object/${access}/${this.bucket}/${path}`
430
+ let url = `${this.url}/object/${access}/${this.bucket}/${encodeObjectPath(path)}`
252
431
  if (transform) {
253
432
  const params = new URLSearchParams()
254
433
  if (transform.width !== undefined) params.set("width", String(transform.width))