@supatype/client 0.3.5 → 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.
Files changed (205) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +58 -31
  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 +78 -4
  10. package/dist/auth.d.ts.map +1 -1
  11. package/dist/auth.js +373 -274
  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 +153 -157
  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 +20 -2
  103. package/dist/realtime.d.ts.map +1 -1
  104. package/dist/realtime.js +105 -12
  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 +129 -37
  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 +84 -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 +421 -280
  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 +272 -201
  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 +116 -13
  149. package/src/select-types.ts +184 -0
  150. package/src/storage.ts +214 -43
  151. package/src/table-subscription.ts +160 -0
  152. package/src/types.ts +90 -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 +122 -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 +139 -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-exact-values.test.ts +2 -4
  182. package/tests/realtime-presence.test.ts +75 -0
  183. package/tests/realtime-session-auth.test.ts +2 -4
  184. package/tests/realtime-swap-status.test.ts +62 -0
  185. package/tests/retry-integration.test.ts +3 -8
  186. package/tests/retry-policy.test.ts +166 -0
  187. package/tests/rpc-resend.test.ts +24 -0
  188. package/tests/server-bodies.test.ts +139 -0
  189. package/tests/serverless.test.ts +2 -2
  190. package/tests/signed-url-absolute.test.ts +2 -5
  191. package/tests/storage-object-shape.test.ts +101 -0
  192. package/tests/storage-quota-integration.test.ts +3 -2
  193. package/tests/storage-reference-url.test.ts +51 -0
  194. package/tests/storage-upload-browser.test.ts +71 -0
  195. package/tests/storage-upload-limit-integration.test.ts +12 -22
  196. package/tests/subscribe-frame.test.ts +5 -11
  197. package/tests/support/fetch-mock.ts +64 -0
  198. package/tests/support/storage-object.ts +37 -0
  199. package/tests/table-subscribe.test.ts +13 -13
  200. package/tests/table-subscription.test.ts +105 -0
  201. package/tests/table-transport.test.ts +94 -0
  202. package/tests/tsconfig.json +1 -1
  203. package/tests/types.test.ts +153 -1
  204. package/tsconfig.json +1 -1
  205. package/tsconfig.tsbuildinfo +1 -1
package/src/storage.ts CHANGED
@@ -1,14 +1,72 @@
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 as `list()` answers it, field for field (packages/storage/src/routes/objects.ts,
19
+ * `listedObject`), named relative to the folder listed. A null is sent as null, never left out.
20
+ */
3
21
  export interface StorageObject {
4
22
  id: string
5
- name: string
6
23
  bucket_id: string
7
- owner?: string | undefined
24
+ name: string
25
+ /** The uploader's user id; null for an object stored without one, such as by the service role. */
26
+ owner: string | null
27
+ metadata: Record<string, unknown> | null
8
28
  created_at: string
9
29
  updated_at: string
10
30
  last_accessed_at: string
11
- metadata?: Record<string, unknown> | undefined
31
+ /** The object's size in bytes, from its metadata; null when the metadata records none. */
32
+ size: number | null
33
+ /** The content type it was stored with, from its metadata; null when the metadata records none. */
34
+ mimetype: string | null
35
+ }
36
+
37
+ /**
38
+ * A subfolder as `list()` answers it: only its bucket and its name, relative to the folder listed.
39
+ * It has no row of its own, so every other field is null.
40
+ */
41
+ export interface StorageFolder {
42
+ id: null
43
+ bucket_id: string
44
+ name: string
45
+ owner: null
46
+ metadata: null
47
+ created_at: null
48
+ updated_at: null
49
+ last_accessed_at: null
50
+ size: null
51
+ mimetype: null
52
+ }
53
+
54
+ /** What `list()` answers: a folder's subfolders, then its objects. */
55
+ export type StorageListEntry = StorageObject | StorageFolder
56
+
57
+ /** What to list besides the folder: a page, and a search of the entries' names. */
58
+ export interface ListOptions {
59
+ /** Entries per page; the server's default is 100. */
60
+ limit?: number | undefined
61
+ offset?: number | undefined
62
+ /** Matched case-insensitively against each entry's name; every character is literal. */
63
+ search?: string | undefined
64
+ }
65
+
66
+ /** What `remove()` answers for each object it removed: one the caller may not delete is absent. */
67
+ export interface RemovedObject {
68
+ name: string
69
+ bucket_id: string
12
70
  }
13
71
 
14
72
  export interface TransformOptions {
@@ -19,6 +77,17 @@ export interface TransformOptions {
19
77
  resize?: "cover" | "contain" | "fill" | "inside" | "outside" | undefined
20
78
  }
21
79
 
80
+ /**
81
+ * What an `ImageAsset` or `FileAsset` column stores: the bucket and path `upload()` wrote to.
82
+ * Studio also records `mimeType` and `size` when it does the upload.
83
+ */
84
+ export interface StorageReference {
85
+ bucket: string
86
+ path: string
87
+ mimeType?: string | undefined
88
+ size?: number | undefined
89
+ }
90
+
22
91
  export interface StorageBucketMeta {
23
92
  id: string
24
93
  name: string
@@ -32,9 +101,91 @@ export interface StorageBucketMeta {
32
101
  /** Resolved fresh per request, so a session that arrives later is used. */
33
102
  export type AuthHeaders = () => Promise<Record<string, string>>
34
103
 
104
+ /**
105
+ * A bucket as the storage service lists it (`SELECT *` on storage.buckets).
106
+ *
107
+ * `file_size_limit` is a Postgres bigint, which node-postgres sends as a string, so the limit
108
+ * arrived as `"1048576"` where `StorageBucketMeta` promises a number. It is read as a number here.
109
+ */
110
+ const isBucketRows = isArrayOf(
111
+ isShape({
112
+ id: isString,
113
+ name: isString,
114
+ public: isBoolean,
115
+ file_size_limit: nullable((value: unknown): value is number | string => isNumber(value) || isString(value)),
116
+ allowed_mime_types: nullable(isArrayOf(isString)),
117
+ created_at: isString,
118
+ updated_at: isString,
119
+ }),
120
+ )
121
+
122
+ async function readBuckets(res: Response): Promise<StorageBucketMeta[]> {
123
+ const rows = await readJson(res, isBucketRows)
124
+ return rows.map((row) => ({
125
+ id: row.id,
126
+ name: row.name,
127
+ public: row.public,
128
+ file_size_limit: row.file_size_limit === null ? null : Number(row.file_size_limit),
129
+ allowed_mime_types: row.allowed_mime_types,
130
+ created_at: row.created_at,
131
+ updated_at: row.updated_at,
132
+ }))
133
+ }
134
+
135
+ const isNull = (value: unknown): value is null => value === null
136
+
137
+ /** A subfolder entry: null in every field but its bucket and name. */
138
+ const isStorageFolder: Guard<StorageFolder> = isShape({
139
+ id: isNull,
140
+ bucket_id: isString,
141
+ name: isString,
142
+ owner: isNull,
143
+ metadata: isNull,
144
+ created_at: isNull,
145
+ updated_at: isNull,
146
+ last_accessed_at: isNull,
147
+ size: isNull,
148
+ mimetype: isNull,
149
+ })
150
+
151
+ /** An object entry: every declared field, checked. */
152
+ const isStorageObject: Guard<StorageObject> = isShape({
153
+ id: isString,
154
+ bucket_id: isString,
155
+ name: isString,
156
+ owner: nullable(isString),
157
+ metadata: nullable(isJsonObject),
158
+ created_at: isString,
159
+ updated_at: isString,
160
+ last_accessed_at: isString,
161
+ size: nullable(isNumber),
162
+ mimetype: nullable(isString),
163
+ })
164
+
165
+ /** The boundary between a `list` answer and `StorageListEntry`: every declared field, checked. */
166
+ const isStorageEntries: Guard<StorageListEntry[]> = isArrayOf(
167
+ (value: unknown): value is StorageListEntry => isStorageFolder(value) || isStorageObject(value),
168
+ )
169
+
170
+ /** A total count header as a number, or null when it is absent or not a count. */
171
+ function countHeader(res: Response): number | null {
172
+ const count = res.headers.get("X-Total-Count")
173
+ return count !== null && /^\d+$/.test(count) ? Number(count) : null
174
+ }
175
+
176
+ /** The boundary between a `remove` answer and `RemovedObject`. */
177
+ const isRemovedObjects: Guard<RemovedObject[]> = isArrayOf(isShape({ name: isString, bucket_id: isString }))
178
+
179
+ /** A refusal's reason: the body's `message`, else its `error`, else `fallback`. */
180
+ async function storageRefusal(res: Response, fallback: string): Promise<string> {
181
+ const body = await readJsonObject(res)
182
+ return String(body["message"] ?? body["error"] ?? fallback)
183
+ }
184
+
35
185
  export class StorageClient {
36
186
  private readonly url: string
37
187
  private readonly headers: AuthHeaders
188
+ private readonly send: RequestTransport
38
189
 
39
190
  /**
40
191
  * Headers are asked for per request, not captured here.
@@ -47,26 +198,44 @@ export class StorageClient {
47
198
  * Every other client on this object already took the same function. Storage was the one that did
48
199
  * not.
49
200
  */
50
- constructor(url: string, headers: AuthHeaders) {
201
+ constructor(url: string, headers: AuthHeaders, transport: RequestTransport = plainFetch) {
202
+ this.send = transport
51
203
  this.url = url
52
204
  this.headers = headers
53
205
  }
54
206
 
55
207
  from(bucket: string): BucketClient {
56
- return new BucketClient(this.url, bucket, this.headers)
208
+ return new BucketClient(this.url, bucket, this.headers, this.send)
209
+ }
210
+
211
+ /**
212
+ * The public URL of what an `ImageAsset` or `FileAsset` column holds.
213
+ *
214
+ * The column stores a {@link StorageReference}, never a URL: a stored URL goes stale and bakes in
215
+ * the host, and the bucket and path rebuild it anywhere. This is that rebuild, so a component can
216
+ * write `src={supatype.storage.publicUrl(speaker.headshot)}` instead of reading a `url` field that
217
+ * is not there. Pass `transform` for a derivative resized or re-encoded on read.
218
+ *
219
+ * Null for an empty column or a reference without a bucket or path. Only meaningful for a public
220
+ * bucket; a private one needs `from(bucket).createSignedUrl(path)`.
221
+ */
222
+ publicUrl(
223
+ reference: StorageReference | null | undefined,
224
+ options?: { transform?: TransformOptions | undefined } | undefined,
225
+ ): string | null {
226
+ if (reference === null || reference === undefined) return null
227
+ const { bucket, path } = reference
228
+ if (typeof bucket !== "string" || bucket === "" || typeof path !== "string" || path === "") return null
229
+ return this.from(bucket).getPublicUrl(path, options).data.publicUrl
57
230
  }
58
231
 
59
232
  async listBuckets(): Promise<{ data: StorageBucketMeta[] | null; error: SupatypeError | null }> {
60
233
  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 }
234
+ const res = await this.send(`${this.url}/bucket`, { headers: await this.headers() })
235
+ if (!res.ok) return { data: null, error: { message: await storageRefusal(res, "Failed to list buckets") } }
236
+ return { data: await readBuckets(res), error: null }
68
237
  } catch (e) {
69
- return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
238
+ return { data: null, error: transportFailure(e) }
70
239
  }
71
240
  }
72
241
 
@@ -82,18 +251,15 @@ export class StorageClient {
82
251
  ...(options?.fileSizeLimit !== undefined && { file_size_limit: options.fileSizeLimit }),
83
252
  ...(options?.allowedMimeTypes !== undefined && { allowed_mime_types: options.allowedMimeTypes }),
84
253
  }
85
- const res = await fetch(`${this.url}/bucket`, {
254
+ const res = await this.send(`${this.url}/bucket`, {
86
255
  method: "POST",
87
256
  headers: { ...(await this.headers()), "Content-Type": "application/json" },
88
257
  body: JSON.stringify(body),
89
258
  })
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
- }
259
+ if (!res.ok) return { data: null, error: { message: await storageRefusal(res, "Failed to create bucket") } }
94
260
  return { data: { name }, error: null }
95
261
  } catch (e) {
96
- return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
262
+ return { data: null, error: transportFailure(e) }
97
263
  }
98
264
  }
99
265
  }
@@ -102,8 +268,10 @@ export class BucketClient {
102
268
  private readonly url: string
103
269
  private readonly bucket: string
104
270
  private readonly headers: AuthHeaders
271
+ private readonly send: RequestTransport
105
272
 
106
- constructor(url: string, bucket: string, headers: AuthHeaders) {
273
+ constructor(url: string, bucket: string, headers: AuthHeaders, transport: RequestTransport = plainFetch) {
274
+ this.send = transport
107
275
  this.url = url
108
276
  this.bucket = bucket
109
277
  this.headers = headers
@@ -122,14 +290,13 @@ export class BucketClient {
122
290
  if (options?.upsert === true) {
123
291
  headers["x-upsert"] = "true"
124
292
  }
125
- const res = await fetch(`${this.url}/object/${this.bucket}/${path}`, {
293
+ const res = await this.send(`${this.url}/object/${this.bucket}/${path}`, {
126
294
  method: "POST",
127
295
  headers,
128
296
  body: file,
129
297
  })
130
298
  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 } }
299
+ return { data: null, error: { message: await storageRefusal(res, "Upload failed"), status: res.status } }
133
300
  }
134
301
  return { data: { path }, error: null }
135
302
  }
@@ -139,10 +306,9 @@ export class BucketClient {
139
306
  options?: { transform?: TransformOptions | undefined } | undefined,
140
307
  ): Promise<{ data: Blob | null; error: SupatypeError | null }> {
141
308
  const url = this.buildObjectUrl("authenticated", path, options?.transform)
142
- const res = await fetch(url, { headers: await this.headers() })
309
+ const res = await this.send(url, { headers: await this.headers() })
143
310
  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 } }
311
+ return { data: null, error: { message: await storageRefusal(res, "Download failed"), status: res.status } }
146
312
  }
147
313
  const blob = await res.blob()
148
314
  return { data: blob, error: null }
@@ -176,16 +342,17 @@ export class BucketClient {
176
342
  path: string,
177
343
  expiresIn: number,
178
344
  ): Promise<{ data: { signedUrl: string } | null; error: SupatypeError | null }> {
179
- const res = await fetch(`${this.url}/object/sign/${this.bucket}/${path}`, {
345
+ const res = await this.send(`${this.url}/object/sign/${this.bucket}/${path}`, {
180
346
  method: "POST",
347
+ // Signing creates nothing on the server, so a second request is harmless.
348
+ idempotent: true,
181
349
  headers: { ...(await this.headers()), "Content-Type": "application/json" },
182
350
  body: JSON.stringify({ expiresIn }),
183
351
  })
184
352
  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 } }
353
+ return { data: null, error: { message: await storageRefusal(res, "Failed to create signed URL"), status: res.status } }
187
354
  }
188
- const json = await res.json() as { signedURL: string }
355
+ const json = await readJson(res, isShape({ signedURL: isString }))
189
356
  return { data: { signedUrl: this.absoluteObjectUrl(json.signedURL) }, error: null }
190
357
  }
191
358
 
@@ -205,40 +372,44 @@ export class BucketClient {
205
372
  return { data: results, error: null }
206
373
  }
207
374
 
208
- async remove(paths: string[]): Promise<{ data: StorageObject[] | null; error: SupatypeError | null }> {
209
- const res = await fetch(`${this.url}/object/${this.bucket}`, {
375
+ async remove(paths: string[]): Promise<{ data: RemovedObject[] | null; error: SupatypeError | null }> {
376
+ const res = await this.send(`${this.url}/object/${this.bucket}`, {
210
377
  method: "DELETE",
211
378
  headers: { ...(await this.headers()), "Content-Type": "application/json" },
212
379
  body: JSON.stringify({ prefixes: paths }),
213
380
  })
214
381
  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 } }
382
+ return { data: null, error: { message: await storageRefusal(res, "Delete failed"), status: res.status } }
217
383
  }
218
- const json = await res.json() as StorageObject[]
219
- return { data: json, error: null }
384
+ return { data: await readJson(res, isRemovedObjects), error: null }
220
385
  }
221
386
 
387
+ /**
388
+ * The folder `prefix` names ("" or none for the bucket root): its subfolders, then its objects, each
389
+ * named relative to it. `count` is how many entries match in all, before `limit` and `offset`,
390
+ * or null from a server that does not send it.
391
+ */
222
392
  async list(
223
393
  prefix?: string | undefined,
224
- options?: { limit?: number | undefined; offset?: number | undefined } | undefined,
225
- ): Promise<{ data: StorageObject[] | null; error: SupatypeError | null }> {
394
+ options?: ListOptions | undefined,
395
+ ): Promise<{ data: StorageListEntry[] | null; count: number | null; error: SupatypeError | null }> {
226
396
  const body: Record<string, unknown> = {
227
397
  ...(prefix !== undefined && { prefix }),
398
+ ...(options?.search !== undefined && { search: options.search }),
228
399
  ...(options?.limit !== undefined && { limit: options.limit }),
229
400
  ...(options?.offset !== undefined && { offset: options.offset }),
230
401
  }
231
- const res = await fetch(`${this.url}/object/list/${this.bucket}`, {
402
+ const res = await this.send(`${this.url}/object/list/${this.bucket}`, {
232
403
  method: "POST",
404
+ // A read that happens to be sent as POST.
405
+ idempotent: true,
233
406
  headers: { ...(await this.headers()), "Content-Type": "application/json" },
234
407
  body: JSON.stringify(body),
235
408
  })
236
409
  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 } }
410
+ return { data: null, count: null, error: { message: await storageRefusal(res, "List failed"), status: res.status } }
239
411
  }
240
- const json = await res.json() as StorageObject[]
241
- return { data: json, error: null }
412
+ return { data: await readJson(res, isStorageEntries), count: countHeader(res), error: null }
242
413
  }
243
414
 
244
415
  // ─── Internal ───────────────────────────────────────────────────────────────
@@ -0,0 +1,160 @@
1
+ import type { ChannelStatus, RealtimeClient, RealtimeEvent, RealtimePayload } from "./realtime.js"
2
+ import type { SupatypeError } from "./types.js"
3
+ import { isJsonObject } from "./json.js"
4
+
5
+ /**
6
+ * A table's live rows, for `from(table).subscribe()` and for the Vue, Svelte and Solid bindings.
7
+ *
8
+ * Each binding carried its own copy of the channel wiring, the status mapping and the row merge,
9
+ * beside the client's own wiring for `from(table).subscribe()`. The copies drifted the way copies
10
+ * do: none of the three bindings mapped SUBSCRIBING, so while a sign-in swapped the socket all
11
+ * three read "connected" with no join anywhere, and all three still shared one `public:table`
12
+ * channel that the client's own subscribe had long since stopped sharing. One copy here means
13
+ * each binding is only the adapter between this and its framework's state.
14
+ */
15
+
16
+ /** What a binding shows for a subscription's connection. */
17
+ export type SubscriptionState = "connecting" | "connected" | "disconnected" | "error"
18
+
19
+ /** A binding's status and error, as one channel status implies them. */
20
+ export interface SubscriptionView {
21
+ status: SubscriptionState
22
+ error: SupatypeError | null
23
+ }
24
+
25
+ export interface TableWatchOptions {
26
+ event?: RealtimeEvent | undefined
27
+ filter?: string | undefined
28
+ }
29
+
30
+ export interface TableSubscribeOptions extends TableWatchOptions {
31
+ schema?: string | undefined
32
+ }
33
+
34
+ export interface TableWatchHandlers<TRow> {
35
+ /** The rows seen so far, after each change. */
36
+ rows(rows: TRow[]): void
37
+ /** The connection, after each status the channel reports. */
38
+ status(view: SubscriptionView): void
39
+ }
40
+
41
+ export interface TableSubscription {
42
+ unsubscribe: () => void
43
+ channel: ReturnType<RealtimeClient["channel"]>
44
+ }
45
+
46
+ /**
47
+ * Makes each table subscription's channel name unique.
48
+ *
49
+ * Module-wide rather than per client because it only has to be unique, and a name never seen by
50
+ * one client cannot collide on another.
51
+ */
52
+ let tableSubscriptionCount = 0
53
+
54
+ /**
55
+ * Subscribe to postgres_changes on one table, and join.
56
+ *
57
+ * Each call gets a channel of its own, named `schema:table:n`. The server keys a subscription by
58
+ * channel, so two calls sharing `schema:table` shared one filter and one event, and the first to
59
+ * unsubscribe removed the channel out from under the second. The name still reads as
60
+ * `schema:table` to anything that splits it, which is what a server predating `table` in the
61
+ * subscribe frame falls back to.
62
+ */
63
+ export function subscribeToTable<TRow>(
64
+ realtime: RealtimeClient,
65
+ table: string,
66
+ callback: (payload: RealtimePayload<TRow>) => void,
67
+ opts?: TableSubscribeOptions | undefined,
68
+ ): TableSubscription {
69
+ const schema = opts?.schema ?? "public"
70
+ tableSubscriptionCount += 1
71
+ const channel = realtime
72
+ .channel<TRow>(`${schema}:${table}:${tableSubscriptionCount}`)
73
+ .on(
74
+ "postgres_changes",
75
+ {
76
+ event: opts?.event ?? "*",
77
+ schema,
78
+ table,
79
+ ...(opts?.filter !== undefined && { filter: opts.filter }),
80
+ },
81
+ callback,
82
+ )
83
+ // `on()` only records the listener. Without this nothing opened a socket or sent the join,
84
+ // and the callback waited forever unless something else on the client had joined already.
85
+ .subscribe()
86
+ return { channel, unsubscribe: () => channel.unsubscribe() }
87
+ }
88
+
89
+ /**
90
+ * The status and error a binding shows for a channel status.
91
+ *
92
+ * A refused join and a reconnect that gave up are both errors: neither is going to deliver
93
+ * anything without the caller doing something about it.
94
+ */
95
+ export function subscriptionViewOf(status: ChannelStatus): SubscriptionView {
96
+ switch (status) {
97
+ case "SUBSCRIBING":
98
+ return { status: "connecting", error: null }
99
+ case "SUBSCRIBED":
100
+ return { status: "connected", error: null }
101
+ case "CLOSED":
102
+ return { status: "disconnected", error: null }
103
+ case "CHANNEL_ERROR":
104
+ return { status: "error", error: { message: "Subscription error" } }
105
+ case "TIMED_OUT":
106
+ return { status: "error", error: { message: "Realtime connection timed out" } }
107
+ }
108
+ }
109
+
110
+ function rowId(row: unknown): unknown {
111
+ return isJsonObject(row) ? row["id"] : undefined
112
+ }
113
+
114
+ /**
115
+ * The rows after one change, matched on `id`.
116
+ *
117
+ * An insert or update always carries the new row; one without it (which the service does not send)
118
+ * leaves the rows as they were rather than putting a null among them.
119
+ */
120
+ export function applyRowChange<TRow>(rows: TRow[] | null, payload: RealtimePayload<TRow>): TRow[] {
121
+ const current = rows ?? []
122
+ const next = payload.new
123
+ switch (payload.eventType) {
124
+ case "INSERT":
125
+ return next === null ? current : [...current, next]
126
+ case "UPDATE":
127
+ return next === null ? current : current.map((row) => (rowId(row) === rowId(next) ? next : row))
128
+ case "DELETE":
129
+ return current.filter((row) => rowId(row) !== rowId(payload.old))
130
+ default:
131
+ return current
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Subscribe to changes on a `public` table, and return the unsubscribe.
137
+ *
138
+ * The handlers are told the rows and the connection status; the binding decides where they live.
139
+ * The status is watched on the channel `subscribeToTable` already joined, which is what its
140
+ * channel's `subscribe(cb)` is for.
141
+ */
142
+ export function watchTable<TRow>(
143
+ realtime: RealtimeClient,
144
+ table: string,
145
+ options: TableWatchOptions | undefined,
146
+ handlers: TableWatchHandlers<TRow>,
147
+ ): () => void {
148
+ let rows: TRow[] | null = null
149
+ const subscription = subscribeToTable<TRow>(
150
+ realtime,
151
+ table,
152
+ (payload) => {
153
+ rows = applyRowChange(rows, payload)
154
+ handlers.rows(rows)
155
+ },
156
+ options,
157
+ )
158
+ subscription.channel.subscribe((status) => handlers.status(subscriptionViewOf(status)))
159
+ return subscription.unsubscribe
160
+ }