@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
package/src/index.ts CHANGED
@@ -1,13 +1,26 @@
1
1
  import { AuthClient } from "./auth.js"
2
2
  import { onIdentityChange } from "./identity.js"
3
3
  import { PreviewCredential } from "./preview.js"
4
- import { QueryBuilder, MutationBuilder, type HeadersProvider } from "./query.js"
4
+ import {
5
+ QueryBuilder,
6
+ MutationBuilder,
7
+ fetchWithOptional401Retry,
8
+ type DraftCreate,
9
+ type HeadersProvider,
10
+ } from "./query.js"
11
+ import { registeredDraftModel } from "./draft-models-registry.js"
12
+ import { GENERATED_CLIENT_IMPORT } from "./generated-client.js"
13
+ import type { FetchOptions, RequestTransport } from "./fetch-with-retry.js"
5
14
  import { defaultQueryCache, type QueryCache } from "./query-cache.js"
6
15
  import { StorageClient } from "./storage.js"
7
16
  import { RealtimeClient } from "./realtime.js"
8
- import type { RealtimeEvent, RealtimePayload } from "./realtime.js"
9
- import { PostgrestError } from "./errors.js"
17
+ import type { RealtimePayload } from "./realtime.js"
18
+ import { subscribeToTable, type TableSubscribeOptions, type TableSubscription } from "./table-subscription.js"
19
+ import { PostgrestError, transportFailure } from "./errors.js"
10
20
  import { createRetryFetch } from "./retry.js"
21
+ import { isJsonObject, isString, readJsonObject, refusalText } from "./json.js"
22
+ import { jwtRole } from "./jwt.js"
23
+ import { createGraphqlRunner } from "./graphql-transport.js"
11
24
  import { warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
12
25
  import type {
13
26
  AnyDatabase,
@@ -19,7 +32,11 @@ import type {
19
32
  SupatypeError,
20
33
  RpcOptions,
21
34
  SelectQueryOptions,
35
+ TableDef,
36
+ UpdateOptions,
22
37
  } from "./types.js"
38
+ import type { MutationOptions } from "./query.js"
39
+ import type { SelectRow } from "./select-types.js"
23
40
  import { DRAFT_SCHEMA } from "./types.js"
24
41
 
25
42
  export type {
@@ -28,6 +45,7 @@ export type {
28
45
  AuthChangeEvent,
29
46
  AuthFlowType,
30
47
  SupatypeError,
48
+ AuthRedirectError,
31
49
  QueryResult,
32
50
  MaskedField,
33
51
  RpcResult,
@@ -45,13 +63,16 @@ export type {
45
63
  SupatypeBuckets,
46
64
  SupatypeFunctions,
47
65
  AugmentedDatabase,
66
+ DraftUpdateOptions,
67
+ UpdateOptions,
48
68
  } from "./types.js"
49
69
  export {
50
70
  generateCodeVerifier,
51
71
  createCodeChallengeS256,
52
72
  PKCE_METHOD_S256,
53
73
  } from "./pkce.js"
54
- export { DRAFT_SCHEMA } from "./types.js"
74
+ export { DRAFT_SCHEMA, PUBLISHING_SCHEMA } from "./types.js"
75
+ export type { SelectRow, SelectError, TableRelationship } from "./select-types.js"
55
76
 
56
77
  /**
57
78
  * A client whose database type the holder does not know.
@@ -70,15 +91,17 @@ export type AnyClient = SupatypeClient<AnyDatabase>
70
91
  export type { QueryCacheOptions, CacheStatus } from "./query-cache.js"
71
92
  export { AuthClient } from "./auth.js"
72
93
  export { onIdentityChange, type IdentitySource } from "./identity.js"
73
- export { QueryBuilder, MutationBuilder, type HeadersProvider } from "./query.js"
94
+ export { QueryBuilder, MutationBuilder, type HeadersProvider, type RequestTransport } from "./query.js"
74
95
  export { QueryCache, defaultQueryCache } from "./query-cache.js"
75
96
  export { StorageClient, BucketClient } from "./storage.js"
76
- export type { StorageObject, TransformOptions } from "./storage.js"
97
+ export type { StorageObject, StorageFolder, StorageListEntry, ListOptions, RemovedObject, StorageReference, TransformOptions } from "./storage.js"
77
98
  export { RealtimeClient } from "./realtime.js"
78
99
  export type { RealtimeEvent, RealtimePayload, ChannelStatus, PresenceEntry } from "./realtime.js"
100
+ // The bindings' shared subscription helpers are on `@supatype/client/bindings`, not here.
101
+ export type { TableSubscribeOptions, TableSubscription } from "./table-subscription.js"
79
102
  export * from "./errors.js"
80
103
 
81
- // Called by the generated `supatype/client.ts`, which is how a project tells the client which
104
+ // Called by the generated `supatype/generated/client.ts`, which is how a project tells the client which
82
105
  // columns hold values a JSON parser would destroy. Exported because generated code imports it;
83
106
  // applications do not call it.
84
107
  export {
@@ -86,7 +109,17 @@ export {
86
109
  fieldKindsAreRegistered,
87
110
  forgetRegisteredFieldKinds,
88
111
  type FieldKindsDocument,
112
+ type UnrecognisedFieldKindsDocument,
89
113
  } from "./field-kinds-registry.js"
114
+ // Also called by the generated file: which tables keep drafts, so `insert` creates their records
115
+ // through `supatype.create_record`.
116
+ export {
117
+ registerDraftModels,
118
+ forgetRegisteredDraftModels,
119
+ type DraftModel,
120
+ type DraftModelsDocument,
121
+ type UnrecognisedDraftModelsDocument,
122
+ } from "./draft-models-registry.js"
90
123
  export { fetchWithRetry, detectServerlessEnvironment, warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
91
124
  export type { FetchOptions, ServerlessDetectionResult } from "./fetch-with-retry.js"
92
125
  export { createRetryFetch } from "./retry.js"
@@ -96,37 +129,45 @@ export type { ErrorCodeEntry } from "./error-codes-doc.js"
96
129
  export { CONNECTION_MODES, SERVERLESS_CONNECTION_WARNING, CONNECTION_FAQ } from "./serverless-docs.js"
97
130
  export type { ConnectionModeDoc } from "./serverless-docs.js"
98
131
  export { PreviewLinkError } from "./preview.js"
132
+ // pg_graphql sends its `JSON` scalar as a string and `graphql()` decodes it. These let another
133
+ // GraphQL client decode the same way with the schema it reads, and Studio's explorer run its
134
+ // send-as requests through the same runner.
135
+ export {
136
+ GRAPHQL_SCHEMA_QUERY,
137
+ GraphqlSchemaCache,
138
+ decodeGraphqlJsonFields,
139
+ readGraphqlSchema,
140
+ type GraphqlJsonDecoding,
141
+ type GraphqlSchema,
142
+ } from "./graphql-json.js"
143
+ export { createGraphqlRunner, type GraphqlTransport } from "./graphql-transport.js"
99
144
 
100
145
  // ─── Table client ─────────────────────────────────────────────────────────────
101
146
 
102
- interface TableDef {
103
- Row: Record<string, unknown>
104
- Insert: Record<string, unknown>
105
- Update: Record<string, unknown>
106
- }
107
-
108
147
  /**
109
- * Makes each `from(table).subscribe()` channel name unique.
110
- *
111
- * Module-wide rather than per client because it only has to be unique, and a name never seen by
112
- * one client cannot collide on another.
148
+ * One table, typed by its definition and by every table beside it: an embedded select is resolved
149
+ * against the other tables' rows and the relationships between them.
113
150
  */
114
- let tableSubscriptionCount = 0
115
-
116
- class TableClient<TDef extends TableDef> {
151
+ class TableClient<
152
+ TDef extends TableDef,
153
+ TTables extends Record<string, TableDef> = Record<string, TableDef>,
154
+ TName extends string = string,
155
+ > {
117
156
  private readonly baseUrl: string
118
157
  private readonly table: string
119
158
  private readonly path: string
120
159
  private readonly getHeaders: HeadersProvider
121
160
  private readonly onUnauthorized: (() => Promise<void>) | undefined
161
+ /** The client's retry-aware fetch, so `timeout` and `retry` reach table requests too. */
162
+ private readonly send: RequestTransport
122
163
  private readonly queryCache: QueryCache
123
164
  private readonly realtime: RealtimeClient
124
165
  /**
125
166
  * The schema this table's reads come from, set by `draft()`.
126
167
  *
127
168
  * Mutable, and safe to be: `from()` builds a fresh client per call, so nothing is shared between
128
- * two queries. Reads only; a draft view is not writable and a write is an ordinary update that
129
- * records a new version.
169
+ * two queries. Reads only: a draft view is not writable, and `update` on a model with drafts
170
+ * saves a new version through the publishing functions instead.
130
171
  */
131
172
  private profile: string | undefined
132
173
 
@@ -136,7 +177,8 @@ class TableClient<TDef extends TableDef> {
136
177
  getHeaders: HeadersProvider,
137
178
  realtime: RealtimeClient,
138
179
  queryCache: QueryCache = defaultQueryCache,
139
- onUnauthorized?: (() => Promise<void>) | undefined,
180
+ onUnauthorized: (() => Promise<void>) | undefined,
181
+ send: RequestTransport,
140
182
  ) {
141
183
  this.baseUrl = baseUrl
142
184
  this.table = table
@@ -145,6 +187,7 @@ class TableClient<TDef extends TableDef> {
145
187
  this.realtime = realtime
146
188
  this.onUnauthorized = onUnauthorized
147
189
  this.queryCache = queryCache
190
+ this.send = send
148
191
  }
149
192
 
150
193
  /**
@@ -161,15 +204,35 @@ class TableClient<TDef extends TableDef> {
161
204
  * **Read-only, and permission is not the read rule.** A draft is visible to the record's creator
162
205
  * and to the project's elevated Studio roles, or to a caller holding a signed preview link. A
163
206
  * caller who may read published content is not thereby entitled to read what has not been
164
- * published. Write with the ordinary `update`, which records a new draft version; publish with
165
- * `supatype.publish`.
207
+ * published. Write with the ordinary `update`, which on a model with drafts saves a new draft of
208
+ * each record it matches and leaves the live rows alone; pass `{ publish: true }` to publish in the
209
+ * same call. A saved draft is published later by the generated `publish` database function in the
210
+ * `supatype` schema:
211
+ * `rpc("publish", { model_table: "posts", record_id: id }, { schema: "supatype" })`.
166
212
  */
167
213
  draft(): this {
168
214
  this.profile = DRAFT_SCHEMA
169
215
  return this
170
216
  }
171
217
 
172
- select<TResult = TDef["Row"]>(
218
+ /**
219
+ * Read rows, typed from the select string.
220
+ *
221
+ * `select("id, author:authors(name)")` resolves to `{ id: string; author: { name: string } | null }`
222
+ * from the generated schema: columns, aliases and embedded relations are read from the string, so
223
+ * the joined shape is not declared a second time by hand. See `select-types.ts` for the grammar.
224
+ * A string only known at run time types as the whole row.
225
+ */
226
+ select<TColumns extends string = "*">(
227
+ columns?: TColumns | undefined,
228
+ options?: SelectQueryOptions | undefined,
229
+ ): QueryBuilder<SelectRow<TTables, TName, TColumns>>
230
+ /** Read rows typed as `TResult`, for a shape the select string cannot describe. */
231
+ select<TResult>(
232
+ columns?: string | undefined,
233
+ options?: SelectQueryOptions | undefined,
234
+ ): QueryBuilder<TResult>
235
+ select<TResult>(
173
236
  columns?: string | undefined,
174
237
  options?: SelectQueryOptions | undefined,
175
238
  ): QueryBuilder<TResult> {
@@ -183,27 +246,56 @@ class TableClient<TDef extends TableDef> {
183
246
  // The profile joins the select options rather than riding a longer constructor: it is a
184
247
  // property of the request being described, like `count` and `head` beside it.
185
248
  { ...options, ...(this.profile !== undefined && { profile: this.profile }) },
249
+ this.send,
186
250
  )
187
251
  }
188
252
 
253
+ /**
254
+ * Insert one row or several.
255
+ *
256
+ * **On a model that keeps drafts**, one record is created through `supatype.create_record`, as
257
+ * Studio creates it, and several through `supatype.create_records`, all or none in one call: each
258
+ * record starts as its first draft, and the rows come back read from the draft view in the shape
259
+ * and order a plain insert returns. A plain insert asking for the row back is refused there by a
260
+ * read rule that hides unpublished records, because Postgres checks the returned row against it
261
+ * before anything has made the new row visible to its author. The generated `supatype/generated/client.ts`
262
+ * says which models keep drafts; a client without it inserts as before.
263
+ */
189
264
  insert(
190
265
  data: TDef["Insert"] | TDef["Insert"][],
191
- ): MutationBuilder<TDef["Row"]> {
192
- return new MutationBuilder<TDef["Row"]>(
266
+ ): MutationBuilder<TDef["Row"], TTables, TName> {
267
+ return new MutationBuilder<TDef["Row"], TTables, TName>(
193
268
  this.baseUrl,
194
269
  this.path,
195
270
  this.getHeaders,
196
271
  "POST",
197
272
  data,
198
- undefined,
273
+ { createThrough: this.draftCreate(data) },
199
274
  this.onUnauthorized,
275
+ this.send,
200
276
  )
201
277
  }
202
278
 
279
+ /** Where an insert of `data` is created through the publishing functions: any rows, on a drafts model. */
280
+ private draftCreate(data: TDef["Insert"] | TDef["Insert"][]): DraftCreate | undefined {
281
+ const model = registeredDraftModel(this.table)
282
+ if (model === undefined) return undefined
283
+ // Nothing to create: the plain insert answers an empty array with no rows, as it always has.
284
+ if (Array.isArray(data) && data.length === 0) return undefined
285
+ return { table: this.table, primaryKey: model.primaryKey }
286
+ }
287
+
288
+ /**
289
+ * Insert, or update the row a key or unique column already names.
290
+ *
291
+ * Never sent through `create_record`, on a drafts model or not: it cannot say what happens on a
292
+ * conflict, and an upsert that met an existing record would make a second one rather than update
293
+ * it. On a drafts model whose read rule hides unpublished records, create through `insert`.
294
+ */
203
295
  upsert(
204
296
  data: TDef["Insert"] | TDef["Insert"][],
205
- ): MutationBuilder<TDef["Row"]> {
206
- return new MutationBuilder<TDef["Row"]>(
297
+ ): MutationBuilder<TDef["Row"], TTables, TName> {
298
+ return new MutationBuilder<TDef["Row"], TTables, TName>(
207
299
  this.baseUrl,
208
300
  this.path,
209
301
  this.getHeaders,
@@ -211,23 +303,48 @@ class TableClient<TDef extends TableDef> {
211
303
  data,
212
304
  { upsert: true },
213
305
  this.onUnauthorized,
306
+ this.send,
214
307
  )
215
308
  }
216
309
 
217
- update(data: TDef["Update"]): MutationBuilder<TDef["Row"]> {
218
- return new MutationBuilder<TDef["Row"]>(
310
+ /**
311
+ * Change the rows the filters match.
312
+ *
313
+ * **On a model that keeps drafts** the live rows do not change: each matched record gets a new
314
+ * draft through `supatype.save_drafts`, merged onto its newest version as Studio saves one, all or
315
+ * none in one call, and the drafts come back read from the draft view. Pass `{ publish: true }` to
316
+ * publish them in the same call, so the history records the version that went live. The generated
317
+ * `supatype/generated/client.ts` says which models keep drafts; elsewhere this is a plain `PATCH`, and
318
+ * `{ publish: true }` is refused, since there is nothing to publish.
319
+ */
320
+ update(
321
+ data: TDef["Update"],
322
+ options?: UpdateOptions<TDef>,
323
+ ): MutationBuilder<TDef["Row"], TTables, TName> {
324
+ return new MutationBuilder<TDef["Row"], TTables, TName>(
219
325
  this.baseUrl,
220
326
  this.path,
221
327
  this.getHeaders,
222
328
  "PATCH",
223
329
  data,
224
- undefined,
330
+ this.draftEdit(options),
225
331
  this.onUnauthorized,
332
+ this.send,
226
333
  )
227
334
  }
228
335
 
229
- delete(): MutationBuilder<TDef["Row"]> {
230
- return new MutationBuilder<TDef["Row"]>(
336
+ /** How an update is made: as drafts on a drafts model, else a plain `PATCH`, or refused. */
337
+ private draftEdit(options: unknown): MutationOptions | undefined {
338
+ const publish = isJsonObject(options) && options["publish"] === true
339
+ const model = registeredDraftModel(this.table)
340
+ if (model !== undefined) return { editThrough: { table: this.table, primaryKey: model.primaryKey, publish } }
341
+ if (!publish) return undefined
342
+ const message = `{ publish: true } applies to a model that keeps drafts, and "${this.table}" is not one this client knows of. Import the client from the generated ${GENERATED_CLIENT_IMPORT}, which says which models keep drafts.`
343
+ return { refusal: { message } }
344
+ }
345
+
346
+ delete(): MutationBuilder<TDef["Row"], TTables, TName> {
347
+ return new MutationBuilder<TDef["Row"], TTables, TName>(
231
348
  this.baseUrl,
232
349
  this.path,
233
350
  this.getHeaders,
@@ -235,6 +352,7 @@ class TableClient<TDef extends TableDef> {
235
352
  undefined,
236
353
  undefined,
237
354
  this.onUnauthorized,
355
+ this.send,
238
356
  )
239
357
  }
240
358
 
@@ -244,47 +362,14 @@ class TableClient<TDef extends TableDef> {
244
362
  * Phase 10.6 F11: preferred over raw `client.realtime.channel(...)`. The returned `channel` is
245
363
  * already subscribed; call `channel.subscribe(cb)` only to watch its status.
246
364
  *
247
- * Each call gets a channel of its own, named `schema:table:n`. The server keys a subscription by
248
- * channel, so two calls sharing `schema:table` shared one filter and one event, and the first to
249
- * unsubscribe removed the channel out from under the second. The name still reads as
250
- * `schema:table` to anything that splits it, which is what a server predating `table` in the
251
- * subscribe frame falls back to.
365
+ * Each call gets a channel of its own; `subscribeToTable` says why. The framework bindings join
366
+ * through the same function, so a table subscribed either way behaves the same.
252
367
  */
253
368
  subscribe(
254
369
  callback: (payload: RealtimePayload<TDef["Row"]>) => void,
255
- opts?: {
256
- event?: RealtimeEvent | undefined
257
- filter?: string | undefined
258
- schema?: string | undefined
259
- } | undefined,
260
- ): {
261
- unsubscribe: () => void
262
- channel: ReturnType<RealtimeClient["channel"]>
263
- } {
264
- const event = opts?.event ?? "*"
265
- const schema = opts?.schema ?? "public"
266
- tableSubscriptionCount += 1
267
- const channel = this.realtime
268
- .channel(`${schema}:${this.table}:${tableSubscriptionCount}`)
269
- .on(
270
- "postgres_changes",
271
- {
272
- event,
273
- schema,
274
- table: this.table,
275
- ...(opts?.filter !== undefined && { filter: opts.filter }),
276
- },
277
- callback,
278
- )
279
- // `on()` only records the listener. Without this nothing opened a socket or sent the join,
280
- // and the callback waited forever unless something else on the client had joined already.
281
- .subscribe()
282
- return {
283
- channel,
284
- unsubscribe: () => {
285
- channel.unsubscribe()
286
- },
287
- }
370
+ opts?: TableSubscribeOptions | undefined,
371
+ ): TableSubscription {
372
+ return subscribeToTable(this.realtime, this.table, callback, opts)
288
373
  }
289
374
  }
290
375
 
@@ -295,18 +380,30 @@ export interface GlobalClient<TRow extends Record<string, unknown> = Record<stri
295
380
  update(data: Partial<TRow>): Promise<{ data: TRow | null; error: SupatypeError | null }>
296
381
  }
297
382
 
298
- function jwtRole(token: string): string | null {
299
- const parts = token.split(".")
300
- if (parts.length !== 3) return null
301
- try {
302
- const payloadJson =
303
- typeof atob === "function"
304
- ? atob(parts[1] ?? "")
305
- : Buffer.from(parts[1] ?? "", "base64").toString("utf-8")
306
- const payload = JSON.parse(payloadJson) as Record<string, unknown>
307
- return typeof payload["role"] === "string" ? payload["role"] : null
308
- } catch {
309
- return null
383
+ /**
384
+ * The boundary between a function's answer and the return type the generated schema declares.
385
+ *
386
+ * A database or edge function may answer with any JSON value (an edge function with text, too), so
387
+ * the only thing to check is that there is a value. That it has the declared type is the generated
388
+ * schema's claim about the function, which nothing on the client can check.
389
+ */
390
+ function isDeclaredReturn<T>(value: unknown): value is T {
391
+ return value !== undefined
392
+ }
393
+
394
+ /**
395
+ * The message and machine-readable code on an edge function's error body. A handler may send its
396
+ * own `code`. The functions worker answers its own failures as `{ error: <code>, message }`, so
397
+ * `error` is a code when a `message` is beside it. On its own, `error` is a handler's sentence
398
+ * (`{ error: "Email already taken" }`) and is the message.
399
+ */
400
+ function functionError(body: Record<string, unknown>, status: number): SupatypeError {
401
+ const workerCode = isString(body["message"]) ? body["error"] : undefined
402
+ const code = isString(body["code"]) ? body["code"] : isString(workerCode) ? workerCode : undefined
403
+ return {
404
+ message: refusalText(body) ?? `Function returned ${status}`,
405
+ status,
406
+ ...(code !== undefined && { code }),
310
407
  }
311
408
  }
312
409
 
@@ -379,18 +476,26 @@ export interface FunctionInvokeOptions {
379
476
  headers?: Record<string, string> | undefined
380
477
  /** Request body (JSON-serialisable) */
381
478
  body?: unknown | undefined
479
+ /**
480
+ * Retry this call on a transient failure although it is not a GET. Default: false.
481
+ *
482
+ * Only GET calls are retried otherwise: a POST that failed in flight may already have run the
483
+ * function, and running it again could charge a card or send an email twice. Set this when a
484
+ * second run is harmless.
485
+ */
486
+ idempotent?: boolean | undefined
382
487
  }
383
488
 
384
489
  class FunctionsClient {
385
490
  private readonly baseUrl: string
386
491
  private readonly getHeaders: HeadersProvider
387
492
  private readonly onUnauthorized: (() => Promise<void>) | undefined
388
- private readonly doFetch: (url: string, init?: RequestInit) => Promise<Response>
493
+ private readonly doFetch: RequestTransport
389
494
 
390
495
  constructor(
391
496
  baseUrl: string,
392
497
  getHeaders: HeadersProvider,
393
- doFetch: (url: string, init?: RequestInit) => Promise<Response>,
498
+ doFetch: RequestTransport,
394
499
  onUnauthorized?: (() => Promise<void>) | undefined,
395
500
  ) {
396
501
  this.baseUrl = baseUrl
@@ -420,8 +525,9 @@ class FunctionsClient {
420
525
  ...options?.headers,
421
526
  })
422
527
 
423
- const fetchOpts: RequestInit = {
528
+ const fetchOpts: RequestInit & FetchOptions = {
424
529
  method,
530
+ ...(options?.idempotent === true && { idempotent: true }),
425
531
  }
426
532
 
427
533
  if (options?.body !== undefined && method !== "GET") {
@@ -429,46 +535,24 @@ class FunctionsClient {
429
535
  }
430
536
 
431
537
  try {
432
- let headers = await resolveHeaders()
433
- let res = await this.doFetch(
538
+ const res = await fetchWithOptional401Retry(
539
+ this.doFetch,
434
540
  `${this.baseUrl}/functions/v1/${functionName}`,
435
- { ...fetchOpts, headers },
541
+ fetchOpts,
542
+ resolveHeaders,
543
+ this.onUnauthorized,
436
544
  )
437
- if (res.status === 401 && this.onUnauthorized !== undefined) {
438
- await this.onUnauthorized()
439
- headers = await resolveHeaders()
440
- res = await this.doFetch(
441
- `${this.baseUrl}/functions/v1/${functionName}`,
442
- { ...fetchOpts, headers },
443
- )
444
- }
445
545
 
446
546
  if (!res.ok) {
447
- const body = await res.json().catch(() => ({})) as Record<string, unknown>
448
- return {
449
- data: null,
450
- error: {
451
- message: typeof body["message"] === "string" ? body["message"] : `Function returned ${res.status}`,
452
- status: res.status,
453
- ...(typeof body["code"] === "string" ? { code: body["code"] } : {}),
454
- },
455
- }
547
+ return { data: null, error: functionError(await readJsonObject(res), res.status) }
456
548
  }
457
549
 
458
550
  const contentType = res.headers.get("content-type") ?? ""
459
- if (contentType.includes("application/json")) {
460
- const data = await res.json() as EdgeFunctionReturns<TFn>
461
- return { data, error: null }
462
- }
463
-
464
- // Return text for non-JSON responses
465
- const text = await res.text()
466
- return { data: text as unknown as EdgeFunctionReturns<TFn>, error: null }
551
+ // Text for a response that is not JSON.
552
+ const data = contentType.includes("application/json") ? await res.json() : await res.text()
553
+ return { data: isDeclaredReturn<EdgeFunctionReturns<TFn>>(data) ? data : null, error: null }
467
554
  } catch (e) {
468
- return {
469
- data: null,
470
- error: { message: e instanceof Error ? e.message : "Network error" },
471
- }
555
+ return { data: null, error: transportFailure(e) }
472
556
  }
473
557
  }
474
558
  }
@@ -479,16 +563,26 @@ export interface SupatypeClient<TDatabase extends AnyDatabase = AugmentedDatabas
479
563
  serviceRoleKey: string | undefined
480
564
  from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
481
565
  table: TTable,
482
- ): TableClient<TDatabase["public"]["Tables"][TTable]>
566
+ ): TableClient<TDatabase["public"]["Tables"][TTable], TDatabase["public"]["Tables"], TTable>
483
567
  global<TRow extends Record<string, unknown> = Record<string, unknown>>(name: string): GlobalClient<TRow>
484
568
  auth: AuthClient
485
569
  storage: StorageClient
486
570
  realtime: RealtimeClient
487
571
  functions: FunctionsClient
488
- graphql(
572
+ /**
573
+ * Run a GraphQL query. `options.idempotent`: retry on a transient failure, for a query that is not
574
+ * a mutation.
575
+ *
576
+ * Rich text, blocks and json fields come back as values, not as the JSON strings pg_graphql sends:
577
+ * the client reads the schema once and decodes every field typed with its `JSON` scalar, through
578
+ * aliases, fragments, relations and lists. `TData` names the answer's shape, typically from
579
+ * `TableRow<"post">`; nothing checks it at runtime.
580
+ */
581
+ graphql<TData = unknown>(
489
582
  query: string,
490
583
  variables?: Record<string, unknown> | undefined,
491
- ): Promise<{ data: unknown; error: SupatypeError | null }>
584
+ options?: { idempotent?: boolean | undefined } | undefined,
585
+ ): Promise<{ data: TData | null; error: SupatypeError | null }>
492
586
  /**
493
587
  * Call a Postgres function via PostgREST's `/rpc/function_name` endpoint.
494
588
  *
@@ -533,11 +627,16 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
533
627
  ? null
534
628
  : new PreviewCredential(config.url, config.previewCode)
535
629
 
630
+ // `headers` may be a function, read on every request: Studio changes the acting mode it asks for
631
+ // without rebuilding its client (and losing its session and sockets).
632
+ const extraHeaders = (): Record<string, string> =>
633
+ typeof config.headers === "function" ? config.headers() : (config.headers ?? {})
634
+
536
635
  const baseHeaders: Record<string, string> = {
537
636
  apikey: config.anonKey,
538
637
  Authorization: `Bearer ${config.anonKey}`,
539
638
  "Content-Type": "application/json",
540
- ...config.headers,
639
+ ...extraHeaders(),
541
640
  }
542
641
 
543
642
  // Create a retry-aware fetch bound to client-level config
@@ -549,13 +648,17 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
549
648
  const auth = new AuthClient(`${config.url}/auth/v1`, baseHeaders, {
550
649
  initialSession: config.initialSession,
551
650
  persistSession: config.auth?.persistSession,
651
+ autoRefreshToken: config.auth?.autoRefreshToken,
652
+ refreshExpiredToken: config.auth?.refreshExpiredToken,
552
653
  storageKey: config.auth?.storageKey,
553
654
  cookiePrefix: config.auth?.cookiePrefix,
554
655
  storage: config.auth?.storage,
656
+ detectSessionInUrl: config.auth?.detectSessionInUrl,
657
+ transport: doFetch,
555
658
  })
556
659
  const queryCache = config.queryCache ?? defaultQueryCache
557
660
 
558
- const getAuthHeaders = async (): Promise<Record<string, string>> => {
661
+ const credentialHeaders = async (): Promise<Record<string, string>> => {
559
662
  // Studio and other admin tools pass serviceRoleKey, use it for table/RPC/GraphQL
560
663
  // so supatype_admin RLS policies and bypass rules apply (anon would fail).
561
664
  if (config.serviceRoleKey) {
@@ -563,7 +666,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
563
666
  apikey: config.serviceRoleKey,
564
667
  Authorization: `Bearer ${config.serviceRoleKey}`,
565
668
  "Content-Type": "application/json",
566
- ...config.headers,
669
+ ...extraHeaders(),
567
670
  }
568
671
  }
569
672
  // A preview link is the whole credential, and it comes before any session on purpose: whoever
@@ -587,13 +690,19 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
587
690
  return baseHeaders
588
691
  }
589
692
 
693
+ // Every request's headers: its credential, then the caller's own extra headers as they are now.
694
+ const getAuthHeaders = async (): Promise<Record<string, string>> => ({
695
+ ...(await credentialHeaders()),
696
+ ...extraHeaders(),
697
+ })
698
+
590
699
  // Storage asks for headers per request, like every other client here.
591
700
  //
592
701
  // It used to be handed a plain object built above, before anybody had signed in, so every storage
593
702
  // request carried the anon key for the life of the page. An app's per-user storage policies saw
594
703
  // `anon` rather than the caller, and through Studio's proxy the request was refused outright,
595
704
  // because an anon key carries no `sub` and the proxy requires one.
596
- const storage = new StorageClient(`${config.url}/storage/v1`, getAuthHeaders)
705
+ const storage = new StorageClient(`${config.url}/storage/v1`, getAuthHeaders, doFetch)
597
706
 
598
707
  // The same provider the other sub-clients get, not `baseHeaders`.
599
708
  //
@@ -608,6 +717,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
608
717
  : (): Promise<void> => auth.ensureValidSession()
609
718
 
610
719
  const functions = new FunctionsClient(config.url, getAuthHeaders, doFetch, onUnauthorized)
720
+ const runGraphql = createGraphqlRunner({ endpoint: `${config.url}/graphql/v1`, send: doFetch, headers: getAuthHeaders, onUnauthorized })
611
721
 
612
722
  // Signing in has to reach an already-open socket.
613
723
  //
@@ -626,30 +736,39 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
626
736
  void realtime.reauthenticate()
627
737
  })
628
738
 
739
+ // One place that wires a table to this client's headers, cache, auth refresh and fetch.
740
+ const tableClient = <
741
+ TDef extends TableDef,
742
+ TTables extends Record<string, TableDef> = Record<string, TableDef>,
743
+ TName extends string = string,
744
+ >(table: string): TableClient<TDef, TTables, TName> =>
745
+ new TableClient<TDef, TTables, TName>(config.url, table, getAuthHeaders, realtime, queryCache, onUnauthorized, doFetch)
746
+
629
747
  return {
630
748
  url: config.url,
631
749
  serviceRoleKey: config.serviceRoleKey,
632
750
 
633
751
  from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
634
752
  table: TTable,
635
- ): TableClient<TDatabase["public"]["Tables"][TTable]> {
753
+ ): TableClient<TDatabase["public"]["Tables"][TTable], TDatabase["public"]["Tables"], TTable> {
636
754
  type TDef = TDatabase["public"]["Tables"][TTable]
637
- return new TableClient<TDef>(config.url, table, getAuthHeaders, realtime, queryCache, onUnauthorized)
755
+ return tableClient<TDef, TDatabase["public"]["Tables"], TTable>(table)
638
756
  },
639
757
 
640
758
  global<TRow extends Record<string, unknown> = Record<string, unknown>>(name: string): GlobalClient<TRow> {
641
759
  const tableName = `_global_${name}`
642
- type TDef = { Row: TRow; Insert: TRow; Update: Partial<TRow> }
760
+ // A global is one row that always exists, so a write to it names only the fields it changes.
761
+ type TDef = { Row: TRow; Insert: Partial<TRow>; Update: Partial<TRow> }
643
762
  return {
644
763
  async get(): Promise<{ data: TRow | null; error: SupatypeError | null }> {
645
- const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders, realtime, queryCache, onUnauthorized)
764
+ const tc = tableClient<TDef, Record<string, TDef>>(tableName)
646
765
  const result = await tc.select().limit(1).maybeSingle()
647
766
  return { data: result.data ?? null, error: result.error }
648
767
  },
649
768
  async update(data: Partial<TRow>): Promise<{ data: TRow | null; error: SupatypeError | null }> {
650
- const tc = new TableClient<TDef>(config.url, tableName, getAuthHeaders, realtime, queryCache, onUnauthorized)
651
- const result = await tc.upsert(data as TRow)
652
- const row = Array.isArray(result.data) ? (result.data[0] as TRow | undefined) ?? null : null
769
+ const tc = tableClient<TDef>(tableName)
770
+ const result = await tc.upsert(data)
771
+ const row = result.data?.[0] ?? null
653
772
  return { data: row, error: result.error }
654
773
  },
655
774
  }
@@ -660,50 +779,17 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
660
779
  realtime,
661
780
  functions,
662
781
 
663
- async graphql(
782
+ /**
783
+ * Run a GraphQL query. Sent as a POST, so it is not retried unless `options.idempotent` says a
784
+ * second copy is harmless, as it is for any query that is not a mutation.
785
+ */
786
+ async graphql<TData = unknown>(
664
787
  query: string,
665
788
  variables?: Record<string, unknown> | undefined,
666
- ): Promise<{ data: unknown; error: SupatypeError | null }> {
667
- const body: Record<string, unknown> = { query }
668
- if (variables !== undefined) {
669
- body["variables"] = variables
670
- }
671
- let res: Response
672
- try {
673
- res = await doFetch(`${config.url}/graphql/v1`, {
674
- method: "POST",
675
- headers: await getAuthHeaders(),
676
- body: JSON.stringify(body),
677
- })
678
- if (res.status === 401 && onUnauthorized !== undefined) {
679
- await onUnauthorized()
680
- res = await doFetch(`${config.url}/graphql/v1`, {
681
- method: "POST",
682
- headers: await getAuthHeaders(),
683
- body: JSON.stringify(body),
684
- })
685
- }
686
- } catch (e) {
687
- return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
688
- }
689
- let json: Record<string, unknown>
690
- try {
691
- json = await res.json() as Record<string, unknown>
692
- } catch {
693
- return { data: null, error: { message: `GraphQL endpoint returned a non-JSON response (HTTP ${res.status} ${res.statusText})` } }
694
- }
695
- if (!res.ok) {
696
- const message =
697
- typeof json["message"] === "string" ? json["message"]
698
- : typeof json["error"] === "string" ? json["error"]
699
- : `GraphQL request failed (HTTP ${res.status})`
700
- return { data: json["data"] ?? null, error: { message, status: res.status } }
701
- }
702
- if (json["errors"] !== undefined) {
703
- const errors = json["errors"] as Array<{ message: string }>
704
- return { data: json["data"] ?? null, error: { message: (errors[0]?.message ?? "GraphQL error") } }
705
- }
706
- return { data: json["data"] ?? null, error: null }
789
+ options?: { idempotent?: boolean | undefined } | undefined,
790
+ ): Promise<{ data: TData | null; error: SupatypeError | null }> {
791
+ const { data, error } = await runGraphql(query, variables, options)
792
+ return { data: isDeclaredReturn<TData>(data) ? data : null, error }
707
793
  },
708
794
 
709
795
  async rpc<TFn extends FunctionNames<TDatabase>>(
@@ -711,47 +797,40 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
711
797
  params?: FunctionArgs<TDatabase, TFn> | undefined,
712
798
  options?: RpcOptions | undefined,
713
799
  ): Promise<RpcResult<FunctionReturns<TDatabase, TFn>>> {
714
- const headers: Record<string, string> = { ...(await getAuthHeaders()) }
715
800
  const method = options?.head === true ? "HEAD" : "POST"
716
-
717
- if (options?.count !== undefined) {
718
- headers["Prefer"] = `count=${options.count}`
719
- }
720
- // PostgREST resolves `/rpc/<name>` against the default profile, so a function in any other
721
- // schema is unreachable without this. `Content-Profile` rather than `Accept-Profile`, because
722
- // an RPC call is a POST and PostgREST reads the write-side header for it.
723
- if (options?.schema !== undefined) {
724
- headers["Content-Profile"] = options.schema
725
- }
801
+ // Resolved per attempt, so the resend after a 401 carries the same `Prefer` and profile as
802
+ // the first send. It used to rebuild only `Prefer` and drop the schema.
803
+ const rpcHeaders = async (): Promise<Record<string, string>> => ({
804
+ ...(await getAuthHeaders()),
805
+ ...(options?.count !== undefined && { Prefer: `count=${options.count}` }),
806
+ // PostgREST resolves `/rpc/<name>` against the default profile, so a function in any other
807
+ // schema is unreachable without this. `Content-Profile` rather than `Accept-Profile`,
808
+ // because an RPC call is a POST and PostgREST reads the write-side header for it.
809
+ ...(options?.schema !== undefined && { "Content-Profile": options.schema }),
810
+ })
726
811
 
727
812
  let res: Response
728
813
  try {
729
- res = await doFetch(`${config.url}/rest/v1/rpc/${fn}`, {
730
- method,
731
- headers,
732
- ...(params !== undefined && method !== "HEAD" && { body: JSON.stringify(params) }),
733
- })
734
- if (res.status === 401 && onUnauthorized !== undefined) {
735
- await onUnauthorized()
736
- const retryHeaders: Record<string, string> = { ...(await getAuthHeaders()) }
737
- if (options?.count !== undefined) {
738
- retryHeaders["Prefer"] = `count=${options.count}`
739
- }
740
- res = await doFetch(`${config.url}/rest/v1/rpc/${fn}`, {
814
+ res = await fetchWithOptional401Retry(
815
+ doFetch,
816
+ `${config.url}/rest/v1/rpc/${fn}`,
817
+ {
741
818
  method,
742
- headers: retryHeaders,
743
819
  ...(params !== undefined && method !== "HEAD" && { body: JSON.stringify(params) }),
744
- })
745
- }
820
+ ...(options?.idempotent === true && { idempotent: true }),
821
+ },
822
+ rpcHeaders,
823
+ onUnauthorized,
824
+ )
746
825
  } catch (e) {
747
- return { data: null, error: { message: e instanceof Error ? e.message : "Network error" } }
826
+ return { data: null, error: transportFailure(e) }
748
827
  }
749
828
 
750
829
  if (!res.ok) {
751
- const body = await res.json().catch(() => ({})) as Record<string, unknown>
830
+ const body = await readJsonObject(res)
752
831
  const pgError = PostgrestError.fromResponse(
753
832
  {
754
- message: typeof body["message"] === "string" ? body["message"] : undefined,
833
+ message: refusalText(body),
755
834
  code: typeof body["code"] === "string" ? body["code"] : undefined,
756
835
  details: typeof body["details"] === "string" ? body["details"] : undefined,
757
836
  hint: typeof body["hint"] === "string" ? body["hint"] : undefined,
@@ -764,6 +843,8 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
764
843
  message: pgError.message,
765
844
  status: pgError.statusCode,
766
845
  code: pgError.code,
846
+ ...(pgError.hint !== null && pgError.hint !== "" && { hint: pgError.hint }),
847
+ ...(pgError.details !== null && pgError.details !== "" && { details: pgError.details }),
767
848
  },
768
849
  }
769
850
  }
@@ -772,8 +853,8 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
772
853
  return { data: null, error: null }
773
854
  }
774
855
 
775
- const data = await res.json() as FunctionReturns<TDatabase, TFn>
776
- return { data, error: null }
856
+ const data = await res.json()
857
+ return { data: isDeclaredReturn<FunctionReturns<TDatabase, TFn>>(data) ? data : null, error: null }
777
858
  },
778
859
  }
779
860
  }