@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/dist/query.js CHANGED
@@ -1,26 +1,34 @@
1
1
  import { buildCacheKey, defaultQueryCache } from "./query-cache.js";
2
+ import { DRAFT_SCHEMA, PUBLISHING_SCHEMA } from "./types.js";
3
+ import { createCall, createdKeys, inCreatedOrder, readBackColumns } from "./draft-create.js";
2
4
  import { parseRowsExactly, tableFromPath } from "./exact-response.js";
3
5
  import { stringifyWithBigInts } from "./exact-values.js";
6
+ import { FilterBuilder } from "./filters.js";
7
+ import { PostgrestErrorCodes, transportFailure } from "./errors.js";
8
+ import { plainFetch } from "./fetch-with-retry.js";
9
+ import { isJsonObject, isOneOf, readJsonObject, refusalText } from "./json.js";
10
+ import { bearerRole } from "./jwt.js";
4
11
  const DEBUG_AUTH = (typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1") ||
5
12
  (typeof process !== "undefined" && process.env["SUPATYPE_DEBUG_AUTH"] === "1");
6
- function decodeJwtRoleFromAuthHeader(headers) {
7
- const auth = headers["Authorization"] ?? headers["authorization"];
8
- if (auth === undefined || !auth.startsWith("Bearer "))
9
- return null;
10
- const token = auth.slice("Bearer ".length);
11
- const parts = token.split(".");
12
- if (parts.length !== 3)
13
- return null;
14
- try {
15
- const payloadJson = typeof atob === "function"
16
- ? atob(parts[1] ?? "")
17
- : Buffer.from(parts[1] ?? "", "base64").toString("utf-8");
18
- const payload = JSON.parse(payloadJson);
19
- return typeof payload["role"] === "string" ? payload["role"] : null;
20
- }
21
- catch {
22
- return null;
23
- }
13
+ /**
14
+ * The boundary between a parsed body and the row type the caller declared for the table.
15
+ *
16
+ * PostgREST answers a table read or write with JSON objects, which is what is checked. That each
17
+ * object holds `TRow`'s columns is the generated schema's claim about the database, or the
18
+ * caller's own for `select<TResult>()`, which nothing on the client can check.
19
+ */
20
+ function isCallerRow(value) {
21
+ return isJsonObject(value);
22
+ }
23
+ /** The rows a body holds: an array of objects, or one object (the single-object Accept). */
24
+ function callerRows(value) {
25
+ if (Array.isArray(value))
26
+ return value.every((isCallerRow)) ? value : null;
27
+ return isCallerRow(value) ? [value] : null;
28
+ }
29
+ /** The body was JSON but not rows: PostgREST does not answer a table request that way. */
30
+ function notRows(status) {
31
+ return { message: `Unexpected response body: expected rows (HTTP ${status})`, status };
24
32
  }
25
33
  /**
26
34
  * Parse `X-Supatype-Masked-Fields: salary=row, ssn=identity`.
@@ -43,6 +51,66 @@ export function parseMaskedFields(header) {
43
51
  }
44
52
  return fields.length > 0 ? fields : undefined;
45
53
  }
54
+ /**
55
+ * `.single()` answered without exactly one row, worded as PostgREST 14 words it, so a caller sees
56
+ * the same error whether PostgREST refused the request or the client found the rows wrong.
57
+ */
58
+ function notOneRow() {
59
+ return { message: "Cannot coerce the result to a single JSON object", code: PostgrestErrorCodes.NOT_FOUND };
60
+ }
61
+ /**
62
+ * The error a refused request answered with, for a read and a write alike.
63
+ *
64
+ * One function for both because they drifted: the write path dropped `field`, and a field
65
+ * validator only ever runs on a write, so the column it named never reached the caller.
66
+ */
67
+ function refusal(err, status) {
68
+ return {
69
+ message: refusalText(err) ?? String(err["hint"] ?? "Request failed"),
70
+ status,
71
+ ...(err["code"] !== undefined && { code: String(err["code"]) }),
72
+ // A field validator's refusal names the column it refused. Kept whole rather than folded into
73
+ // the message, so a form can mark the input.
74
+ ...(typeof err["field"] === "string" && { field: err["field"] }),
75
+ ...(typeof err["hint"] === "string" && err["hint"] !== "" && { hint: err["hint"] }),
76
+ ...(typeof err["details"] === "string" && err["details"] !== "" && { details: err["details"] }),
77
+ };
78
+ }
79
+ /** The refusal a failed request answered with, logged with `context` when auth debugging is on. */
80
+ async function readRefusal(res, label, context) {
81
+ const err = await readJsonObject(res, { message: "Error" });
82
+ if (DEBUG_AUTH) {
83
+ console.log(label, {
84
+ ...(await context()),
85
+ status: res.status,
86
+ message: String(err["message"] ?? err["hint"] ?? "Request failed"),
87
+ code: typeof err["code"] === "string" ? err["code"] : null,
88
+ });
89
+ }
90
+ return refusal(err, res.status);
91
+ }
92
+ /**
93
+ * The rows a successful body holds.
94
+ *
95
+ * Read from the text rather than `res.json()`: a bigInt, decimal or money column is already ruined
96
+ * by the time `JSON.parse` returns, and the digits are only recoverable from the body.
97
+ */
98
+ function readRows(body, path, status, count) {
99
+ const parsed = parseRowsExactly(body, tableFromPath(path));
100
+ if (!parsed.ok)
101
+ return { data: null, error: { message: parsed.message, status }, count: null };
102
+ const rows = callerRows(parsed.value);
103
+ if (rows === null)
104
+ return { data: null, error: notRows(status), count: null };
105
+ return { data: rows, error: null, count };
106
+ }
107
+ const isServerCacheStatus = isOneOf(["HIT", "MISS", "BYPASS"]);
108
+ /** What the server said of its cache, else MISS for a cached read, else nothing. */
109
+ function cacheStatusOf(header, cached) {
110
+ if (isServerCacheStatus(header))
111
+ return header;
112
+ return cached ? "MISS" : undefined;
113
+ }
46
114
  function withMeta(result, meta) {
47
115
  const { cacheStatus, maskedFields } = meta;
48
116
  if (cacheStatus === undefined && maskedFields === undefined)
@@ -77,35 +145,47 @@ export function bearerToken(headers) {
77
145
  return authorization.slice("Bearer ".length);
78
146
  return headers["apikey"] ?? headers["Apikey"] ?? "";
79
147
  }
80
- async function fetchWithOptional401Retry(url, init, resolveHeaders, onUnauthorized) {
148
+ /** Send once; on a 401, let the session refresh and send again with freshly resolved headers. */
149
+ export async function fetchWithOptional401Retry(send, url, init, resolveHeaders, onUnauthorized) {
81
150
  let headers = await resolveHeaders();
82
- let res = await fetch(url, { ...init, headers });
151
+ let res = await send(url, { ...init, headers });
83
152
  if (res.status === 401 && onUnauthorized !== undefined) {
84
153
  await onUnauthorized();
85
154
  headers = await resolveHeaders();
86
- res = await fetch(url, { ...init, headers });
155
+ res = await send(url, { ...init, headers });
87
156
  }
88
157
  return res;
89
158
  }
159
+ /**
160
+ * The total from PostgREST's `Content-Range: <range>/<total>`, or null when there is none.
161
+ *
162
+ * PostgREST sends the header on every read, and the total is `*` unless the request asked for a
163
+ * count with `Prefer: count=...`. Reading `*` as a number gave `NaN` on every ordinary query.
164
+ */
165
+ export function parseContentRangeTotal(header) {
166
+ const total = header?.split("/")[1];
167
+ return total !== undefined && /^\d+$/.test(total) ? Number(total) : null;
168
+ }
90
169
  // ─── QueryBuilder ─────────────────────────────────────────────────────────────
91
- export class QueryBuilder {
170
+ export class QueryBuilder extends FilterBuilder {
92
171
  baseUrl;
93
172
  path;
94
173
  getHeaders;
95
174
  onUnauthorized;
175
+ send;
96
176
  extraHeaders;
97
- params;
98
177
  queryCache;
99
178
  cacheOptions;
100
179
  countMode;
101
180
  head;
102
- constructor(baseUrl, path, headers, columns, queryCache = defaultQueryCache, onUnauthorized, selectOptions) {
181
+ constructor(baseUrl, path, headers, columns, queryCache = defaultQueryCache, onUnauthorized, selectOptions, transport = plainFetch) {
182
+ super();
103
183
  this.baseUrl = baseUrl;
104
184
  this.path = path;
105
185
  this.getHeaders = asHeadersProvider(headers);
106
186
  this.onUnauthorized = onUnauthorized;
187
+ this.send = transport;
107
188
  this.extraHeaders = {};
108
- this.params = new URLSearchParams();
109
189
  this.queryCache = queryCache;
110
190
  this.countMode = selectOptions?.count;
111
191
  this.head = selectOptions?.head === true;
@@ -131,67 +211,14 @@ export class QueryBuilder {
131
211
  this.params.set("select", columns);
132
212
  return this;
133
213
  }
134
- eq(column, value) {
135
- this.params.append(column, `eq.${String(value)}`);
136
- return this;
137
- }
138
- neq(column, value) {
139
- this.params.append(column, `neq.${String(value)}`);
140
- return this;
141
- }
142
- gt(column, value) {
143
- this.params.append(column, `gt.${String(value)}`);
144
- return this;
145
- }
146
- gte(column, value) {
147
- this.params.append(column, `gte.${String(value)}`);
148
- return this;
149
- }
150
- lt(column, value) {
151
- this.params.append(column, `lt.${String(value)}`);
152
- return this;
153
- }
154
- lte(column, value) {
155
- this.params.append(column, `lte.${String(value)}`);
156
- return this;
157
- }
158
- like(column, pattern) {
159
- this.params.append(column, `like.${pattern}`);
160
- return this;
161
- }
162
- ilike(column, pattern) {
163
- this.params.append(column, `ilike.${pattern}`);
164
- return this;
165
- }
166
- in(column, values) {
167
- this.params.append(column, `in.(${values.map(String).join(",")})`);
168
- return this;
169
- }
170
- is(column, value) {
171
- this.params.append(column, `is.${String(value)}`);
172
- return this;
173
- }
174
- not(column, op, value) {
175
- this.params.append(column, `not.${op}.${String(value)}`);
176
- return this;
177
- }
178
- contains(column, value) {
179
- this.params.append(column, `cs.${JSON.stringify(value)}`);
180
- return this;
181
- }
182
- containedBy(column, value) {
183
- this.params.append(column, `cd.${JSON.stringify(value)}`);
184
- return this;
185
- }
186
- /** PostgREST OR filter: pass conditions in PostgREST syntax, e.g. `"status.eq.active,owner_id.eq.123"`. */
187
- or(filters) {
188
- this.params.append("or", `(${filters})`);
189
- return this;
190
- }
191
214
  order(column, opts) {
192
215
  const dir = opts?.ascending === false ? "desc" : "asc";
193
216
  const nulls = opts?.nullsFirst === true ? "nullsfirst" : "nullslast";
194
- this.params.append("order", `${column}.${dir}.${nulls}`);
217
+ // One parameter, comma-separated: PostgREST reads only the first `order`, so appending a second
218
+ // dropped every column after the first without an error.
219
+ const term = `${column}.${dir}.${nulls}`;
220
+ const prior = this.params.get("order");
221
+ this.params.set("order", prior === null ? term : `${prior},${term}`);
195
222
  return this;
196
223
  }
197
224
  limit(count) {
@@ -215,12 +242,13 @@ export class QueryBuilder {
215
242
  });
216
243
  if (error !== null)
217
244
  return { data: null, error, count: null, ...(meta && { meta }) };
218
- // Some proxies drop Accept and return a one-element array, unwrap.
219
- const row = (Array.isArray(data) ? data[0] : data);
245
+ // The single-object body and a one-element array (from a proxy that dropped Accept) both
246
+ // arrive here as rows: `callerRows` reads either.
247
+ const row = data === null ? null : data[0];
220
248
  if (row === undefined) {
221
249
  return {
222
250
  data: null,
223
- error: { message: "JSON object requested, multiple (or no) rows returned", code: "PGRST116" },
251
+ error: notOneRow(),
224
252
  count: null,
225
253
  ...(meta && { meta }),
226
254
  };
@@ -232,8 +260,7 @@ export class QueryBuilder {
232
260
  const { data, error, count, meta } = await this._fetch({});
233
261
  if (error !== null)
234
262
  return { data: null, error, count: null, ...(meta && { meta }) };
235
- const rows = data;
236
- const row = rows.length > 0 ? (rows[0] ?? null) : null;
263
+ const row = data?.[0] ?? null;
237
264
  return { data: row, error: null, count, ...(meta && { meta }) };
238
265
  }
239
266
  then(onfulfilled, onrejected) {
@@ -267,129 +294,101 @@ export class QueryBuilder {
267
294
  const mergedExtra = this.mergePreferHeader(this.extraHeaders, fetchHeaders);
268
295
  const url = this.buildRequestUrl();
269
296
  const method = this.head ? "HEAD" : "GET";
270
- const resolveRequestHeaders = async () => {
271
- const authHeaders = await this.getHeaders();
272
- return this.applyServerCacheHeader({ ...authHeaders, ...mergedExtra });
273
- };
274
- if (this.cacheOptions && !this.head) {
275
- const requestHeaders = await resolveRequestHeaders();
276
- const cacheKey = buildCacheKey("GET", url, requestHeaders, {
277
- partition: this.cacheOptions.key,
278
- public: this.cacheOptions.public,
279
- });
280
- const cached = this.queryCache.get(cacheKey);
281
- if (cached) {
282
- return withMeta(cached, { cacheStatus: "HIT" });
283
- }
284
- }
297
+ const resolveRequestHeaders = async () => this.applyServerCacheHeader({ ...(await this.getHeaders()), ...mergedExtra });
298
+ const cached = await this.cachedResult(url, resolveRequestHeaders);
299
+ if (cached)
300
+ return withMeta(cached, { cacheStatus: "HIT" });
285
301
  let res;
286
302
  try {
287
- res = await fetchWithOptional401Retry(url, { method }, resolveRequestHeaders, this.onUnauthorized);
303
+ res = await fetchWithOptional401Retry(this.send, url, { method }, resolveRequestHeaders, this.onUnauthorized);
288
304
  }
289
305
  catch (e) {
290
- return {
291
- data: null,
292
- error: { message: e instanceof Error ? e.message : "Network error" },
293
- count: null,
294
- };
306
+ return { data: null, error: transportFailure(e), count: null };
295
307
  }
296
- const contentRange = res.headers.get("content-range");
297
- const count = contentRange !== null
298
- ? parseInt(contentRange.split("/")[1] ?? "0", 10)
299
- : null;
300
- const maskedFields = parseMaskedFields(res.headers.get("X-Supatype-Masked-Fields"));
301
- const serverCacheStatus = res.headers.get("X-Supatype-Cache-Status");
302
- const cacheStatus = serverCacheStatus === "HIT" || serverCacheStatus === "MISS" || serverCacheStatus === "BYPASS"
303
- ? serverCacheStatus
304
- : this.cacheOptions
305
- ? "MISS"
306
- : undefined;
308
+ const result = await this.readResult(res, method, url, resolveRequestHeaders);
309
+ await this.remember(url, resolveRequestHeaders, result);
310
+ return withMeta(result, {
311
+ cacheStatus: cacheStatusOf(res.headers.get("X-Supatype-Cache-Status"), this.cacheOptions !== undefined),
312
+ maskedFields: parseMaskedFields(res.headers.get("X-Supatype-Masked-Fields")),
313
+ });
314
+ }
315
+ /** The cached result for this read, when it is cached and the cache holds one. */
316
+ async cachedResult(url, resolveRequestHeaders) {
317
+ if (!this.cacheOptions || this.head)
318
+ return null;
319
+ return this.queryCache.get(await this.cacheKey(url, this.cacheOptions, resolveRequestHeaders));
320
+ }
321
+ /** Cache a read's rows, when this read is cached and it returned rows. */
322
+ async remember(url, resolveRequestHeaders, result) {
323
+ if (!this.cacheOptions || result.error !== null || result.data === null)
324
+ return;
325
+ const key = await this.cacheKey(url, this.cacheOptions, resolveRequestHeaders);
326
+ this.queryCache.set(key, result, this.cacheOptions.ttl);
327
+ }
328
+ /** What the response says: a refusal, no body (HEAD or 204), or the rows. */
329
+ async readResult(res, method, url, resolveRequestHeaders) {
307
330
  if (!res.ok) {
308
- const err = await res.json().catch(() => ({ message: "Error" }));
309
- const debugHeaders = await resolveRequestHeaders();
310
- if (DEBUG_AUTH) {
311
- console.log("[supatype:query] request failed", {
312
- url,
313
- status: res.status,
314
- role: decodeJwtRoleFromAuthHeader(debugHeaders),
315
- message: String(err["message"] ?? err["hint"] ?? "Request failed"),
316
- code: typeof err["code"] === "string" ? err["code"] : null,
317
- });
318
- }
319
- return withMeta({
320
- data: null,
321
- error: {
322
- message: String(err["message"] ?? err["hint"] ?? "Request failed"),
323
- status: res.status,
324
- ...(err["code"] !== undefined && { code: String(err["code"]) }),
325
- // A field validator's refusal names the column it refused. Kept whole rather than
326
- // folded into the message, so a form can mark the input.
327
- ...(typeof err["field"] === "string" && { field: err["field"] }),
328
- },
329
- count: null,
330
- }, { cacheStatus, maskedFields });
331
- }
332
- if (method === "HEAD" || res.status === 204) {
333
- return withMeta({ data: null, error: null, count }, { cacheStatus, maskedFields });
334
- }
335
- // Read from the text rather than `res.json()`: a bigInt, decimal or money column is already
336
- // ruined by the time `JSON.parse` returns, and the digits are only recoverable from the body.
337
- const parsed = parseRowsExactly(await res.text(), tableFromPath(this.path));
338
- if (!parsed.ok) {
339
- return withMeta({ data: null, error: { message: parsed.message, status: res.status }, count: null }, { cacheStatus, maskedFields });
331
+ const error = await readRefusal(res, "[supatype:query] request failed", async () => ({
332
+ url,
333
+ role: bearerRole(await resolveRequestHeaders()),
334
+ }));
335
+ return { data: null, error, count: null };
340
336
  }
341
- const result = { data: parsed.value, error: null, count };
342
- if (this.cacheOptions) {
343
- const cacheKey = buildCacheKey("GET", url, await resolveRequestHeaders(), {
344
- partition: this.cacheOptions.key,
345
- public: this.cacheOptions.public,
346
- });
347
- this.queryCache.set(cacheKey, result, this.cacheOptions.ttl);
348
- }
349
- return withMeta(result, { cacheStatus, maskedFields });
337
+ const count = parseContentRangeTotal(res.headers.get("content-range"));
338
+ if (method === "HEAD" || res.status === 204)
339
+ return { data: null, error: null, count };
340
+ return readRows(await res.text(), this.path, res.status, count);
341
+ }
342
+ async cacheKey(url, options, resolveRequestHeaders) {
343
+ return buildCacheKey("GET", url, await resolveRequestHeaders(), {
344
+ partition: options.key,
345
+ public: options.public,
346
+ });
350
347
  }
351
348
  }
352
- export class MutationBuilder {
349
+ export class MutationBuilder extends FilterBuilder {
353
350
  baseUrl;
354
351
  path;
355
352
  getHeaders;
356
353
  onUnauthorized;
354
+ send;
357
355
  extraHeaders;
358
356
  method;
359
357
  body;
360
- params;
361
- constructor(baseUrl, path, headers, method, body, opts, onUnauthorized) {
358
+ createThrough;
359
+ editThrough;
360
+ refusal;
361
+ constructor(baseUrl, path, headers, method, body, opts, onUnauthorized, transport = plainFetch) {
362
+ super();
362
363
  this.baseUrl = baseUrl;
363
364
  this.path = path;
364
365
  this.getHeaders = asHeadersProvider(headers);
365
366
  this.onUnauthorized = onUnauthorized;
367
+ this.send = transport;
366
368
  this.extraHeaders = {};
367
369
  this.method = method;
368
370
  this.body = body;
369
- this.params = new URLSearchParams();
370
- if (opts?.upsert === true) {
371
- this.extraHeaders["Prefer"] = "resolution=merge-duplicates";
372
- }
371
+ this.createThrough = opts?.createThrough;
372
+ this.editThrough = opts?.editThrough;
373
+ this.refusal = opts?.refusal;
374
+ if (opts?.upsert === true)
375
+ this.prefer("resolution=merge-duplicates");
373
376
  // Return inserted/updated rows
374
- if (method !== "DELETE") {
375
- this.extraHeaders["Prefer"] = (this.extraHeaders["Prefer"] ?? "") + ",return=representation";
376
- }
377
- }
378
- eq(column, value) {
379
- this.params.append(column, `eq.${String(value)}`);
380
- return this;
381
- }
382
- neq(column, value) {
383
- this.params.append(column, `neq.${String(value)}`);
384
- return this;
385
- }
386
- in(column, values) {
387
- this.params.append(column, `in.(${values.map(String).join(",")})`);
388
- return this;
389
- }
390
- /** Limit returned columns on the mutation response (requires `return=representation`). */
377
+ if (method !== "DELETE")
378
+ this.prefer("return=representation");
379
+ }
380
+ prefer(preference) {
381
+ const current = this.extraHeaders["Prefer"];
382
+ if (current?.split(",").includes(preference) === true)
383
+ return;
384
+ this.extraHeaders["Prefer"] = current === undefined ? preference : `${current},${preference}`;
385
+ }
386
+ // The same request, now described as returning the selected shape rather than the whole row. The
387
+ // overloads above say which shape; the row type is the caller's claim, checked by nothing at
388
+ // runtime, so the builder itself is returned rather than a copy that would split the request.
391
389
  select(columns) {
392
390
  this.params.set("select", columns ?? "*");
391
+ this.prefer("return=representation");
393
392
  return this;
394
393
  }
395
394
  async single() {
@@ -398,11 +397,11 @@ export class MutationBuilder {
398
397
  });
399
398
  if (error !== null)
400
399
  return { data: null, error, count: null, ...(meta && { meta }) };
401
- const row = data !== null && data.length > 0 ? data[0] : null;
400
+ const row = data?.[0] ?? null;
402
401
  if (row === null) {
403
402
  return {
404
403
  data: null,
405
- error: { message: "JSON object requested, multiple (or no) rows returned" },
404
+ error: notOneRow(),
406
405
  count: null,
407
406
  ...(meta && { meta }),
408
407
  };
@@ -419,7 +418,22 @@ export class MutationBuilder {
419
418
  then(onfulfilled, onrejected) {
420
419
  return this._execute().then(onfulfilled, onrejected);
421
420
  }
421
+ /** POST, PATCH and DELETE: the transport applies the timeout and never retries them. */
422
+ requestInit() {
423
+ return {
424
+ method: this.method,
425
+ // Not `JSON.stringify`: it throws on a bigint, so reading a row with a bigInt column and
426
+ // writing it back would fail now that the generated types declare one.
427
+ ...(this.body !== undefined && { body: stringifyWithBigInts(this.body) }),
428
+ };
429
+ }
422
430
  async _execute(fetchHeaders = {}) {
431
+ if (this.refusal !== undefined)
432
+ return { data: null, error: this.refusal, count: null };
433
+ if (this.createThrough !== undefined)
434
+ return this.createDraftRecords(this.createThrough);
435
+ if (this.editThrough !== undefined)
436
+ return this.saveDraftRecords(this.editThrough);
423
437
  const qs = this.params.toString();
424
438
  const url = `${this.baseUrl}${this.path}${qs ? `?${qs}` : ""}`;
425
439
  const resolveRequestHeaders = async () => ({
@@ -427,55 +441,111 @@ export class MutationBuilder {
427
441
  ...this.extraHeaders,
428
442
  ...fetchHeaders,
429
443
  });
430
- const init = {
431
- method: this.method,
432
- // Not `JSON.stringify`: it throws on a bigint, so reading a row with a bigInt column and
433
- // writing it back would fail now that the generated types declare one.
434
- ...(this.body !== undefined && { body: stringifyWithBigInts(this.body) }),
435
- };
436
444
  let res;
437
445
  try {
438
- res = await fetchWithOptional401Retry(url, init, resolveRequestHeaders, this.onUnauthorized);
446
+ res = await fetchWithOptional401Retry(this.send, url, this.requestInit(), resolveRequestHeaders, this.onUnauthorized);
439
447
  }
440
448
  catch (e) {
441
- return {
442
- data: null,
443
- error: { message: e instanceof Error ? e.message : "Network error" },
444
- count: null,
445
- };
449
+ return { data: null, error: transportFailure(e), count: null };
446
450
  }
447
451
  if (!res.ok) {
448
- const err = await res.json().catch(() => ({ message: "Error" }));
449
- if (DEBUG_AUTH) {
450
- console.log("[supatype:mutation] request failed", {
451
- url,
452
- method: this.method,
453
- status: res.status,
454
- role: decodeJwtRoleFromAuthHeader(await resolveRequestHeaders()),
455
- message: String(err["message"] ?? err["hint"] ?? "Request failed"),
456
- code: typeof err["code"] === "string" ? err["code"] : null,
457
- });
458
- }
459
- return {
460
- data: null,
461
- error: {
462
- message: String(err["message"] ?? err["hint"] ?? "Request failed"),
463
- status: res.status,
464
- ...(err["code"] !== undefined && { code: String(err["code"]) }),
465
- },
466
- count: null,
467
- };
452
+ const error = await readRefusal(res, "[supatype:mutation] request failed", async () => ({
453
+ url,
454
+ method: this.method,
455
+ role: bearerRole(await resolveRequestHeaders()),
456
+ }));
457
+ return { data: null, error, count: null };
468
458
  }
469
459
  if (res.status === 204) {
470
460
  return { data: [], error: null, count: 0 };
471
461
  }
472
462
  // The returned representation of what was just written, so it needs the same care as a read.
473
- const parsed = parseRowsExactly(await res.text(), tableFromPath(this.path));
474
- if (!parsed.ok) {
475
- return { data: null, error: { message: parsed.message, status: res.status }, count: null };
463
+ const result = readRows(await res.text(), this.path, res.status, null);
464
+ return result.data === null ? result : { ...result, count: result.data.length };
465
+ }
466
+ /**
467
+ * Create the records as their first drafts, then read them back as an insert returns them.
468
+ *
469
+ * Read from the draft view, which has the table's row type: the live row of a new record holds no
470
+ * locale yet, so reading the table would hand back empty translations for what was just written.
471
+ * The select string applies as it would to the insert's own answer, and several rows come back in
472
+ * the order they were sent.
473
+ */
474
+ async createDraftRecords(target) {
475
+ const { fn, data } = createCall(this.body);
476
+ const keys = await this.callPublishing(fn, { model_table: target.table, data });
477
+ if (!Array.isArray(keys))
478
+ return { data: null, error: keys, count: null };
479
+ return this.readDrafts(target, keys);
480
+ }
481
+ /**
482
+ * Save a draft of each record the filters match, publishing it too when asked, then read the
483
+ * drafts back as an update returns its rows. The live rows are left to publishing.
484
+ *
485
+ * The records are the ones the caller reads in the table under the update's filters, as a `PATCH`
486
+ * would match them, and `save_drafts` saves all of them or none.
487
+ */
488
+ async saveDraftRecords(target) {
489
+ const matched = await this.matchedKeys(target.primaryKey);
490
+ if (!Array.isArray(matched))
491
+ return { data: null, error: matched, count: null };
492
+ // A `PATCH` that matches nothing answers no rows, and so does this, having saved nothing.
493
+ if (matched.length === 0)
494
+ return { data: [], error: null, count: 0 };
495
+ const body = { model_table: target.table, record_ids: matched, data: this.body, publish: target.publish };
496
+ const keys = await this.callPublishing("save_drafts", body);
497
+ if (!Array.isArray(keys))
498
+ return { data: null, error: keys, count: null };
499
+ return this.readDrafts(target, keys);
500
+ }
501
+ /** The keys of the rows this write's filters match, read from the table as the caller. */
502
+ async matchedKeys(primaryKey) {
503
+ const params = new URLSearchParams(this.params);
504
+ params.set("select", primaryKey);
505
+ const url = `${this.baseUrl}${this.path}?${params.toString()}`;
506
+ let res;
507
+ try {
508
+ res = await fetchWithOptional401Retry(this.send, url, { method: "GET" }, this.getHeaders, this.onUnauthorized);
509
+ }
510
+ catch (e) {
511
+ return transportFailure(e);
512
+ }
513
+ if (!res.ok)
514
+ return readRefusal(res, "[supatype:mutation] reading the records to draft failed", async () => ({ url }));
515
+ const rows = readRows(await res.text(), this.path, res.status, null);
516
+ if (rows.data === null)
517
+ return rows.error ?? notRows(res.status);
518
+ return rows.data.map((row) => String(row[primaryKey]));
519
+ }
520
+ /** `keys`' newest drafts, from the draft view, with this write's select and in the order given. */
521
+ async readDrafts(target, keys) {
522
+ const select = readBackColumns(this.params.get("select"), target.primaryKey, keys.length);
523
+ const result = await new QueryBuilder(this.baseUrl, this.path, this.getHeaders, select, defaultQueryCache, this.onUnauthorized, { profile: DRAFT_SCHEMA }, this.send).in(target.primaryKey, keys);
524
+ if (result.data === null)
525
+ return { ...result, data: null };
526
+ const rows = callerRows(inCreatedOrder(result.data, keys)) ?? [];
527
+ return { ...result, data: rows, count: rows.length };
528
+ }
529
+ /** Call the publishing function `fn` with `body`: the record keys it answers with, in order, or why not. */
530
+ async callPublishing(fn, body) {
531
+ const url = `${this.baseUrl}/rest/v1/rpc/${fn}`;
532
+ const init = { method: "POST", body: stringifyWithBigInts(body) };
533
+ const resolveRequestHeaders = async () => ({
534
+ ...(await this.getHeaders()),
535
+ "Content-Profile": PUBLISHING_SCHEMA,
536
+ });
537
+ let res;
538
+ try {
539
+ res = await fetchWithOptional401Retry(this.send, url, init, resolveRequestHeaders, this.onUnauthorized);
540
+ }
541
+ catch (e) {
542
+ return transportFailure(e);
476
543
  }
477
- const data = Array.isArray(parsed.value) ? parsed.value : [parsed.value];
478
- return { data, error: null, count: data.length };
544
+ const table = body["model_table"];
545
+ if (!res.ok)
546
+ return readRefusal(res, `[supatype:mutation] ${fn} failed`, async () => ({ url, table }));
547
+ const answer = await res.json().catch(() => null);
548
+ return createdKeys(answer) ?? { message: `${fn} answered without the record ids`, status: res.status };
479
549
  }
480
550
  }
481
551
  export { QueryCache, defaultQueryCache } from "./query-cache.js";