@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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json.d.ts","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,oDAAoD;AACpD,MAAM,MAAM,KAAK,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,KAAK,KAAK,IAAI,CAAC,CAAA;AAErD,sDAAsD;AACtD,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAE7E;AAED,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAExD;AAED,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CA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G;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,GAAG,SAAS,CAM7E"}
package/dist/json.js ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Reading JSON from outside the client: a response body, a socket frame, a stored session.
3
+ *
4
+ * `res.json()` and `JSON.parse` return `unknown` here (see ts-reset.d.ts at the repository root), and
5
+ * a cast cannot turn that into a type (`no-unsafe-type-assertion`). A value is narrowed by a guard
6
+ * instead: the small ones below, composed with `isShape` and `isArrayOf` for a body's shape.
7
+ *
8
+ * Modelled on packages/studio/src/lib/json.ts. Internal: not exported from the package index, so
9
+ * nothing here is part of the client's public API.
10
+ */
11
+ /** True for a JSON object: not null, not an array. */
12
+ export function isJsonObject(value) {
13
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14
+ }
15
+ export function isString(value) {
16
+ return typeof value === "string";
17
+ }
18
+ export function isNumber(value) {
19
+ return typeof value === "number";
20
+ }
21
+ export function isBoolean(value) {
22
+ return typeof value === "boolean";
23
+ }
24
+ /** An array whose every item the guard accepts. */
25
+ export function isArrayOf(item) {
26
+ return (value) => Array.isArray(value) && value.every(item);
27
+ }
28
+ /** An object whose every value the guard accepts. */
29
+ export function isRecordOf(item) {
30
+ return (value) => isJsonObject(value) && Object.values(value).every(item);
31
+ }
32
+ /** The guard's type, or null. */
33
+ export function nullable(guard) {
34
+ return (value) => value === null || guard(value);
35
+ }
36
+ /** One of the listed values, by identity. */
37
+ export function isOneOf(values) {
38
+ return (value) => values.some((allowed) => allowed === value);
39
+ }
40
+ export function optional(guard) {
41
+ return { optional: guard };
42
+ }
43
+ function fieldAccepts(field, value) {
44
+ if (typeof field === "function")
45
+ return field(value);
46
+ return value === undefined || field.optional(value);
47
+ }
48
+ /** A JSON object whose named keys each pass their guard. Keys not named are allowed and not typed. */
49
+ export function isShape(shape) {
50
+ return (value) => isJsonObject(value) && Object.entries(shape).every(([key, field]) => fieldAccepts(field, value[key]));
51
+ }
52
+ /** A response's JSON body when the guard accepts it; throws, naming the request, when it does not. */
53
+ export async function readJson(res, guard) {
54
+ const body = await res.json();
55
+ if (!guard(body))
56
+ throw new Error(`Unexpected response from ${res.url || "the server"} (HTTP ${res.status})`);
57
+ return body;
58
+ }
59
+ /**
60
+ * A response's body as an object, or `fallback` when it is not JSON or not an object. For error
61
+ * bodies, which a proxy or a crashed upstream may send as HTML, plain text or nothing at all.
62
+ */
63
+ export async function readJsonObject(res, fallback = {}) {
64
+ const body = await res.json().catch(() => null);
65
+ return isJsonObject(body) ? body : fallback;
66
+ }
67
+ /** The value when it is a JSON object, else an empty one: for a nested object a body may omit. */
68
+ export function objectOrEmpty(value) {
69
+ return isJsonObject(value) ? value : {};
70
+ }
71
+ /**
72
+ * A refusal body's sentence: PostgREST's `message`, or the `error` (or `msg`) that the Studio proxy,
73
+ * the server's guards and the auth server answer with. Undefined when the body carries none.
74
+ */
75
+ export function refusalText(body) {
76
+ for (const key of ["message", "error", "msg"]) {
77
+ const value = body[key];
78
+ if (typeof value === "string" && value !== "")
79
+ return value;
80
+ }
81
+ return undefined;
82
+ }
83
+ //# sourceMappingURL=json.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json.js","sourceRoot":"","sources":["../src/json.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAKH,sDAAsD;AACtD,MAAM,UAAU,YAAY,CAAC,KAAc;IACzC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;AAC7E,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,KAAc;IACrC,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAA;AAClC,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,KAAc;IACrC,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAA;AAClC,CAAC;AAED,MAAM,UAAU,SAAS,CAAC,KAAc;IACtC,OAA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AA;IAC7D,CAAC;IACD,OAAO,SAAS,CAAA;AAClB,CAAC"}
package/dist/jwt.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The claims in a JWT's payload segment, read without verifying the signature: for `exp`, `role`,
3
+ * `sub` and `aal` on the client's own token. Null when the segment is not base64url-encoded JSON of
4
+ * an object.
5
+ *
6
+ * One decoder for the five places that read a claim. A JWT's segments are base64url, and four of the
7
+ * five passed the segment straight to `atob`, which takes only the standard alphabet: a payload
8
+ * whose encoding contains `-` or `_` (one carrying `>`, `?` or `~`, or any non-ASCII text such as an
9
+ * accented name in the user's metadata) threw, and the claim read as absent.
10
+ */
11
+ export declare function decodeJwtPayload(segment: string): Record<string, unknown> | null;
12
+ /** The `role` claim of a JWT, or null when the token is not one or names no role. */
13
+ export declare function jwtRole(token: string): string | null;
14
+ /** The role of the bearer token in `headers`, whichever case the header is named in, or null. */
15
+ export declare function bearerRole(headers: Record<string, string>): string | null;
16
+ //# sourceMappingURL=jwt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwt.d.ts","sourceRoot":"","sources":["../src/jwt.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAUhF;AAED,qFAAqF;AACrF,wBAAgB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAKpD;AAED,iGAAiG;AACjG,wBAAgB,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,GAAG,IAAI,CAGzE"}
package/dist/jwt.js ADDED
@@ -0,0 +1,37 @@
1
+ import { isJsonObject } from "./json.js";
2
+ /**
3
+ * The claims in a JWT's payload segment, read without verifying the signature: for `exp`, `role`,
4
+ * `sub` and `aal` on the client's own token. Null when the segment is not base64url-encoded JSON of
5
+ * an object.
6
+ *
7
+ * One decoder for the five places that read a claim. A JWT's segments are base64url, and four of the
8
+ * five passed the segment straight to `atob`, which takes only the standard alphabet: a payload
9
+ * whose encoding contains `-` or `_` (one carrying `>`, `?` or `~`, or any non-ASCII text such as an
10
+ * accented name in the user's metadata) threw, and the claim read as absent.
11
+ */
12
+ export function decodeJwtPayload(segment) {
13
+ try {
14
+ const padded = segment + "=".repeat((4 - (segment.length % 4)) % 4);
15
+ const b64 = padded.replace(/-/g, "+").replace(/_/g, "/");
16
+ const json = typeof atob === "function" ? atob(b64) : Buffer.from(b64, "base64").toString("utf8");
17
+ const claims = JSON.parse(json);
18
+ return isJsonObject(claims) ? claims : null;
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ }
24
+ /** The `role` claim of a JWT, or null when the token is not one or names no role. */
25
+ export function jwtRole(token) {
26
+ const parts = token.split(".");
27
+ if (parts.length !== 3)
28
+ return null;
29
+ const role = decodeJwtPayload(parts[1] ?? "")?.["role"];
30
+ return typeof role === "string" ? role : null;
31
+ }
32
+ /** The role of the bearer token in `headers`, whichever case the header is named in, or null. */
33
+ export function bearerRole(headers) {
34
+ const auth = headers["Authorization"] ?? headers["authorization"];
35
+ return auth?.startsWith("Bearer ") === true ? jwtRole(auth.slice("Bearer ".length)) : null;
36
+ }
37
+ //# sourceMappingURL=jwt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwt.js","sourceRoot":"","sources":["../src/jwt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA;AAExC;;;;;;;;;GASG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAe;IAC9C,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,OAAO,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAA;QACnE,MAAM,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC,IA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1,23 @@
1
+ /**
2
+ * The live preview protocol: what Studio posts to a framed preview page on every keystroke, and how
3
+ * a binding reads it back. One copy, so the sender and the receivers cannot drift apart without
4
+ * either side noticing.
5
+ */
6
+ declare const LIVE_PREVIEW_MESSAGE = "supatype:live-preview";
7
+ /** What Studio posts: the model being edited and its unsaved form values. */
8
+ export interface LivePreviewMessage {
9
+ type: typeof LIVE_PREVIEW_MESSAGE;
10
+ model: string;
11
+ data: Record<string, unknown>;
12
+ }
13
+ /** The message Studio posts for `model`'s unsaved `data`. */
14
+ export declare function livePreviewMessage(model: string, data: Record<string, unknown>): LivePreviewMessage;
15
+ /** The model and data a received message carries, when it is a live preview message at all. */
16
+ export declare function previewMessageOf(value: unknown): {
17
+ model: unknown;
18
+ data: unknown;
19
+ } | null;
20
+ /** The origin `url` loads from, resolved against `base` when given; null when it names none. */
21
+ export declare function originOf(url: string, base?: string): string | null;
22
+ export {};
23
+ //# sourceMappingURL=live-preview.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live-preview.d.ts","sourceRoot":"","sources":["../src/live-preview.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AAEH,QAAA,MAAM,oBAAoB,0BAA0B,CAAA;AAEpD,6EAA6E;AAC7E,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,OAAO,oBAAoB,CAAA;IACjC,KAAK,EAAE,MAAM,CAAA;IACb,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAC9B;AAED,6DAA6D;AAC7D,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,kBAAkB,CAEnG;AAED,+FAA+F;AAC/F,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,OAAO,CAAA;CAAE,GAAG,IAAI,CAGzF;AAED,gGAAgG;AAChG,wBAAgB,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAOlE"}
@@ -0,0 +1,28 @@
1
+ import { isJsonObject } from "./json.js";
2
+ /**
3
+ * The live preview protocol: what Studio posts to a framed preview page on every keystroke, and how
4
+ * a binding reads it back. One copy, so the sender and the receivers cannot drift apart without
5
+ * either side noticing.
6
+ */
7
+ const LIVE_PREVIEW_MESSAGE = "supatype:live-preview";
8
+ /** The message Studio posts for `model`'s unsaved `data`. */
9
+ export function livePreviewMessage(model, data) {
10
+ return { type: LIVE_PREVIEW_MESSAGE, model, data };
11
+ }
12
+ /** The model and data a received message carries, when it is a live preview message at all. */
13
+ export function previewMessageOf(value) {
14
+ if (!isJsonObject(value) || value["type"] !== LIVE_PREVIEW_MESSAGE)
15
+ return null;
16
+ return { model: value["model"], data: value["data"] };
17
+ }
18
+ /** The origin `url` loads from, resolved against `base` when given; null when it names none. */
19
+ export function originOf(url, base) {
20
+ try {
21
+ const { origin } = new URL(url, base);
22
+ return origin === "null" ? null : origin;
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ //# sourceMappingURL=live-preview.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live-preview.js","sourceRoot":"","sources":["../src/live-preview.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA;AAExC;;;;GAIG;AAEH,MAAM,oBAAoB,GAAG,uBAAuB,CAAA;AASpD,6DAA6D;AAC7D,MAAM,UAAU,kBAAkB,CAAC,KAAa,EAAE,IAA6B;IAC7E,OAAO,EAAE,IAAI,EAAE,oBAAoB,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;AACpD,CAAC;AAED,+FAA+F;AAC/F,MAAM,UAAU,gBAAgB,CAAC,KAAc;IAC7C,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,oBAAoB;QAAE,OAAO,IAAI,CAAA;IAC/E,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,CAAA;AACvD,CAAC;AAED,gGAAgG;AAChG,MAAM,UAAU,QAAQ,CAAC,GAAW,EAAE,IAAa;IACjD,IAAI,CAAC;QACH,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;QACrC,OAAO,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAA;IAC1C,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAA;IACb,CAAC;AACH,CAAC"}
@@ -0,0 +1,17 @@
1
+ import type { AnyClient } from "./index.js";
2
+ import type { DraftUpdateOptions, SupatypeError } from "./types.js";
3
+ export type MutationOperation = "insert" | "update" | "delete" | "upsert";
4
+ export type MutationRows = Record<string, unknown> | Record<string, unknown>[];
5
+ export interface MutationOutcome<TRow> {
6
+ data: TRow[] | null;
7
+ error: SupatypeError | null;
8
+ count: number | null;
9
+ }
10
+ /**
11
+ * Run one mutation against `table`, with the rows that come back as the caller's row type.
12
+ *
13
+ * `options` is an update's: on a model that keeps drafts, `{ publish: true }` publishes the drafts
14
+ * it saves in the same call.
15
+ */
16
+ export declare function runMutation<TRow>(client: AnyClient, table: string, operation: MutationOperation, data: MutationRows | undefined, filter?: Record<string, unknown>, options?: DraftUpdateOptions): Promise<MutationOutcome<TRow>>;
17
+ //# sourceMappingURL=mutation-request.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mutation-request.d.ts","sourceRoot":"","sources":["../src/mutation-request.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAE3C,OAAO,KAAK,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAGnE,MAAM,MAAM,iBAAiB,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,GAAG,QAAQ,CAAA;AAEzE,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;AAE9E,MAAM,WAAW,eAAe,CAAC,IAAI;IACnC,IAAI,EAAE,IAAI,EAAE,GAAG,IAAI,CAAA;IACnB,KAAK,EAAE,aAAa,GAAG,IAAI,CAAA;IAC3B,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;CACrB;AAkCD;;;;;GAKG;AACH,wBAAsB,WAAW,CAAC,IAAI,EACpC,MAAM,EAAE,SAAS,EACjB,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,iBAAiB,EAC5B,IAAI,EAAE,YAAY,GAAG,SAAS,EAC9B,MAAM,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,EACpC,OAAO,GAAE,kBAAuB,GAC/B,OAAO,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAKhC"}
@@ -0,0 +1,41 @@
1
+ import { isRowsOf } from "./caller-types.js";
2
+ function withFilter(pending, filter) {
3
+ let filtered = pending;
4
+ for (const [col, val] of Object.entries(filter))
5
+ filtered = filtered.eq(col, val);
6
+ return filtered;
7
+ }
8
+ /**
9
+ * The request `operation` makes, or why it cannot make one: an insert or upsert with nothing to
10
+ * write, or an update that is not one object of changes, used to go out and come back as the
11
+ * server's error.
12
+ *
13
+ * Through the untyped client: the generated Insert and Update types do not survive a table name
14
+ * known only at run time, so `data` goes out as the caller wrote it and PostgREST is what checks it.
15
+ */
16
+ function mutationRequest(tableClient, operation, data, filter, options) {
17
+ if (operation === "delete")
18
+ return withFilter(tableClient.delete(), filter);
19
+ if (operation === "update") {
20
+ if (data === undefined || Array.isArray(data))
21
+ return "update needs one object of the changes to make";
22
+ return withFilter(tableClient.update(data, options), filter);
23
+ }
24
+ if (data === undefined)
25
+ return `${operation} needs the row or rows to write`;
26
+ return operation === "insert" ? tableClient.insert(data) : tableClient.upsert(data);
27
+ }
28
+ /**
29
+ * Run one mutation against `table`, with the rows that come back as the caller's row type.
30
+ *
31
+ * `options` is an update's: on a model that keeps drafts, `{ publish: true }` publishes the drafts
32
+ * it saves in the same call.
33
+ */
34
+ export async function runMutation(client, table, operation, data, filter = {}, options = {}) {
35
+ const pending = mutationRequest(client.from(table), operation, data, filter, options);
36
+ if (typeof pending === "string")
37
+ return { data: null, error: { message: pending }, count: null };
38
+ const result = await pending;
39
+ return { data: isRowsOf(result.data) ? result.data : null, error: result.error, count: result.count };
40
+ }
41
+ //# sourceMappingURL=mutation-request.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mutation-request.js","sourceRoot":"","sources":["../src/mutation-request.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAc5C,SAAS,UAAU,CAAC,OAAwB,EAAE,MAA+B;IAC3E,IAAI,QAAQ,GAAG,OAAO,CAAA;IACtB,KAAK,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;QAAE,QAAQ,GAAG,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;IACjF,OAAO,QAAQ,CAAA;AACjB,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,eAAe,CACtB,WAA0C,EAC1C,SAA4B,EAC5B,IAA8B,EAC9B,MAA+B,EAC/B,OAA2B;IAE3B,IAAI,SAAS,KAAK,QAAQ;QAAE,OAAO,UAAU,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,MAAM,CAAC,CAAA;IAC3E,IAAI,SAAS,KAAK,QAAQ,EAAE,CAAC;QAC3B,IAAI,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;YAAE,OAAO,gDAAgD,CAAA;QACtG,OAAO,UAAU,CAAC,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AACH,qBAAa,iBAAiB;;gBAOhB,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM;IAKzC,4EAA4E;IACtE,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC;CAqC/B"}
1
+ {"version":3,"file":"preview.d.ts","sourceRoot":"","sources":["../src/preview.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAOH;;;;;;;GAOG;AACH,qBAAa,gBAAiB,SAAQ,KAAK;gBAC7B,OAAO,SAA0E;CAI9F;AAED;;;;;GAKG;AACH,qBAAa,iBAAiB;;gBAOhB,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM;IAKzC,4EAA4E;IACtE,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC;CAsC/B"}
package/dist/preview.js CHANGED
@@ -19,7 +19,8 @@
19
19
  * shared, and a second caller arriving mid-flight waits on the same promise rather than starting
20
20
  * its own.
21
21
  */
22
- /** Seconds of slack before expiry at which the token is treated as spent. */
22
+ import { readJsonObject } from "./json.js";
23
+ /** Milliseconds of slack before expiry at which the token is treated as spent. */
23
24
  const REFRESH_SKEW_MS = 5_000;
24
25
  /**
25
26
  * Thrown when a code will not resolve, for any reason.
@@ -78,15 +79,16 @@ export class PreviewCredential {
78
79
  }
79
80
  if (!response.ok)
80
81
  throw new PreviewLinkError();
81
- const body = (await response.json().catch(() => ({})));
82
- if (typeof body.token !== "string" || body.token === "")
82
+ const body = await readJsonObject(response);
83
+ const token = body["token"];
84
+ if (typeof token !== "string" || token === "")
83
85
  throw new PreviewLinkError();
84
- const expiresAt = typeof body.expiresAt === "string" ? Date.parse(body.expiresAt) : NaN;
85
- this.#token = body.token;
86
+ const expiresAt = typeof body["expiresAt"] === "string" ? Date.parse(body["expiresAt"]) : NaN;
87
+ this.#token = token;
86
88
  // An unparseable expiry means exchanging again next time rather than trusting a token for an
87
89
  // unknown length of time.
88
90
  this.#expiresAtMs = Number.isNaN(expiresAt) ? 0 : expiresAt;
89
- return body.token;
91
+ return token;
90
92
  }
91
93
  }
92
94
  //# sourceMappingURL=preview.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"preview.js","sourceRoot":"","sources":["../src/preview.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,6EAA6E;AAC7E,MAAM,eAAe,GAAG,KAAK,CAAA;AAE7B;;;;;;;GAOG;AACH,MAAM,OAAO,gBAAiB,SAAQ,KAAK;IACzC,YAAY,OAAO,GAAG,uEAAuE;QAC3F,KAAK,CAAC,OAAO,CAAC,CAAA;QACd,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAA;IAChC,CAAC;CACF;AAOD;;;;;GAKG;AACH,MAAM,OAAO,iBAAiB;IACnB,SAAS,CAAQ;IACjB,KAAK,CAAQ;IACtB,MAAM,GAAkB,IAAI,CAAA;IAC5B,YAAY,GAAG,CAAC,CAAA;IAChB,SAAS,GAA2B,IAAI,CAAA;IAExC,YAAY,OAAe,EAAE,IAAY;QACvC,IAAI,CAAC,SAAS,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,wBAAwB,CAAA;QACtE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAA;IACnB,CAAC;IAED,4EAA4E;IAC5E,KAAK,CAAC,KAAK;QACT,IAAI,IAAI,CAAC,MAAM,KAAK,IAAI,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,YAAY,GAAG,eAAe,EAAE,CAAC;YAC7E,OAAO,IAAI,CAAC,MAAM,CAAA;QACpB,CAAC;QACD,wEAAwE;QACxE,IAAI,CAAC,SAAS,KAAK,IAAI,CAAC,SAAS,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE;YAC/C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAA;QACvB,CAAC,CAAC,CAAA;QACF,OAAO,IAAI,CAAC,SAAS,CAAA;IACvB,CAAC;IAED,KAAK,CAAC,SAAS;QACb,IAAI,QAAkB,CA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.js";
2
2
  import { bearerToken } from "./query.js";
3
+ import { decodeJwtPayload } from "./jwt.js";
3
4
  const DEFAULT_MAX_ENTRIES = 256;
4
- function parseJwtPayload(token) {
5
+ /** A string claim off the token, or undefined when the token or the claim is not readable. */
6
+ function stringClaim(token, claim) {
5
7
  const parts = token.split(".");
6
8
  if (parts.length !== 3)
7
- return null;
8
- try {
9
- const payloadJson = atob(parts[1] ?? "");
10
- return JSON.parse(payloadJson);
11
- }
12
- catch {
13
- return null;
14
- }
9
+ return undefined;
10
+ const value = decodeJwtPayload(parts[1] ?? "")?.[claim];
11
+ return typeof value === "string" ? value : undefined;
12
+ }
13
+ /**
14
+ * The boundary between the cache's stored results and the type a reader asks for.
15
+ *
16
+ * Nothing about a stored result can be checked against `T`: the cache holds whatever `set` was
17
+ * given. A key names one request (method, URL, select, identity), so the reader of a key is the
18
+ * request that stored it, and `T` is that request's own claim about its rows.
19
+ */
20
+ function isResultFor(result) {
21
+ return result.error === null;
15
22
  }
16
23
  /** Auth component for cache keys, mirrors server IdentityForCache. */
17
24
  export function identityFingerprint(headers, scope) {
@@ -20,9 +27,8 @@ export function identityFingerprint(headers, scope) {
20
27
  const token = bearerToken(headers);
21
28
  if (!token)
22
29
  return "anon";
23
- const claims = parseJwtPayload(token);
24
- const role = claims?.role?.trim() || "authenticated";
25
- const sub = claims?.sub?.trim();
30
+ const role = stringClaim(token, "role")?.trim() || "authenticated";
31
+ const sub = stringClaim(token, "sub")?.trim();
26
32
  if (sub)
27
33
  return `${role}:${sub}`;
28
34
  return sha256Hex(token).slice(0, 16);
@@ -48,7 +54,7 @@ export class QueryCache {
48
54
  this.store.delete(key);
49
55
  return null;
50
56
  }
51
- return entry.result;
57
+ return isResultFor(entry.result) ? entry.result : null;
52
58
  }
53
59
  set(key, result, ttlMs) {
54
60
  if (ttlMs <= 0 || result.error !== null)
@@ -1 +1 @@
1
- {"version":3,"file":"query-cache.js","sourceRoot":"","sources":["../src/query-cache.ts"],"names":[],"mappings":"AACA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CAAA;QACjC,IAAI,CAAC,KAAK;YAAE,OAAO,IAAI,CAAA;QACvB,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;YACtB,OAAO,IAAI,CAAA;QACb,CAAC;QACD,OAAO,WAAW,CAAI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAA;IAC3D,CAAC;IAED,GAAG,CAAI,GAAW,EAAE,MAAsB,EAAE,KAAa;QACvD,IAAI,KAAK,IAAI,CAAC,IAAI,MAAM,CAAC,KAAK,KAAK,IAAI;YAAE,OAAM;QAC/C,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACvC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAA;YAC5C,IAAI,KAAK,KAAK,SAAS;gBAAE,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;QACnD,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE;YAClB,MAAM,EAAE,MAA8B;YACtC,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK;SAC9B,CAAC,CAAA;IACJ,CAAC;IAED,KAAK;QACH,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAA;IACpB,CAAC;CACF;AAED,oDAAoD;AACpD,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,UAAU,EAAE,CAAA"}
package/dist/query.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  import type { QueryCache, QueryCacheOptions } from "./query-cache.js";
2
- import type { MaskedField, QueryResult, SelectQueryOptions, SupatypeError } from "./types.js";
2
+ import type { MaskedField, QueryResult, SelectQueryOptions, SupatypeError, TableDef } from "./types.js";
3
+ import type { SelectRow } from "./select-types.js";
4
+ import { FilterBuilder } from "./filters.js";
5
+ import { type FetchOptions, type RequestTransport } from "./fetch-with-retry.js";
3
6
  /**
4
7
  * Parse `X-Supatype-Masked-Fields: salary=row, ssn=identity`.
5
8
  *
@@ -22,36 +25,31 @@ export declare function asHeadersProvider(headers: Record<string, string> | Head
22
25
  * lowercase is just as valid over the wire.
23
26
  */
24
27
  export declare function bearerToken(headers: Record<string, string>): string;
25
- export declare class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
28
+ export type { RequestTransport };
29
+ /** Send once; on a 401, let the session refresh and send again with freshly resolved headers. */
30
+ export declare function fetchWithOptional401Retry(send: RequestTransport, url: string, init: RequestInit & FetchOptions, resolveHeaders: () => Promise<Record<string, string>>, onUnauthorized?: (() => Promise<void>) | undefined): Promise<Response>;
31
+ /**
32
+ * The total from PostgREST's `Content-Range: <range>/<total>`, or null when there is none.
33
+ *
34
+ * PostgREST sends the header on every read, and the total is `*` unless the request asked for a
35
+ * count with `Prefer: count=...`. Reading `*` as a number gave `NaN` on every ordinary query.
36
+ */
37
+ export declare function parseContentRangeTotal(header: string | null): number | null;
38
+ export declare class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<QueryResult<TRow[]>> {
26
39
  private readonly baseUrl;
27
40
  private readonly path;
28
41
  private readonly getHeaders;
29
42
  private readonly onUnauthorized;
43
+ private readonly send;
30
44
  private readonly extraHeaders;
31
- private readonly params;
32
45
  private readonly queryCache;
33
46
  private cacheOptions;
34
47
  private readonly countMode;
35
48
  private readonly head;
36
- constructor(baseUrl: string, path: string, headers: Record<string, string> | HeadersProvider, columns?: string | undefined, queryCache?: QueryCache, onUnauthorized?: (() => Promise<void>) | undefined, selectOptions?: SelectQueryOptions | undefined);
49
+ constructor(baseUrl: string, path: string, headers: Record<string, string> | HeadersProvider, columns?: string | undefined, queryCache?: QueryCache, onUnauthorized?: (() => Promise<void>) | undefined, selectOptions?: SelectQueryOptions | undefined, transport?: RequestTransport);
37
50
  /** Enable GET caching. Use `{ server: true }` for Valkey-backed server cache. */
38
51
  cache(options: QueryCacheOptions): this;
39
52
  select(columns: string): this;
40
- eq(column: string, value: unknown): this;
41
- neq(column: string, value: unknown): this;
42
- gt(column: string, value: unknown): this;
43
- gte(column: string, value: unknown): this;
44
- lt(column: string, value: unknown): this;
45
- lte(column: string, value: unknown): this;
46
- like(column: string, pattern: string): this;
47
- ilike(column: string, pattern: string): this;
48
- in(column: string, values: unknown[]): this;
49
- is(column: string, value: null | boolean): this;
50
- not(column: string, op: string, value: unknown): this;
51
- contains(column: string, value: unknown): this;
52
- containedBy(column: string, value: unknown): this;
53
- /** PostgREST OR filter: pass conditions in PostgREST syntax, e.g. `"status.eq.active,owner_id.eq.123"`. */
54
- or(filters: string): this;
55
53
  order(column: string, opts?: {
56
54
  ascending?: boolean | undefined;
57
55
  nullsFirst?: boolean | undefined;
@@ -69,29 +67,110 @@ export declare class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[
69
67
  private applyServerCacheHeader;
70
68
  private mergePreferHeader;
71
69
  private _fetch;
70
+ /** The cached result for this read, when it is cached and the cache holds one. */
71
+ private cachedResult;
72
+ /** Cache a read's rows, when this read is cached and it returned rows. */
73
+ private remember;
74
+ /** What the response says: a refusal, no body (HEAD or 204), or the rows. */
75
+ private readResult;
76
+ private cacheKey;
72
77
  }
73
78
  type HttpMethod = "POST" | "PATCH" | "DELETE";
74
- export declare class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
79
+ /**
80
+ * An insert sent through `supatype.create_record` (one row) or `supatype.create_records` (several,
81
+ * all or none) rather than as a plain `POST`: the table, which keeps drafts, and the key its new
82
+ * records are read back by.
83
+ *
84
+ * Why at all: a new record on a drafts model is unpublished, and when the model's read rule hides
85
+ * unpublished rows Postgres refuses an insert that asks for the row back, since it checks the
86
+ * returned row against that rule before anything has made it visible to its author.
87
+ * `create_record` inserts without reading back and writes version 1, after which the author sees it.
88
+ */
89
+ export interface DraftCreate {
90
+ readonly table: string;
91
+ readonly primaryKey: string;
92
+ }
93
+ /**
94
+ * An update sent through `supatype.save_drafts` rather than as a plain `PATCH`: the table, which
95
+ * keeps drafts, its key, and whether to publish the new drafts in the same call.
96
+ *
97
+ * Why at all: on a drafts model the live row changes only by publishing, and the database refuses
98
+ * a direct update of it from the API roles.
99
+ */
100
+ export interface DraftEdit extends DraftCreate {
101
+ readonly publish: boolean;
102
+ }
103
+ /** How a write is made beyond its method and body. */
104
+ export interface MutationOptions {
105
+ upsert?: boolean | undefined;
106
+ /** Create the records through `create_record` or `create_records`, for an insert on a drafts model. */
107
+ createThrough?: DraftCreate | undefined;
108
+ /** Save a draft of each matched record through `save_drafts`, for an update on a drafts model. */
109
+ editThrough?: DraftEdit | undefined;
110
+ /** Send nothing and answer with this: the write asks for something its table cannot do. */
111
+ refusal?: SupatypeError | undefined;
112
+ }
113
+ /**
114
+ * The rows a write hands back for `select(columns)`.
115
+ *
116
+ * Read from the string, as `TableClient.select` does, when the builder knows the tables it was
117
+ * written against. A builder constructed by hand knows only its row, so there it stays the row.
118
+ */
119
+ type ReturnedRow<TRow, TTables, TName extends string, TColumns extends string> = [
120
+ TTables
121
+ ] extends [Record<string, TableDef>] ? SelectRow<TTables, TName, TColumns> : TRow;
122
+ export declare class MutationBuilder<TRow, TTables = unknown, TName extends string = string> extends FilterBuilder implements PromiseLike<QueryResult<TRow[]>> {
75
123
  private readonly baseUrl;
76
124
  private readonly path;
77
125
  private readonly getHeaders;
78
126
  private readonly onUnauthorized;
127
+ private readonly send;
79
128
  private readonly extraHeaders;
80
129
  private readonly method;
81
130
  private readonly body;
82
- private readonly params;
83
- constructor(baseUrl: string, path: string, headers: Record<string, string> | HeadersProvider, method: HttpMethod, body?: unknown, opts?: {
84
- upsert?: boolean | undefined;
85
- } | undefined, onUnauthorized?: (() => Promise<void>) | undefined);
86
- eq(column: string, value: unknown): this;
87
- neq(column: string, value: unknown): this;
88
- in(column: string, values: unknown[]): this;
89
- /** Limit returned columns on the mutation response (requires `return=representation`). */
90
- select(columns?: string): this;
131
+ private readonly createThrough;
132
+ private readonly editThrough;
133
+ private readonly refusal;
134
+ constructor(baseUrl: string, path: string, headers: Record<string, string> | HeadersProvider, method: HttpMethod, body?: unknown, opts?: MutationOptions | undefined, onUnauthorized?: (() => Promise<void>) | undefined, transport?: RequestTransport);
135
+ private prefer;
136
+ /**
137
+ * Return the written rows, limited to `columns`.
138
+ *
139
+ * Asks for the representation too, which a delete does not by default: without it PostgREST
140
+ * answers 204 and `delete().select()` returned no rows although it had deleted some.
141
+ */
142
+ select<TColumns extends string = "*">(columns?: TColumns | undefined): MutationBuilder<ReturnedRow<TRow, TTables, TName, TColumns>, TTables, TName>;
143
+ /** Return the written rows typed as `TResult`, for a shape the select string cannot describe. */
144
+ select<TResult>(columns?: string | undefined): MutationBuilder<TResult, TTables, TName>;
91
145
  single(): Promise<QueryResult<TRow>>;
92
146
  maybeSingle(): Promise<QueryResult<TRow | null>>;
93
147
  then<R1 = QueryResult<TRow[]>, R2 = never>(onfulfilled?: ((value: QueryResult<TRow[]>) => R1 | PromiseLike<R1>) | null | undefined, onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null | undefined): PromiseLike<R1 | R2>;
148
+ /** POST, PATCH and DELETE: the transport applies the timeout and never retries them. */
149
+ private requestInit;
94
150
  private _execute;
151
+ /**
152
+ * Create the records as their first drafts, then read them back as an insert returns them.
153
+ *
154
+ * Read from the draft view, which has the table's row type: the live row of a new record holds no
155
+ * locale yet, so reading the table would hand back empty translations for what was just written.
156
+ * The select string applies as it would to the insert's own answer, and several rows come back in
157
+ * the order they were sent.
158
+ */
159
+ private createDraftRecords;
160
+ /**
161
+ * Save a draft of each record the filters match, publishing it too when asked, then read the
162
+ * drafts back as an update returns its rows. The live rows are left to publishing.
163
+ *
164
+ * The records are the ones the caller reads in the table under the update's filters, as a `PATCH`
165
+ * would match them, and `save_drafts` saves all of them or none.
166
+ */
167
+ private saveDraftRecords;
168
+ /** The keys of the rows this write's filters match, read from the table as the caller. */
169
+ private matchedKeys;
170
+ /** `keys`' newest drafts, from the draft view, with this write's select and in the order given. */
171
+ private readDrafts;
172
+ /** Call the publishing function `fn` with `body`: the record keys it answers with, in order, or why not. */
173
+ private callPublishing;
95
174
  }
96
175
  export type { SupatypeError };
97
176
  export type { QueryCacheOptions, CacheStatus } from "./query-cache.js";