@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.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +58 -31
- package/.turbo/turbo-typecheck.log +2 -2
- package/LICENSE +1 -1
- package/dist/auth-redirect.d.ts +48 -0
- package/dist/auth-redirect.d.ts.map +1 -0
- package/dist/auth-redirect.js +70 -0
- package/dist/auth-redirect.js.map +1 -0
- package/dist/auth.d.ts +78 -4
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +373 -274
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +16 -0
- package/dist/bindings.d.ts.map +1 -0
- package/dist/bindings.js +13 -0
- package/dist/bindings.js.map +1 -0
- package/dist/caller-types.d.ts +18 -0
- package/dist/caller-types.d.ts.map +1 -0
- package/dist/caller-types.js +22 -0
- package/dist/caller-types.js.map +1 -0
- package/dist/draft-create.d.ts +12 -0
- package/dist/draft-create.d.ts.map +1 -0
- package/dist/draft-create.js +47 -0
- package/dist/draft-create.js.map +1 -0
- package/dist/draft-models-registry.d.ts +27 -0
- package/dist/draft-models-registry.d.ts.map +1 -0
- package/dist/draft-models-registry.js +61 -0
- package/dist/draft-models-registry.js.map +1 -0
- package/dist/error-codes-doc.d.ts +1 -1
- package/dist/error-codes-doc.d.ts.map +1 -1
- package/dist/error-codes-doc.js +42 -34
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +102 -60
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +69 -28
- package/dist/errors.js.map +1 -1
- package/dist/exact-response.d.ts.map +1 -1
- package/dist/exact-response.js +2 -1
- package/dist/exact-response.js.map +1 -1
- package/dist/exact-values.d.ts +2 -0
- package/dist/exact-values.d.ts.map +1 -1
- package/dist/exact-values.js +12 -10
- package/dist/exact-values.js.map +1 -1
- package/dist/fetch-with-retry.d.ts +21 -6
- package/dist/fetch-with-retry.d.ts.map +1 -1
- package/dist/fetch-with-retry.js +67 -53
- package/dist/fetch-with-retry.js.map +1 -1
- package/dist/field-kinds-registry.d.ts +11 -3
- package/dist/field-kinds-registry.d.ts.map +1 -1
- package/dist/field-kinds-registry.js +10 -6
- package/dist/field-kinds-registry.js.map +1 -1
- package/dist/filters.d.ts +51 -0
- package/dist/filters.d.ts.map +1 -0
- package/dist/filters.js +117 -0
- package/dist/filters.js.map +1 -0
- package/dist/generated-client.d.ts +7 -0
- package/dist/generated-client.d.ts.map +1 -0
- package/dist/generated-client.js +7 -0
- package/dist/generated-client.js.map +1 -0
- package/dist/graphql-document.d.ts +39 -0
- package/dist/graphql-document.d.ts.map +1 -0
- package/dist/graphql-document.js +228 -0
- package/dist/graphql-document.js.map +1 -0
- package/dist/graphql-json.d.ts +56 -0
- package/dist/graphql-json.d.ts.map +1 -0
- package/dist/graphql-json.js +220 -0
- package/dist/graphql-json.js.map +1 -0
- package/dist/graphql-transport.d.ts +28 -0
- package/dist/graphql-transport.d.ts.map +1 -0
- package/dist/graphql-transport.js +77 -0
- package/dist/graphql-transport.js.map +1 -0
- package/dist/index.d.ts +103 -40
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +153 -157
- package/dist/index.js.map +1 -1
- package/dist/json.d.ts +61 -0
- package/dist/json.d.ts.map +1 -0
- package/dist/json.js +83 -0
- package/dist/json.js.map +1 -0
- package/dist/jwt.d.ts +16 -0
- package/dist/jwt.d.ts.map +1 -0
- package/dist/jwt.js +37 -0
- package/dist/jwt.js.map +1 -0
- package/dist/live-preview.d.ts +23 -0
- package/dist/live-preview.d.ts.map +1 -0
- package/dist/live-preview.js +28 -0
- package/dist/live-preview.js.map +1 -0
- package/dist/mutation-request.d.ts +17 -0
- package/dist/mutation-request.d.ts.map +1 -0
- package/dist/mutation-request.js +41 -0
- package/dist/mutation-request.js.map +1 -0
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +8 -6
- package/dist/preview.js.map +1 -1
- package/dist/query-cache.d.ts.map +1 -1
- package/dist/query-cache.js +19 -13
- package/dist/query-cache.js.map +1 -1
- package/dist/query.d.ts +108 -29
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +294 -224
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +20 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +105 -12
- package/dist/realtime.js.map +1 -1
- package/dist/select-types.d.ts +99 -0
- package/dist/select-types.d.ts.map +1 -0
- package/dist/select-types.js +2 -0
- package/dist/select-types.js.map +1 -0
- package/dist/storage.d.ts +81 -11
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +129 -37
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +69 -0
- package/dist/table-subscription.d.ts.map +1 -0
- package/dist/table-subscription.js +93 -0
- package/dist/table-subscription.js.map +1 -0
- package/dist/types.d.ts +84 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +6 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -2
- package/src/auth-redirect.ts +90 -0
- package/src/auth.ts +421 -280
- package/src/bindings.ts +22 -0
- package/src/caller-types.ts +27 -0
- package/src/draft-create.ts +51 -0
- package/src/draft-models-registry.ts +81 -0
- package/src/error-codes-doc.ts +44 -35
- package/src/errors.ts +72 -28
- package/src/exact-response.ts +2 -1
- package/src/exact-values.ts +16 -9
- package/src/fetch-with-retry.ts +80 -70
- package/src/field-kinds-registry.ts +22 -9
- package/src/filters.ts +133 -0
- package/src/generated-client.ts +6 -0
- package/src/graphql-document.ts +234 -0
- package/src/graphql-json.ts +243 -0
- package/src/graphql-transport.ts +97 -0
- package/src/index.ts +272 -201
- package/src/json.ts +117 -0
- package/src/jwt.ts +37 -0
- package/src/live-preview.ts +37 -0
- package/src/mutation-request.ts +66 -0
- package/src/preview.ts +9 -11
- package/src/query-cache.ts +19 -16
- package/src/query.ts +389 -270
- package/src/realtime.ts +116 -13
- package/src/select-types.ts +184 -0
- package/src/storage.ts +214 -43
- package/src/table-subscription.ts +160 -0
- package/src/types.ts +90 -5
- package/tests/auth-error-codes.test.ts +53 -0
- package/tests/auth-errors.test.ts +84 -0
- package/tests/auth-events.test.ts +136 -0
- package/tests/auth-url-session.test.ts +204 -0
- package/tests/auth.test.ts +122 -26
- package/tests/count.test.ts +60 -0
- package/tests/data-plane-auth.test.ts +21 -46
- package/tests/draft-insert.integration.test.ts +118 -0
- package/tests/draft-insert.test.ts +225 -0
- package/tests/draft-profile.test.ts +55 -84
- package/tests/draft-update.integration.test.ts +122 -0
- package/tests/draft-update.test.ts +174 -0
- package/tests/dynamic-headers.test.ts +45 -0
- package/tests/entry-points.test.ts +42 -0
- package/tests/exact-response.test.ts +4 -4
- package/tests/exact-values.test.ts +14 -25
- package/tests/field-kinds-registry.test.ts +3 -3
- package/tests/filters.test.ts +146 -0
- package/tests/graphql-json.test.ts +199 -0
- package/tests/helpers/mock-websocket.ts +44 -11
- package/tests/helpers/oauth-binding.ts +92 -0
- package/tests/helpers/signup-binding.ts +73 -0
- package/tests/helpers/socket-swap.ts +139 -0
- package/tests/mfa-totp-integration.test.ts +13 -20
- package/tests/postgrest-error-codes.test.ts +85 -0
- package/tests/query-cache.test.ts +116 -117
- package/tests/query.test.ts +29 -31
- package/tests/rate-limit-integration.test.ts +4 -12
- package/tests/realtime-exact-values.test.ts +2 -4
- package/tests/realtime-presence.test.ts +75 -0
- package/tests/realtime-session-auth.test.ts +2 -4
- package/tests/realtime-swap-status.test.ts +62 -0
- package/tests/retry-integration.test.ts +3 -8
- package/tests/retry-policy.test.ts +166 -0
- package/tests/rpc-resend.test.ts +24 -0
- package/tests/server-bodies.test.ts +139 -0
- package/tests/serverless.test.ts +2 -2
- package/tests/signed-url-absolute.test.ts +2 -5
- package/tests/storage-object-shape.test.ts +101 -0
- package/tests/storage-quota-integration.test.ts +3 -2
- package/tests/storage-reference-url.test.ts +51 -0
- package/tests/storage-upload-browser.test.ts +71 -0
- package/tests/storage-upload-limit-integration.test.ts +12 -22
- package/tests/subscribe-frame.test.ts +5 -11
- package/tests/support/fetch-mock.ts +64 -0
- package/tests/support/storage-object.ts +37 -0
- package/tests/table-subscribe.test.ts +13 -13
- package/tests/table-subscription.test.ts +105 -0
- package/tests/table-transport.test.ts +94 -0
- package/tests/tsconfig.json +1 -1
- package/tests/types.test.ts +153 -1
- package/tsconfig.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
package/src/fetch-with-retry.ts
CHANGED
|
@@ -11,98 +11,108 @@ export interface FetchOptions {
|
|
|
11
11
|
timeout?: number | undefined
|
|
12
12
|
/** Disable automatic retry. */
|
|
13
13
|
retry?: boolean | undefined
|
|
14
|
+
/**
|
|
15
|
+
* Retry this request although its method is not GET or HEAD.
|
|
16
|
+
*
|
|
17
|
+
* Only GET and HEAD are retried by default. A POST, PUT, PATCH or DELETE that failed in flight may
|
|
18
|
+
* still have been applied, and sending it again could apply it twice. Set this when the caller
|
|
19
|
+
* knows repeating the request is harmless: a read sent as POST, or a write keyed so that a second
|
|
20
|
+
* copy changes nothing.
|
|
21
|
+
*/
|
|
22
|
+
idempotent?: boolean | undefined
|
|
14
23
|
}
|
|
15
24
|
|
|
25
|
+
/** How a request is sent: `fetch`, or the client's retrying fetch with its timeout. */
|
|
26
|
+
export type RequestTransport = (url: string, init: RequestInit & FetchOptions) => Promise<Response>
|
|
27
|
+
|
|
28
|
+
/** Plain `fetch`, for a client built without a transport. */
|
|
29
|
+
export const plainFetch: RequestTransport = (url, init) => fetch(url, init)
|
|
30
|
+
|
|
16
31
|
const DEFAULT_MAX_RETRIES = 3
|
|
17
32
|
const DEFAULT_TIMEOUT = 30000
|
|
18
33
|
const RETRY_DELAYS = [200, 1000, 3000]
|
|
34
|
+
const SAFE_METHODS = new Set(["GET", "HEAD"])
|
|
35
|
+
|
|
36
|
+
/** Whether sending this request twice is harmless: GET, HEAD, or marked `idempotent`. */
|
|
37
|
+
function isRepeatable(init: (RequestInit & FetchOptions) | undefined): boolean {
|
|
38
|
+
return SAFE_METHODS.has((init?.method ?? "GET").toUpperCase()) || init?.idempotent === true
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** How many times this request may be repeated: none unless it is safe to send twice. */
|
|
42
|
+
function allowedRetries(init: (RequestInit & FetchOptions) | undefined): number {
|
|
43
|
+
if (init?.retry === false || !isRepeatable(init)) return 0
|
|
44
|
+
return init?.maxRetries ?? DEFAULT_MAX_RETRIES
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A failure that never produced a response, as the typed error callers branch on. */
|
|
48
|
+
function networkFailure(err: Error, url: string, timeout: number): NetworkError {
|
|
49
|
+
if (err.name === "AbortError") {
|
|
50
|
+
return new NetworkError(`Request timed out after ${timeout}ms`, NetworkErrorCodes.TIMEOUT)
|
|
51
|
+
}
|
|
52
|
+
const message = err.message.toLowerCase()
|
|
53
|
+
if (message.includes("econnrefused")) {
|
|
54
|
+
return new NetworkError(`Connection refused: ${url}`, NetworkErrorCodes.CONNECTION_REFUSED)
|
|
55
|
+
}
|
|
56
|
+
if (message.includes("enotfound") || message.includes("dns")) {
|
|
57
|
+
return new NetworkError(`DNS lookup failed: ${url}`, NetworkErrorCodes.DNS_FAILURE)
|
|
58
|
+
}
|
|
59
|
+
return new NetworkError(err.message)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function fetchWithTimeout(url: string, init: RequestInit | undefined, timeout: number): Promise<Response> {
|
|
63
|
+
const controller = new AbortController()
|
|
64
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout)
|
|
65
|
+
try {
|
|
66
|
+
return await fetch(url, { ...init, signal: controller.signal })
|
|
67
|
+
} finally {
|
|
68
|
+
clearTimeout(timeoutId)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
19
71
|
|
|
20
72
|
/**
|
|
21
|
-
* Fetch with
|
|
73
|
+
* Fetch with a timeout on every request, and retry for transient errors on requests safe to repeat.
|
|
22
74
|
*
|
|
23
|
-
* Retries on:
|
|
24
|
-
* -
|
|
25
|
-
* - 5xx server errors
|
|
75
|
+
* Retries GET and HEAD, and any request marked `idempotent`, on:
|
|
76
|
+
* - network errors (connection refused, DNS), but never a timeout;
|
|
77
|
+
* - 5xx server errors;
|
|
78
|
+
* - 429, after its `Retry-After`, throwing `RateLimitError` once the retries run out.
|
|
26
79
|
*
|
|
27
|
-
* Does
|
|
28
|
-
*
|
|
80
|
+
* Does not retry 4xx client errors. Any other request (a POST, PUT, PATCH or DELETE not marked
|
|
81
|
+
* `idempotent`) is sent once and its response returned as it came, a 429 included, so the caller
|
|
82
|
+
* sees the server's own error rather than a `RateLimitError`.
|
|
29
83
|
*/
|
|
30
84
|
export async function fetchWithRetry(
|
|
31
85
|
url: string,
|
|
32
86
|
init?: RequestInit & FetchOptions,
|
|
33
87
|
): Promise<Response> {
|
|
34
|
-
const maxRetries =
|
|
88
|
+
const maxRetries = allowedRetries(init)
|
|
35
89
|
const timeout = init?.timeout ?? DEFAULT_TIMEOUT
|
|
36
|
-
let lastError: Error | undefined
|
|
37
90
|
|
|
38
|
-
for (let attempt = 0;
|
|
91
|
+
for (let attempt = 0; ; attempt++) {
|
|
92
|
+
const canRetry = attempt < maxRetries
|
|
93
|
+
let response: Response
|
|
39
94
|
try {
|
|
40
|
-
|
|
41
|
-
const timeoutId = setTimeout(() => controller.abort(), timeout)
|
|
42
|
-
|
|
43
|
-
const response = await fetch(url, {
|
|
44
|
-
...init,
|
|
45
|
-
signal: controller.signal,
|
|
46
|
-
})
|
|
47
|
-
|
|
48
|
-
clearTimeout(timeoutId)
|
|
49
|
-
|
|
50
|
-
// Handle rate limiting
|
|
51
|
-
if (response.status === 429) {
|
|
52
|
-
const retryAfter = parseInt(response.headers.get("Retry-After") || "5", 10)
|
|
53
|
-
if (attempt < maxRetries) {
|
|
54
|
-
await sleep(retryAfter * 1000)
|
|
55
|
-
continue
|
|
56
|
-
}
|
|
57
|
-
throw new RateLimitError(retryAfter)
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// Retry on 5xx server errors
|
|
61
|
-
if (response.status >= 500 && attempt < maxRetries) {
|
|
62
|
-
await sleep(RETRY_DELAYS[attempt] ?? 3000)
|
|
63
|
-
continue
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
return response
|
|
95
|
+
response = await fetchWithTimeout(url, init, timeout)
|
|
67
96
|
} catch (err) {
|
|
68
|
-
if (err instanceof RateLimitError) throw err
|
|
69
97
|
if (err instanceof SupatypeError) throw err
|
|
98
|
+
const error = err instanceof Error ? err : new Error(String(err))
|
|
99
|
+
if (error.name === "AbortError" || !canRetry) throw networkFailure(error, url, timeout)
|
|
100
|
+
await sleep(RETRY_DELAYS[attempt] ?? 3000)
|
|
101
|
+
continue
|
|
102
|
+
}
|
|
70
103
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
`Request timed out after ${timeout}ms`,
|
|
77
|
-
NetworkErrorCodes.TIMEOUT,
|
|
78
|
-
)
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
// Retry on network errors
|
|
82
|
-
if (attempt < maxRetries) {
|
|
83
|
-
await sleep(RETRY_DELAYS[attempt] ?? 3000)
|
|
84
|
-
continue
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
// Classify and throw
|
|
88
|
-
const message = lastError.message.toLowerCase()
|
|
89
|
-
if (message.includes("econnrefused")) {
|
|
90
|
-
throw new NetworkError(
|
|
91
|
-
`Connection refused: ${url}`,
|
|
92
|
-
NetworkErrorCodes.CONNECTION_REFUSED,
|
|
93
|
-
)
|
|
94
|
-
}
|
|
95
|
-
if (message.includes("enotfound") || message.includes("dns")) {
|
|
96
|
-
throw new NetworkError(
|
|
97
|
-
`DNS lookup failed: ${url}`,
|
|
98
|
-
NetworkErrorCodes.DNS_FAILURE,
|
|
99
|
-
)
|
|
100
|
-
}
|
|
101
|
-
throw new NetworkError(lastError.message)
|
|
104
|
+
if (response.status === 429 && isRepeatable(init)) {
|
|
105
|
+
const retryAfter = parseInt(response.headers.get("Retry-After") || "5", 10)
|
|
106
|
+
if (!canRetry) throw new RateLimitError(retryAfter)
|
|
107
|
+
await sleep(retryAfter * 1000)
|
|
108
|
+
continue
|
|
102
109
|
}
|
|
110
|
+
if (response.status >= 500 && canRetry) {
|
|
111
|
+
await sleep(RETRY_DELAYS[attempt] ?? 3000)
|
|
112
|
+
continue
|
|
113
|
+
}
|
|
114
|
+
return response
|
|
103
115
|
}
|
|
104
|
-
|
|
105
|
-
throw new NetworkError(lastError?.message || "Request failed after retries")
|
|
106
116
|
}
|
|
107
117
|
|
|
108
118
|
function sleep(ms: number): Promise<void> {
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Which columns hold values a JSON parser would destroy, told to the client by generated code.
|
|
3
3
|
*
|
|
4
|
-
* `supatype push` writes `supatype/client.ts` into the project. That file calls
|
|
4
|
+
* `supatype push` writes `supatype/generated/client.ts` into the project. That file calls
|
|
5
5
|
* {@link registerFieldKinds} at import time and re-exports `createClient`, so an app writes
|
|
6
6
|
*
|
|
7
|
-
* import { createClient } from "./supatype/client"
|
|
7
|
+
* import { createClient } from "./supatype/generated/client"
|
|
8
8
|
*
|
|
9
9
|
* and the kinds arrive by the same import that brings the client. They are compiled into the same
|
|
10
10
|
* bundle, so there is nothing to fetch, nothing to read from disk, and nothing that can be stale
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
* {@link fieldKindsAreRegistered} is false, and the caller can say so.
|
|
18
18
|
*/
|
|
19
19
|
import type { ExactFields, ExactKind } from "./exact-values.js"
|
|
20
|
+
import { isJsonObject, isOneOf } from "./json.js"
|
|
20
21
|
|
|
21
22
|
/** Table name to its exact-value columns. */
|
|
22
23
|
export type ExactFieldsByTable = Readonly<Record<string, ExactFields>>
|
|
@@ -27,7 +28,17 @@ export type FieldKindsDocument = {
|
|
|
27
28
|
readonly tables: Readonly<Record<string, Readonly<Record<string, ExactKind>>>>
|
|
28
29
|
}
|
|
29
30
|
|
|
31
|
+
/**
|
|
32
|
+
* A document from a generator this client predates: a version it does not know, or kinds it does
|
|
33
|
+
* not. Accepted so that generated code type-checks against an older client, and then ignored.
|
|
34
|
+
*/
|
|
35
|
+
export type UnrecognisedFieldKindsDocument = {
|
|
36
|
+
readonly version: number
|
|
37
|
+
readonly tables: unknown
|
|
38
|
+
}
|
|
39
|
+
|
|
30
40
|
const SUPPORTED_VERSION = 1
|
|
41
|
+
const isExactKind = isOneOf(["bigint", "numeric"])
|
|
31
42
|
const NO_FIELDS: ExactFields = {}
|
|
32
43
|
|
|
33
44
|
// Module level, and deliberately not per client. Server-side rendering builds a client per
|
|
@@ -40,17 +51,19 @@ let registered: ExactFieldsByTable | null = null
|
|
|
40
51
|
* A document whose version this client does not understand is ignored rather than guessed at: a
|
|
41
52
|
* newer shape read by older rules is how a client starts converting the wrong columns.
|
|
42
53
|
*/
|
|
43
|
-
export function registerFieldKinds(document: FieldKindsDocument): void {
|
|
44
|
-
|
|
45
|
-
if (document
|
|
46
|
-
if (document
|
|
54
|
+
export function registerFieldKinds(document: FieldKindsDocument | UnrecognisedFieldKindsDocument): void {
|
|
55
|
+
// Checked as JSON, whatever the type says: plain JavaScript calls this too.
|
|
56
|
+
if (!isJsonObject(document)) return
|
|
57
|
+
if (document["version"] !== SUPPORTED_VERSION) return
|
|
58
|
+
const declared = document["tables"]
|
|
59
|
+
if (!isJsonObject(declared)) return
|
|
47
60
|
|
|
48
61
|
const tables: Record<string, ExactFields> = {}
|
|
49
|
-
for (const [table, columns] of Object.entries(
|
|
50
|
-
if (columns
|
|
62
|
+
for (const [table, columns] of Object.entries(declared)) {
|
|
63
|
+
if (!isJsonObject(columns)) continue
|
|
51
64
|
const fields: Record<string, ExactKind> = {}
|
|
52
65
|
for (const [column, kind] of Object.entries(columns)) {
|
|
53
|
-
if (kind
|
|
66
|
+
if (isExactKind(kind)) fields[column] = kind
|
|
54
67
|
}
|
|
55
68
|
if (Object.keys(fields).length > 0) tables[table] = fields
|
|
56
69
|
}
|
package/src/filters.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The PostgREST row filters, in one place for reads and writes alike.
|
|
3
|
+
*
|
|
4
|
+
* `QueryBuilder` and `MutationBuilder` both extend this, so an update or a delete narrows its rows
|
|
5
|
+
* with exactly the operators a select has. They used to be written out twice, and the mutation copy
|
|
6
|
+
* stopped at `eq`, `neq` and `in`, which left a ranged or patterned delete impossible without a
|
|
7
|
+
* read first.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** A Postgres array literal element needs quoting when it is empty, spells NULL, or holds syntax. */
|
|
11
|
+
const ARRAY_ELEMENT_NEEDS_QUOTES = /^$|^null$|[\s,{}"\\]/i
|
|
12
|
+
|
|
13
|
+
/** An `in.(...)` value needs quoting when it holds the list's own delimiters. */
|
|
14
|
+
const IN_VALUE_NEEDS_QUOTES = /[,()]/
|
|
15
|
+
|
|
16
|
+
function quoteArrayElement(text: string): string {
|
|
17
|
+
if (!ARRAY_ELEMENT_NEEDS_QUOTES.test(text)) return text
|
|
18
|
+
return `"${text.replace(/[\\"]/g, (ch) => `\\${ch}`)}"`
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function arrayElement(value: unknown): string {
|
|
22
|
+
if (value === null || value === undefined) return "NULL"
|
|
23
|
+
if (Array.isArray(value)) return toPostgresArrayLiteral(value)
|
|
24
|
+
if (typeof value === "object") return quoteArrayElement(JSON.stringify(value))
|
|
25
|
+
return quoteArrayElement(String(value))
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* `["a", "b c"]` as PostgreSQL's array input syntax: `{a,"b c"}`.
|
|
30
|
+
*
|
|
31
|
+
* Elements are quoted only when PostgreSQL would otherwise split or reinterpret them, so the common
|
|
32
|
+
* case stays readable in logs. `null` is the SQL NULL; the string `"null"` is quoted to stay a string.
|
|
33
|
+
*/
|
|
34
|
+
export function toPostgresArrayLiteral(values: readonly unknown[]): string {
|
|
35
|
+
return `{${values.map(arrayElement).join(",")}}`
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The operand for `cs` and `cd`, chosen by the shape of the value as supabase-js does.
|
|
40
|
+
*
|
|
41
|
+
* - an array is a Postgres array column's operand, so it goes as an array literal;
|
|
42
|
+
* - a string is sent as written, for range types and literals the caller has already formed;
|
|
43
|
+
* - anything else is a jsonb operand, so it goes as JSON.
|
|
44
|
+
*
|
|
45
|
+
* For a jsonb column holding an array, pass `JSON.stringify([...])`: a bare array means a Postgres
|
|
46
|
+
* array here, which is the far more common column.
|
|
47
|
+
*/
|
|
48
|
+
export function containmentOperand(value: unknown): string {
|
|
49
|
+
if (typeof value === "string") return value
|
|
50
|
+
if (Array.isArray(value)) return toPostgresArrayLiteral(value)
|
|
51
|
+
return JSON.stringify(value)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function inListValue(value: unknown): string {
|
|
55
|
+
const text = String(value)
|
|
56
|
+
return IN_VALUE_NEEDS_QUOTES.test(text) ? `"${text.replace(/"/g, '\\"')}"` : text
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export abstract class FilterBuilder {
|
|
60
|
+
protected readonly params = new URLSearchParams()
|
|
61
|
+
|
|
62
|
+
private filter(column: string, operator: string, operand: string): this {
|
|
63
|
+
this.params.append(column, `${operator}.${operand}`)
|
|
64
|
+
return this
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
eq(column: string, value: unknown): this {
|
|
68
|
+
return this.filter(column, "eq", String(value))
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
neq(column: string, value: unknown): this {
|
|
72
|
+
return this.filter(column, "neq", String(value))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
gt(column: string, value: unknown): this {
|
|
76
|
+
return this.filter(column, "gt", String(value))
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
gte(column: string, value: unknown): this {
|
|
80
|
+
return this.filter(column, "gte", String(value))
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
lt(column: string, value: unknown): this {
|
|
84
|
+
return this.filter(column, "lt", String(value))
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
lte(column: string, value: unknown): this {
|
|
88
|
+
return this.filter(column, "lte", String(value))
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
like(column: string, pattern: string): this {
|
|
92
|
+
return this.filter(column, "like", pattern)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
ilike(column: string, pattern: string): this {
|
|
96
|
+
return this.filter(column, "ilike", pattern)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Values holding a comma or a parenthesis are quoted, so PostgREST does not split them. */
|
|
100
|
+
in(column: string, values: unknown[]): this {
|
|
101
|
+
return this.filter(column, "in", `(${values.map(inListValue).join(",")})`)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
is(column: string, value: null | boolean): this {
|
|
105
|
+
return this.filter(column, "is", String(value))
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
not(column: string, op: string, value: unknown): this {
|
|
109
|
+
return this.filter(column, "not", `${op}.${String(value)}`)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Rows whose array, range or jsonb `column` contains `value`. See `containmentOperand`. */
|
|
113
|
+
contains(column: string, value: unknown): this {
|
|
114
|
+
return this.filter(column, "cs", containmentOperand(value))
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Rows whose array, range or jsonb `column` is contained by `value`. See `containmentOperand`. */
|
|
118
|
+
containedBy(column: string, value: unknown): this {
|
|
119
|
+
return this.filter(column, "cd", containmentOperand(value))
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** One `eq` filter per entry: `match({ author: "ann", lang: "en" })`. */
|
|
123
|
+
match(query: Record<string, unknown>): this {
|
|
124
|
+
for (const [column, value] of Object.entries(query)) this.eq(column, value)
|
|
125
|
+
return this
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** PostgREST OR filter: pass conditions in PostgREST syntax, e.g. `"status.eq.active,owner_id.eq.123"`. */
|
|
129
|
+
or(filters: string): this {
|
|
130
|
+
this.params.append("or", `(${filters})`)
|
|
131
|
+
return this
|
|
132
|
+
}
|
|
133
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where `supatype push` writes a project's generated client, as an app imports it from the project
|
|
3
|
+
* root. Messages that tell someone to import the generated client name it from here, so they cannot
|
|
4
|
+
* drift from each other when the path changes.
|
|
5
|
+
*/
|
|
6
|
+
export const GENERATED_CLIENT_IMPORT = "./supatype/generated/client"
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Just enough of a GraphQL reader to say which response key each selected field lands on.
|
|
3
|
+
*
|
|
4
|
+
* The client needs a query's shape (aliases, fragments, nested selections) to know which keys of
|
|
5
|
+
* an answer hold a `JSON` scalar. It does not need argument values, variable types or directives,
|
|
6
|
+
* so those are skipped as balanced token runs rather than parsed. A document this reader does not
|
|
7
|
+
* understand (a type definition, a syntax error) comes back as null, and the caller then leaves the
|
|
8
|
+
* answer as the server sent it.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export type GraphqlOperationKind = "query" | "mutation" | "subscription"
|
|
12
|
+
|
|
13
|
+
export type GraphqlSelection =
|
|
14
|
+
| { readonly kind: "field"; readonly key: string; readonly name: string; readonly selections: readonly GraphqlSelection[] }
|
|
15
|
+
| { readonly kind: "spread"; readonly fragment: string }
|
|
16
|
+
| { readonly kind: "inline"; readonly typeCondition: string | null; readonly selections: readonly GraphqlSelection[] }
|
|
17
|
+
|
|
18
|
+
type GraphqlOperation = { readonly kind: GraphqlOperationKind; readonly selections: readonly GraphqlSelection[] }
|
|
19
|
+
type GraphqlFragment ={ readonly typeCondition: string; readonly selections: readonly GraphqlSelection[] }
|
|
20
|
+
|
|
21
|
+
export type GraphqlDocument = {
|
|
22
|
+
readonly operations: readonly GraphqlOperation[]
|
|
23
|
+
readonly fragments: ReadonlyMap<string, GraphqlFragment>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
type Token = { readonly kind: "punct" | "name" | "value"; readonly text: string }
|
|
27
|
+
type Read = { readonly token: Token | null; readonly end: number }
|
|
28
|
+
|
|
29
|
+
const PUNCTUATORS = new Set(["!", "$", "&", "(", ")", ":", "=", "@", "[", "]", "{", "|", "}"])
|
|
30
|
+
const IGNORED = /[\s,]/
|
|
31
|
+
const NAME = /[_A-Za-z][_0-9A-Za-z]*/y
|
|
32
|
+
const NUMBER = /-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/y
|
|
33
|
+
const LINE_END = /[\r\n]/g
|
|
34
|
+
const OPERATION_KINDS: ReadonlySet<string> = new Set(["query", "mutation", "subscription"])
|
|
35
|
+
|
|
36
|
+
/** Thrown inside the reader and caught at its edge: the document is not one it can read. */
|
|
37
|
+
class Unreadable extends Error {}
|
|
38
|
+
|
|
39
|
+
/** The document's operations and fragments, or null when it cannot be read. */
|
|
40
|
+
export function parseGraphqlDocument(source: string): GraphqlDocument | null {
|
|
41
|
+
try {
|
|
42
|
+
return new Parser(tokenize(source)).document()
|
|
43
|
+
} catch (e) {
|
|
44
|
+
if (e instanceof Unreadable) return null
|
|
45
|
+
throw e
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function tokenize(source: string): Token[] {
|
|
50
|
+
const tokens: Token[] = []
|
|
51
|
+
let at = 0
|
|
52
|
+
while (at < source.length) {
|
|
53
|
+
const read = readToken(source, at)
|
|
54
|
+
if (read.token !== null) tokens.push(read.token)
|
|
55
|
+
at = read.end
|
|
56
|
+
}
|
|
57
|
+
return tokens
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function readToken(source: string, at: number): Read {
|
|
61
|
+
const char = source.charAt(at)
|
|
62
|
+
if (IGNORED.test(char)) return { token: null, end: at + 1 }
|
|
63
|
+
if (char === "#") return { token: null, end: lineEnd(source, at) }
|
|
64
|
+
if (source.startsWith("...", at)) return { token: { kind: "punct", text: "..." }, end: at + 3 }
|
|
65
|
+
if (PUNCTUATORS.has(char)) return { token: { kind: "punct", text: char }, end: at + 1 }
|
|
66
|
+
if (source.startsWith('"""', at)) return { token: { kind: "value", text: '"""' }, end: blockStringEnd(source, at) }
|
|
67
|
+
if (char === '"') return { token: { kind: "value", text: '"' }, end: stringEnd(source, at) }
|
|
68
|
+
return matchWord(source, at)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function matchWord(source: string, at: number): Read {
|
|
72
|
+
for (const [pattern, kind] of [[NAME, "name"], [NUMBER, "value"]] as const) {
|
|
73
|
+
pattern.lastIndex = at
|
|
74
|
+
const match = pattern.exec(source)
|
|
75
|
+
if (match !== null) return { token: { kind, text: match[0] }, end: at + match[0].length }
|
|
76
|
+
}
|
|
77
|
+
throw new Unreadable(`unexpected character at ${at}`)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function lineEnd(source: string, at: number): number {
|
|
81
|
+
LINE_END.lastIndex = at
|
|
82
|
+
return LINE_END.exec(source) === null ? source.length : LINE_END.lastIndex - 1
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function blockStringEnd(source: string, at: number): number {
|
|
86
|
+
let i = at + 3
|
|
87
|
+
while (i < source.length) {
|
|
88
|
+
if (source.startsWith('\\"""', i)) i += 4
|
|
89
|
+
else if (source.startsWith('"""', i)) return i + 3
|
|
90
|
+
else i += 1
|
|
91
|
+
}
|
|
92
|
+
throw new Unreadable("unterminated block string")
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function stringEnd(source: string, at: number): number {
|
|
96
|
+
let i = at + 1
|
|
97
|
+
while (i < source.length) {
|
|
98
|
+
const char = source.charAt(i)
|
|
99
|
+
if (char === "\\") i += 2
|
|
100
|
+
else if (char === '"') return i + 1
|
|
101
|
+
else if (char === "\n" || char === "\r") break
|
|
102
|
+
else i += 1
|
|
103
|
+
}
|
|
104
|
+
throw new Unreadable("unterminated string")
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
class Parser {
|
|
108
|
+
private at = 0
|
|
109
|
+
constructor(private readonly tokens: readonly Token[]) {}
|
|
110
|
+
|
|
111
|
+
document(): GraphqlDocument {
|
|
112
|
+
const operations: GraphqlOperation[] = []
|
|
113
|
+
const fragments = new Map<string, GraphqlFragment>()
|
|
114
|
+
while (this.at < this.tokens.length) {
|
|
115
|
+
if (this.isName("fragment")) {
|
|
116
|
+
const [name, fragment] = this.fragment()
|
|
117
|
+
fragments.set(name, fragment)
|
|
118
|
+
} else {
|
|
119
|
+
operations.push(this.operation())
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return { operations, fragments }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
private operation(): GraphqlOperation {
|
|
126
|
+
if (this.isPunct("{")) return { kind: "query", selections: this.selectionSet() }
|
|
127
|
+
const kind = this.name()
|
|
128
|
+
if (!isOperationKind(kind)) throw new Unreadable(`not an operation: ${kind}`)
|
|
129
|
+
if (this.peek()?.kind === "name") this.name()
|
|
130
|
+
if (this.isPunct("(")) this.skipBalanced()
|
|
131
|
+
this.directives()
|
|
132
|
+
return { kind, selections: this.selectionSet() }
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private fragment(): [string, GraphqlFragment] {
|
|
136
|
+
this.name()
|
|
137
|
+
const name = this.name()
|
|
138
|
+
if (this.name() !== "on") throw new Unreadable("a fragment needs a type condition")
|
|
139
|
+
const typeCondition = this.name()
|
|
140
|
+
this.directives()
|
|
141
|
+
return [name, { typeCondition, selections: this.selectionSet() }]
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
private selectionSet(): GraphqlSelection[] {
|
|
145
|
+
this.punct("{")
|
|
146
|
+
const selections: GraphqlSelection[] = []
|
|
147
|
+
while (!this.acceptPunct("}")) selections.push(this.selection())
|
|
148
|
+
return selections
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
private selection(): GraphqlSelection {
|
|
152
|
+
if (!this.acceptPunct("...")) return this.field()
|
|
153
|
+
if (this.isName("on")) {
|
|
154
|
+
this.name()
|
|
155
|
+
const typeCondition = this.name()
|
|
156
|
+
this.directives()
|
|
157
|
+
return { kind: "inline", typeCondition, selections: this.selectionSet() }
|
|
158
|
+
}
|
|
159
|
+
if (this.peek()?.kind === "name") {
|
|
160
|
+
const fragment = this.name()
|
|
161
|
+
this.directives()
|
|
162
|
+
return { kind: "spread", fragment }
|
|
163
|
+
}
|
|
164
|
+
this.directives()
|
|
165
|
+
return { kind: "inline", typeCondition: null, selections: this.selectionSet() }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
private field(): GraphqlSelection {
|
|
169
|
+
const first = this.name()
|
|
170
|
+
const name = this.acceptPunct(":") ? this.name() : first
|
|
171
|
+
if (this.isPunct("(")) this.skipBalanced()
|
|
172
|
+
this.directives()
|
|
173
|
+
const selections = this.isPunct("{") ? this.selectionSet() : []
|
|
174
|
+
return { kind: "field", key: first, name, selections }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private directives(): void {
|
|
178
|
+
while (this.acceptPunct("@")) {
|
|
179
|
+
this.name()
|
|
180
|
+
if (this.isPunct("(")) this.skipBalanced()
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Skips `( ... )`, nested parentheses included. Strings are single tokens, so a `)` in one is safe. */
|
|
185
|
+
private skipBalanced(): void {
|
|
186
|
+
let depth = 0
|
|
187
|
+
do {
|
|
188
|
+
const token = this.next()
|
|
189
|
+
if (token.kind === "punct" && token.text === "(") depth += 1
|
|
190
|
+
if (token.kind === "punct" && token.text === ")") depth -= 1
|
|
191
|
+
} while (depth > 0)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
private peek(): Token | undefined {
|
|
195
|
+
return this.tokens[this.at]
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
private next(): Token {
|
|
199
|
+
const token = this.tokens[this.at]
|
|
200
|
+
if (token === undefined) throw new Unreadable("the document ends early")
|
|
201
|
+
this.at += 1
|
|
202
|
+
return token
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
private name(): string {
|
|
206
|
+
const token = this.next()
|
|
207
|
+
if (token.kind !== "name") throw new Unreadable(`expected a name, found ${token.text}`)
|
|
208
|
+
return token.text
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
private punct(text: string): void {
|
|
212
|
+
if (!this.acceptPunct(text)) throw new Unreadable(`expected ${text}`)
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
private acceptPunct(text: string): boolean {
|
|
216
|
+
if (!this.isPunct(text)) return false
|
|
217
|
+
this.at += 1
|
|
218
|
+
return true
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
private isPunct(text: string): boolean {
|
|
222
|
+
const token = this.peek()
|
|
223
|
+
return token?.kind === "punct" && token.text === text
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
private isName(text: string): boolean {
|
|
227
|
+
const token = this.peek()
|
|
228
|
+
return token?.kind === "name" && token.text === text
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function isOperationKind(text: string): text is GraphqlOperationKind {
|
|
233
|
+
return OPERATION_KINDS.has(text)
|
|
234
|
+
}
|