@supacloud/js 0.29.0 → 0.31.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/README.md +373 -104
- package/dist/api-error.d.ts +6 -0
- package/dist/artifact-fetch.d.ts +6 -0
- package/dist/artifact-link.d.ts +8 -0
- package/dist/artifact-read.d.ts +13 -0
- package/dist/artifact-register.d.ts +14 -0
- package/dist/artifact-rpc.d.ts +2 -0
- package/dist/artifacts.d.ts +3 -0
- package/dist/auth-fetch.d.ts +4 -2
- package/dist/bounded-rpc-fetch.d.ts +2 -0
- package/dist/command-fetch.d.ts +6 -0
- package/dist/commands.d.ts +10 -0
- package/dist/index.d.ts +80 -278
- package/dist/index.js +3031 -668
- package/dist/oauth-clients.d.ts +95 -0
- package/dist/oauth-server.d.ts +104 -0
- package/dist/queue-rpc.d.ts +54 -0
- package/dist/workflow-advance.d.ts +8 -0
- package/dist/workflow-attempt.d.ts +4 -0
- package/dist/workflow-cancel.d.ts +14 -0
- package/dist/workflow-claim.d.ts +12 -0
- package/dist/workflow-complete.d.ts +8 -0
- package/dist/workflow-events.d.ts +14 -0
- package/dist/workflow-fail.d.ts +8 -0
- package/dist/workflow-fetch.d.ts +9 -0
- package/dist/workflow-json.d.ts +2 -0
- package/dist/workflow-retry.d.ts +8 -0
- package/dist/workflow-rpc.d.ts +6 -0
- package/dist/workflow-run.d.ts +8 -0
- package/dist/workflow-start.d.ts +8 -0
- package/dist/workflow-timestamp.d.ts +1 -0
- package/dist/workflows.d.ts +9 -0
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,114 +1,2313 @@
|
|
|
1
|
-
// src/
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { FunctionsHttpError } from "@supabase/supabase-js";
|
|
3
|
+
|
|
4
|
+
// src/workflow-rpc.ts
|
|
5
|
+
function invokeWorkflowMutation(supabase, functionName, request, unconfirmed) {
|
|
6
|
+
return invokeWorkflowRpc(supabase, functionName, request, unconfirmed);
|
|
7
|
+
}
|
|
8
|
+
function invokeWorkflowRead(supabase, functionName, request, invalid) {
|
|
9
|
+
return invokeWorkflowRpc(supabase, functionName, request, invalid);
|
|
10
|
+
}
|
|
11
|
+
async function invokeWorkflowRpc(supabase, functionName, request, failure) {
|
|
12
|
+
const controller = new AbortController;
|
|
13
|
+
let timer;
|
|
14
|
+
const deadline = new Promise((_, reject) => {
|
|
15
|
+
timer = setTimeout(() => {
|
|
16
|
+
reject(failure());
|
|
17
|
+
controller.abort();
|
|
18
|
+
}, 15000);
|
|
19
|
+
});
|
|
20
|
+
let result;
|
|
21
|
+
try {
|
|
22
|
+
const pending = supabase.rpc(functionName, { request }).retry(false).abortSignal(controller.signal);
|
|
23
|
+
result = await Promise.race([pending, deadline]);
|
|
24
|
+
} catch {
|
|
25
|
+
throw failure();
|
|
26
|
+
} finally {
|
|
27
|
+
clearTimeout(timer);
|
|
28
|
+
}
|
|
29
|
+
if (result.error && result.status >= 400 && result.status < 500)
|
|
30
|
+
throw result.error;
|
|
31
|
+
if (result.error || result.status !== 200)
|
|
32
|
+
throw failure();
|
|
33
|
+
return result.data;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// src/api-error.ts
|
|
37
|
+
class SupaCloudApiError extends Error {
|
|
38
|
+
status;
|
|
39
|
+
code;
|
|
40
|
+
responseBody;
|
|
41
|
+
constructor(message, status, responseBody) {
|
|
42
|
+
super(message);
|
|
43
|
+
this.name = "SupaCloudApiError";
|
|
44
|
+
this.status = status;
|
|
45
|
+
this.responseBody = responseBody;
|
|
46
|
+
this.code = responseBody && typeof responseBody === "object" && !Array.isArray(responseBody) && Object.hasOwn(responseBody, "code") && "code" in responseBody && typeof responseBody.code === "string" ? responseBody.code : null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// src/queue-rpc.ts
|
|
51
|
+
class SupaCloudQueueError extends SupaCloudApiError {
|
|
52
|
+
mutationMayHaveApplied;
|
|
53
|
+
constructor(mutationMayHaveApplied = false, code = "QUEUE_CONTRACT_INVALID") {
|
|
54
|
+
super("Queue input or response could not be validated", 0, {
|
|
55
|
+
code,
|
|
56
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
57
|
+
});
|
|
58
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
59
|
+
this.name = "SupaCloudQueueError";
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function invalid() {
|
|
63
|
+
throw new SupaCloudQueueError;
|
|
64
|
+
}
|
|
65
|
+
function isRecord(value) {
|
|
66
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
67
|
+
}
|
|
68
|
+
function record(value) {
|
|
69
|
+
return isRecord(value) ? value : invalid();
|
|
70
|
+
}
|
|
71
|
+
function queueMessageId(value) {
|
|
72
|
+
if (typeof value === "number") {
|
|
73
|
+
return Number.isSafeInteger(value) && value > 0 ? String(value) : invalid();
|
|
74
|
+
}
|
|
75
|
+
if (typeof value !== "string" || !/^[1-9][0-9]{0,18}$/.test(value) || BigInt(value) > 9223372036854775807n)
|
|
76
|
+
return invalid();
|
|
77
|
+
return value;
|
|
78
|
+
}
|
|
79
|
+
function queueInteger(value, min, max = 2147483647) {
|
|
80
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= min && value <= max ? value : invalid();
|
|
81
|
+
}
|
|
82
|
+
function queueSeconds(options) {
|
|
83
|
+
record(options);
|
|
84
|
+
const candidates = [];
|
|
85
|
+
for (const value of [options.sleepSeconds, options.sleep_seconds, options.visibilityTimeoutSec]) {
|
|
86
|
+
if (value !== undefined)
|
|
87
|
+
candidates.push(queueInteger(value, 0));
|
|
88
|
+
}
|
|
89
|
+
if (options.delayMs !== undefined) {
|
|
90
|
+
candidates.push(Math.floor(queueInteger(options.delayMs, 0, 2147483647 * 1000) / 1000));
|
|
91
|
+
}
|
|
92
|
+
const first = candidates[0] ?? 0;
|
|
93
|
+
if (candidates.some((value) => value !== first))
|
|
94
|
+
return invalid();
|
|
95
|
+
return first;
|
|
96
|
+
}
|
|
97
|
+
function queueReadCount(options, single = false) {
|
|
98
|
+
const data = record(options);
|
|
99
|
+
const n = data.n === undefined ? undefined : queueInteger(data.n, 1, 1e4);
|
|
100
|
+
const count = data.count === undefined ? undefined : queueInteger(data.count, 1, 1e4);
|
|
101
|
+
if (n !== undefined && count !== undefined && n !== count)
|
|
102
|
+
return invalid();
|
|
103
|
+
const result = n ?? count ?? 1;
|
|
104
|
+
return !single || result === 1 ? result : invalid();
|
|
105
|
+
}
|
|
106
|
+
function queueJsonSnapshot(value) {
|
|
107
|
+
const ancestors = new Set;
|
|
108
|
+
let nodes = 0, characters = 0;
|
|
109
|
+
function visit(input, depth) {
|
|
110
|
+
if (++nodes > 1e4 || depth > 64)
|
|
111
|
+
return invalid();
|
|
112
|
+
if (input === null || typeof input === "boolean")
|
|
113
|
+
return input;
|
|
114
|
+
if (typeof input === "number")
|
|
115
|
+
return Number.isFinite(input) ? input : invalid();
|
|
116
|
+
if (typeof input === "string") {
|
|
117
|
+
characters += input.length;
|
|
118
|
+
return characters <= 1048576 ? input : invalid();
|
|
119
|
+
}
|
|
120
|
+
if (typeof input !== "object" || ancestors.has(input))
|
|
121
|
+
return invalid();
|
|
122
|
+
if (!Array.isArray(input) && Object.getPrototypeOf(input) !== Object.prototype && Object.getPrototypeOf(input) !== null)
|
|
123
|
+
return invalid();
|
|
124
|
+
ancestors.add(input);
|
|
125
|
+
try {
|
|
126
|
+
let property = function(key) {
|
|
127
|
+
const descriptor = properties[key];
|
|
128
|
+
if (!descriptor || !("value" in descriptor))
|
|
129
|
+
return invalid();
|
|
130
|
+
const item = descriptor.value;
|
|
131
|
+
return visit(item, depth + 1);
|
|
132
|
+
};
|
|
133
|
+
if (Object.getOwnPropertySymbols(input).length !== 0)
|
|
134
|
+
return invalid();
|
|
135
|
+
const properties = Object.getOwnPropertyDescriptors(input);
|
|
136
|
+
if (Array.isArray(input)) {
|
|
137
|
+
if (input.length > 1e4 || Object.keys(input).length !== input.length)
|
|
138
|
+
return invalid();
|
|
139
|
+
return Array.from({ length: input.length }, (_, index) => property(String(index)));
|
|
140
|
+
}
|
|
141
|
+
return Object.fromEntries(Object.keys(input).map((key) => {
|
|
142
|
+
characters += key.length;
|
|
143
|
+
if (characters > 1048576)
|
|
144
|
+
return invalid();
|
|
145
|
+
return [key, property(key)];
|
|
146
|
+
}));
|
|
147
|
+
} finally {
|
|
148
|
+
ancestors.delete(input);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return visit(value, 0);
|
|
152
|
+
}
|
|
153
|
+
function queueRpcIds(value, expected) {
|
|
154
|
+
if (!Array.isArray(value) || value.length !== expected)
|
|
155
|
+
return invalid();
|
|
156
|
+
const ids = value.map((id) => queueMessageId(id));
|
|
157
|
+
return new Set(ids).size === ids.length ? ids : invalid();
|
|
158
|
+
}
|
|
159
|
+
function queueRpcId(value) {
|
|
160
|
+
const id = queueRpcIds(value, 1)[0];
|
|
161
|
+
return id === undefined ? invalid() : id;
|
|
162
|
+
}
|
|
163
|
+
function queueRpcBoolean(value) {
|
|
164
|
+
return typeof value === "boolean" ? value : invalid();
|
|
165
|
+
}
|
|
166
|
+
function optionalText(value) {
|
|
167
|
+
return typeof value === "string" && value.length > 0 && value.length <= 4096 ? value : invalid();
|
|
168
|
+
}
|
|
169
|
+
function jsonEqual(left, right) {
|
|
170
|
+
if (left === right)
|
|
171
|
+
return true;
|
|
172
|
+
if (Array.isArray(left)) {
|
|
173
|
+
return Array.isArray(right) && left.length === right.length && left.every((item, index) => right[index] !== undefined && jsonEqual(item, right[index]));
|
|
174
|
+
}
|
|
175
|
+
if (left === null || right === null || typeof left !== "object" || typeof right !== "object" || Array.isArray(right))
|
|
176
|
+
return false;
|
|
177
|
+
const entries = Object.entries(left);
|
|
178
|
+
return entries.length === Object.keys(right).length && entries.every(([key, value]) => Object.hasOwn(right, key) && right[key] !== undefined && jsonEqual(value, right[key]));
|
|
179
|
+
}
|
|
180
|
+
function queueMessage(value, expected = {}) {
|
|
181
|
+
const data = record(value);
|
|
182
|
+
const id = queueMessageId(data.msg_id);
|
|
183
|
+
if (expected.messageId !== undefined && expected.messageId !== id || data.id !== undefined && queueMessageId(data.id) !== id)
|
|
184
|
+
return invalid();
|
|
185
|
+
const hasMessage = Object.hasOwn(data, "message");
|
|
186
|
+
const hasPayload = Object.hasOwn(data, "payload");
|
|
187
|
+
if (!hasMessage && (!hasPayload || expected.rpc))
|
|
188
|
+
return invalid();
|
|
189
|
+
const message = queueJsonSnapshot(hasMessage ? data.message : data.payload);
|
|
190
|
+
if (hasMessage && hasPayload && !jsonEqual(message, queueJsonSnapshot(data.payload)))
|
|
191
|
+
return invalid();
|
|
192
|
+
const result = { id, msg_id: id, message, payload: message };
|
|
193
|
+
if (data.read_ct !== undefined || expected.rpc)
|
|
194
|
+
result.read_ct = queueInteger(data.read_ct, 0);
|
|
195
|
+
for (const field of ["enqueued_at", "vt"]) {
|
|
196
|
+
if (data[field] === undefined && !expected.rpc)
|
|
197
|
+
continue;
|
|
198
|
+
const timestamp = data[field];
|
|
199
|
+
if (timestamp === null && !expected.rpc) {
|
|
200
|
+
result[field] = null;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
const text = optionalText(timestamp);
|
|
204
|
+
if (!Number.isFinite(Date.parse(text)))
|
|
205
|
+
return invalid();
|
|
206
|
+
result[field] = text;
|
|
207
|
+
}
|
|
208
|
+
for (const field of ["status", "queue_name", "task_type"]) {
|
|
209
|
+
if (data[field] !== undefined)
|
|
210
|
+
result[field] = optionalText(data[field]);
|
|
211
|
+
}
|
|
212
|
+
if (expected.queueName !== undefined) {
|
|
213
|
+
if (result.queue_name !== undefined && result.queue_name !== expected.queueName || result.task_type !== undefined && result.task_type !== `queue:${expected.queueName}`)
|
|
214
|
+
return invalid();
|
|
215
|
+
result.queue_name = expected.queueName;
|
|
216
|
+
result.task_type = `queue:${expected.queueName}`;
|
|
217
|
+
}
|
|
218
|
+
if (expected.status !== undefined) {
|
|
219
|
+
if (result.status !== undefined && result.status !== expected.status)
|
|
220
|
+
return invalid();
|
|
221
|
+
result.status = expected.status;
|
|
222
|
+
}
|
|
223
|
+
return result;
|
|
224
|
+
}
|
|
225
|
+
function queueRpcMessages(queueName, value, max, status) {
|
|
226
|
+
if (!Array.isArray(value) || value.length > max)
|
|
227
|
+
return invalid();
|
|
228
|
+
const result = value.map((row) => queueMessage(row, { queueName, status, rpc: true }));
|
|
229
|
+
return new Set(result.map((row) => row.id)).size === result.length ? result : invalid();
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// src/workflow-claim.ts
|
|
233
|
+
class SupaCloudWorkflowClaimInputError extends SupaCloudApiError {
|
|
234
|
+
mutationMayHaveApplied = false;
|
|
235
|
+
constructor() {
|
|
236
|
+
super("Workflow claim request could not be validated", 0, {
|
|
237
|
+
code: "WORKFLOW_CLAIM_INPUT_INVALID",
|
|
238
|
+
mutation_may_have_applied: false
|
|
239
|
+
});
|
|
240
|
+
this.name = "SupaCloudWorkflowClaimInputError";
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
function captureWorkflowClaimRequest(value) {
|
|
244
|
+
const fail = () => {
|
|
245
|
+
throw new SupaCloudWorkflowClaimInputError;
|
|
246
|
+
};
|
|
247
|
+
try {
|
|
248
|
+
if (value === null || typeof value !== "object" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null || Object.getOwnPropertySymbols(value).length !== 0)
|
|
249
|
+
return fail();
|
|
250
|
+
const properties = Object.getOwnPropertyDescriptors(value);
|
|
251
|
+
for (const name of Object.keys(properties)) {
|
|
252
|
+
const descriptor = properties[name];
|
|
253
|
+
if (name !== "workerId" && name !== "visibilityTimeoutSeconds" || !descriptor || !descriptor.enumerable || !("value" in descriptor))
|
|
254
|
+
return fail();
|
|
255
|
+
}
|
|
256
|
+
const worker = properties.workerId?.value;
|
|
257
|
+
const timeout = properties.visibilityTimeoutSeconds?.value;
|
|
258
|
+
if (typeof worker !== "string")
|
|
259
|
+
return fail();
|
|
260
|
+
const workerId = worker.replace(/^ +| +$/g, "");
|
|
261
|
+
let characters = 0;
|
|
262
|
+
for (const character of workerId) {
|
|
263
|
+
const point = character.codePointAt(0);
|
|
264
|
+
if (++characters > 200 || point === undefined || point === 0 || point >= 55296 && point <= 57343)
|
|
265
|
+
return fail();
|
|
266
|
+
}
|
|
267
|
+
if (characters === 0)
|
|
268
|
+
return fail();
|
|
269
|
+
const visibilityTimeoutSeconds = timeout === undefined ? 300 : timeout;
|
|
270
|
+
if (typeof visibilityTimeoutSeconds !== "number" || !Number.isSafeInteger(visibilityTimeoutSeconds) || visibilityTimeoutSeconds < 15 || visibilityTimeoutSeconds > 3600)
|
|
271
|
+
return fail();
|
|
272
|
+
return { workerId, visibilityTimeoutSeconds };
|
|
273
|
+
} catch {
|
|
274
|
+
return fail();
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
class SupaCloudWorkflowClaimError extends SupaCloudApiError {
|
|
279
|
+
mutationMayHaveApplied = true;
|
|
280
|
+
constructor() {
|
|
281
|
+
super("Workflow claim response could not be validated", 0, {
|
|
282
|
+
code: "WORKFLOW_CLAIM_UNCONFIRMED",
|
|
283
|
+
mutation_may_have_applied: true
|
|
284
|
+
});
|
|
285
|
+
this.name = "SupaCloudWorkflowClaimError";
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
function invalid2() {
|
|
289
|
+
throw new SupaCloudWorkflowClaimError;
|
|
290
|
+
}
|
|
291
|
+
function record2(value) {
|
|
292
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : invalid2();
|
|
293
|
+
}
|
|
294
|
+
function text(value) {
|
|
295
|
+
return typeof value === "string" && value.length > 0 ? value : invalid2();
|
|
296
|
+
}
|
|
297
|
+
function key(value) {
|
|
298
|
+
const result = text(value);
|
|
299
|
+
return /^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/.test(result) ? result : invalid2();
|
|
300
|
+
}
|
|
301
|
+
function version(value) {
|
|
302
|
+
const result = text(value);
|
|
303
|
+
let characters = 0;
|
|
304
|
+
for (const character of result) {
|
|
305
|
+
const point = character.codePointAt(0);
|
|
306
|
+
if (++characters > 80 || point === undefined || point === 0 || point >= 55296 && point <= 57343)
|
|
307
|
+
return invalid2();
|
|
308
|
+
}
|
|
309
|
+
return result;
|
|
310
|
+
}
|
|
311
|
+
function uuid(value) {
|
|
312
|
+
const result = text(value);
|
|
313
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(result) ? result : invalid2();
|
|
314
|
+
}
|
|
315
|
+
function id(value) {
|
|
316
|
+
return typeof value === "string" && /^[1-9][0-9]{0,18}$/.test(value) && BigInt(value) <= 9223372036854775807n ? value : invalid2();
|
|
317
|
+
}
|
|
318
|
+
function positiveInteger(value) {
|
|
319
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 && value <= 2147483647 ? value : invalid2();
|
|
320
|
+
}
|
|
321
|
+
function decodeWorkflowClaim(value, expectedWorkerId) {
|
|
322
|
+
if (value === null)
|
|
323
|
+
return null;
|
|
324
|
+
try {
|
|
325
|
+
const data = record2(queueJsonSnapshot(value));
|
|
326
|
+
const messageId = id(data.messageId);
|
|
327
|
+
if (data.status === "discarded") {
|
|
328
|
+
const reason = text(data.reason);
|
|
329
|
+
return {
|
|
330
|
+
status: "discarded",
|
|
331
|
+
reason,
|
|
332
|
+
messageId,
|
|
333
|
+
...data.runId === undefined ? {} : { runId: uuid(data.runId) },
|
|
334
|
+
...data.stepId === undefined ? {} : { stepId: uuid(data.stepId) }
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
const runId = uuid(data.runId);
|
|
338
|
+
const stepId = uuid(data.stepId);
|
|
339
|
+
const stepKey = key(data.stepKey);
|
|
340
|
+
const attempt = positiveInteger(data.attempt);
|
|
341
|
+
const maxAttempts = positiveInteger(data.maxAttempts);
|
|
342
|
+
if (maxAttempts > 100)
|
|
343
|
+
return invalid2();
|
|
344
|
+
if (data.status === "dead_lettered" && attempt > maxAttempts) {
|
|
345
|
+
return { status: "dead_lettered", runId, stepId, stepKey, messageId, attempt, maxAttempts };
|
|
346
|
+
}
|
|
347
|
+
if (data.status !== "claimed" || attempt > maxAttempts || data.workerId !== expectedWorkerId)
|
|
348
|
+
return invalid2();
|
|
349
|
+
return {
|
|
350
|
+
status: "claimed",
|
|
351
|
+
runId,
|
|
352
|
+
stepId,
|
|
353
|
+
stepKey,
|
|
354
|
+
messageId,
|
|
355
|
+
attempt,
|
|
356
|
+
maxAttempts,
|
|
357
|
+
workflowName: key(data.workflowName),
|
|
358
|
+
workflowVersion: version(data.workflowVersion),
|
|
359
|
+
workerId: text(data.workerId),
|
|
360
|
+
input: record2(data.input)
|
|
361
|
+
};
|
|
362
|
+
} catch {
|
|
363
|
+
return invalid2();
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// src/workflow-timestamp.ts
|
|
368
|
+
function isWorkflowTimestamp(value) {
|
|
369
|
+
if (typeof value !== "string" || value.length > 40 || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/.test(value))
|
|
370
|
+
return false;
|
|
371
|
+
const year = Number(value.slice(0, 4));
|
|
372
|
+
const month = Number(value.slice(5, 7));
|
|
373
|
+
const day = Number(value.slice(8, 10));
|
|
374
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
375
|
+
const days = month === 2 ? leap ? 29 : 28 : [4, 6, 9, 11].includes(month) ? 30 : 31;
|
|
376
|
+
return month >= 1 && month <= 12 && day >= 1 && day <= days && Number(value.slice(11, 13)) <= 23 && Number(value.slice(14, 16)) <= 59 && Number(value.slice(17, 19)) <= 59 && Number.isFinite(Date.parse(value));
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// src/workflow-run.ts
|
|
380
|
+
class SupaCloudWorkflowReadError extends SupaCloudApiError {
|
|
381
|
+
mutationMayHaveApplied = false;
|
|
382
|
+
constructor(code = "WORKFLOW_READ_INVALID") {
|
|
383
|
+
super("Workflow read could not be validated", 0, {
|
|
384
|
+
code,
|
|
385
|
+
mutation_may_have_applied: false
|
|
386
|
+
});
|
|
387
|
+
this.name = "SupaCloudWorkflowReadError";
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
function invalid3() {
|
|
391
|
+
throw new SupaCloudWorkflowReadError;
|
|
392
|
+
}
|
|
393
|
+
var uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
394
|
+
function captureWorkflowRunId(value) {
|
|
395
|
+
if (typeof value !== "string" || !uuidPattern.test(value.toLowerCase())) {
|
|
396
|
+
throw new SupaCloudWorkflowReadError("WORKFLOW_READ_INPUT_INVALID");
|
|
397
|
+
}
|
|
398
|
+
return value.toLowerCase();
|
|
399
|
+
}
|
|
400
|
+
function uuid2(value) {
|
|
401
|
+
return typeof value === "string" && uuidPattern.test(value) ? value : invalid3();
|
|
402
|
+
}
|
|
403
|
+
function record3(value) {
|
|
404
|
+
if (value !== null && typeof value === "object" && !Array.isArray(value))
|
|
405
|
+
return value;
|
|
406
|
+
return invalid3();
|
|
407
|
+
}
|
|
408
|
+
function text2(value, min = 0, max = 4000) {
|
|
409
|
+
if (typeof value !== "string")
|
|
410
|
+
return invalid3();
|
|
411
|
+
let count = 0;
|
|
412
|
+
for (const character of value) {
|
|
413
|
+
const point = character.codePointAt(0);
|
|
414
|
+
if (++count > max || point === 0 || point !== undefined && point >= 55296 && point <= 57343)
|
|
415
|
+
return invalid3();
|
|
416
|
+
}
|
|
417
|
+
return count >= min ? value : invalid3();
|
|
418
|
+
}
|
|
419
|
+
function key2(value) {
|
|
420
|
+
const result = text2(value, 1, 120);
|
|
421
|
+
return /^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/.test(result) ? result : invalid3();
|
|
422
|
+
}
|
|
423
|
+
function id2(value) {
|
|
424
|
+
return typeof value === "string" && /^[1-9][0-9]{0,18}$/.test(value) && BigInt(value) <= 9223372036854775807n ? value : invalid3();
|
|
425
|
+
}
|
|
426
|
+
function integer(value, min, max = 2147483647) {
|
|
427
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= min && value <= max ? value : invalid3();
|
|
428
|
+
}
|
|
429
|
+
function timestamp(value) {
|
|
430
|
+
return isWorkflowTimestamp(value) ? value : invalid3();
|
|
431
|
+
}
|
|
432
|
+
function nullable(value, decode) {
|
|
433
|
+
return value === null ? null : decode(value);
|
|
434
|
+
}
|
|
435
|
+
function state(value, values) {
|
|
436
|
+
for (const candidate of values)
|
|
437
|
+
if (candidate === value)
|
|
438
|
+
return candidate;
|
|
439
|
+
return invalid3();
|
|
440
|
+
}
|
|
441
|
+
function step(value) {
|
|
442
|
+
const data = record3(value);
|
|
443
|
+
return {
|
|
444
|
+
stepId: uuid2(data.stepId),
|
|
445
|
+
stepKey: key2(data.stepKey),
|
|
446
|
+
status: state(data.status, ["queued", "running", "completed", "failed", "dead_lettered", "cancelled"]),
|
|
447
|
+
input: record3(data.input),
|
|
448
|
+
output: record3(data.output),
|
|
449
|
+
errorMessage: text2(data.errorMessage),
|
|
450
|
+
attempts: integer(data.attempts, 0),
|
|
451
|
+
maxAttempts: integer(data.maxAttempts, 1, 100),
|
|
452
|
+
retryDelaySeconds: integer(data.retryDelaySeconds, 0, 86400),
|
|
453
|
+
queueMessageId: id2(data.queueMessageId),
|
|
454
|
+
claimedBy: nullable(data.claimedBy, (value) => text2(value, 1, 200)),
|
|
455
|
+
claimedAt: nullable(data.claimedAt, timestamp),
|
|
456
|
+
completedAt: nullable(data.completedAt, timestamp),
|
|
457
|
+
nextStepKey: nullable(data.nextStepKey, key2),
|
|
458
|
+
createdAt: timestamp(data.createdAt),
|
|
459
|
+
updatedAt: timestamp(data.updatedAt)
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
function validateStepSuccessors(steps) {
|
|
463
|
+
if (steps.length === 0)
|
|
464
|
+
return invalid3();
|
|
465
|
+
const byKey = new Map(steps.map((item) => [item.stepKey, item]));
|
|
466
|
+
const successors = new Set;
|
|
467
|
+
for (const item of steps) {
|
|
468
|
+
if (item.nextStepKey !== null) {
|
|
469
|
+
if (item.status !== "completed" || item.completedAt === null || !byKey.has(item.nextStepKey) || successors.has(item.nextStepKey))
|
|
470
|
+
return invalid3();
|
|
471
|
+
successors.add(item.nextStepKey);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
const roots = steps.filter((item) => !successors.has(item.stepKey));
|
|
475
|
+
if (roots.length !== 1)
|
|
476
|
+
return invalid3();
|
|
477
|
+
const visited = new Set;
|
|
478
|
+
let current = roots[0];
|
|
479
|
+
while (current) {
|
|
480
|
+
if (visited.has(current.stepKey))
|
|
481
|
+
return invalid3();
|
|
482
|
+
visited.add(current.stepKey);
|
|
483
|
+
current = current.nextStepKey === null ? undefined : byKey.get(current.nextStepKey);
|
|
484
|
+
}
|
|
485
|
+
if (visited.size !== steps.length)
|
|
486
|
+
return invalid3();
|
|
487
|
+
}
|
|
488
|
+
function validateLifecycle(run) {
|
|
489
|
+
const active = run.status === "queued" || run.status === "running";
|
|
490
|
+
if (active !== (run.completedAt === null))
|
|
491
|
+
return invalid3();
|
|
492
|
+
if ((run.status === "running" || run.status === "completed") && run.startedAt === null)
|
|
493
|
+
return invalid3();
|
|
494
|
+
if (run.status === "queued" && (run.startedAt !== null || run.steps.length !== 1 || run.steps[0]?.status !== "queued" || run.steps[0]?.attempts !== 0))
|
|
495
|
+
return invalid3();
|
|
496
|
+
if ((active || run.status === "completed") && run.errorMessage !== "")
|
|
497
|
+
return invalid3();
|
|
498
|
+
let activeSteps = 0;
|
|
499
|
+
let terminalSteps = 0;
|
|
500
|
+
for (const item of run.steps) {
|
|
501
|
+
const stepActive = item.status === "queued" || item.status === "running";
|
|
502
|
+
if (stepActive)
|
|
503
|
+
activeSteps++;
|
|
504
|
+
if (stepActive !== (item.completedAt === null))
|
|
505
|
+
return invalid3();
|
|
506
|
+
if (item.claimedBy === null !== (item.claimedAt === null))
|
|
507
|
+
return invalid3();
|
|
508
|
+
if (item.claimedBy !== null && (item.attempts === 0 || run.startedAt === null))
|
|
509
|
+
return invalid3();
|
|
510
|
+
if (item.status === "dead_lettered") {
|
|
511
|
+
if (item.attempts < item.maxAttempts || item.claimedBy === null && item.attempts === item.maxAttempts)
|
|
512
|
+
return invalid3();
|
|
513
|
+
} else if (item.attempts > item.maxAttempts || item.attempts > 0 && item.claimedBy === null)
|
|
514
|
+
return invalid3();
|
|
515
|
+
if (item.status === "queued" && item.attempts >= item.maxAttempts)
|
|
516
|
+
return invalid3();
|
|
517
|
+
if (["running", "completed", "failed"].includes(item.status) && (item.attempts === 0 || item.retryDelaySeconds !== 0))
|
|
518
|
+
return invalid3();
|
|
519
|
+
if (item.attempts === 0 && item.retryDelaySeconds !== 0)
|
|
520
|
+
return invalid3();
|
|
521
|
+
if (item.status === "completed" && item.errorMessage !== "")
|
|
522
|
+
return invalid3();
|
|
523
|
+
if (item.status === "failed" || item.status === "dead_lettered" || item.status === "cancelled") {
|
|
524
|
+
terminalSteps++;
|
|
525
|
+
const expected = item.status === "cancelled" ? "cancelled" : "failed";
|
|
526
|
+
if (run.status !== expected || item.errorMessage === "" || item.errorMessage !== run.errorMessage)
|
|
527
|
+
return invalid3();
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
if (activeSteps !== (active ? 1 : 0))
|
|
531
|
+
return invalid3();
|
|
532
|
+
if (terminalSteps !== (run.status === "failed" || run.status === "cancelled" ? 1 : 0))
|
|
533
|
+
return invalid3();
|
|
534
|
+
}
|
|
535
|
+
function decodeWorkflowRun(value, expectedRunId, allowIdempotent = false) {
|
|
536
|
+
if (value === null)
|
|
537
|
+
return null;
|
|
538
|
+
try {
|
|
539
|
+
const data = record3(queueJsonSnapshot(value));
|
|
540
|
+
const runId = uuid2(data.runId);
|
|
541
|
+
if (runId !== expectedRunId || typeof data.idempotent !== "boolean" || !allowIdempotent && data.idempotent || !Array.isArray(data.steps))
|
|
542
|
+
return invalid3();
|
|
543
|
+
const steps = data.steps.map(step);
|
|
544
|
+
for (const field of ["stepId", "stepKey", "queueMessageId"]) {
|
|
545
|
+
if (new Set(steps.map((item) => item[field])).size !== steps.length)
|
|
546
|
+
return invalid3();
|
|
547
|
+
}
|
|
548
|
+
validateStepSuccessors(steps);
|
|
549
|
+
const run = {
|
|
550
|
+
runId,
|
|
551
|
+
workflowName: key2(data.workflowName),
|
|
552
|
+
workflowVersion: text2(data.workflowVersion, 1, 80),
|
|
553
|
+
status: state(data.status, ["queued", "running", "completed", "failed", "cancelled"]),
|
|
554
|
+
input: record3(data.input),
|
|
555
|
+
output: record3(data.output),
|
|
556
|
+
errorMessage: text2(data.errorMessage),
|
|
557
|
+
rowVersion: id2(data.rowVersion),
|
|
558
|
+
createdAt: timestamp(data.createdAt),
|
|
559
|
+
startedAt: nullable(data.startedAt, timestamp),
|
|
560
|
+
completedAt: nullable(data.completedAt, timestamp),
|
|
561
|
+
updatedAt: timestamp(data.updatedAt),
|
|
562
|
+
idempotent: data.idempotent,
|
|
563
|
+
steps
|
|
564
|
+
};
|
|
565
|
+
validateLifecycle(run);
|
|
566
|
+
return run;
|
|
567
|
+
} catch {
|
|
568
|
+
return invalid3();
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// src/workflow-json.ts
|
|
573
|
+
function workflowJsonObject(value) {
|
|
574
|
+
const captured = queueJsonSnapshot(value === undefined ? {} : value);
|
|
575
|
+
if (captured === null || typeof captured !== "object" || Array.isArray(captured))
|
|
576
|
+
throw new Error;
|
|
577
|
+
return captured;
|
|
578
|
+
}
|
|
579
|
+
function workflowJsonEqual(left, right) {
|
|
580
|
+
if (left === right)
|
|
581
|
+
return true;
|
|
582
|
+
if (left === null || right === null || typeof left !== "object" || typeof right !== "object")
|
|
583
|
+
return false;
|
|
584
|
+
if (Array.isArray(left)) {
|
|
585
|
+
return Array.isArray(right) && left.length === right.length && left.every((item, index) => workflowJsonEqual(item, right[index]));
|
|
586
|
+
}
|
|
587
|
+
if (Array.isArray(right))
|
|
588
|
+
return false;
|
|
589
|
+
const a = Object.entries(left);
|
|
590
|
+
const b = Object.entries(right);
|
|
591
|
+
const values = new Map(b);
|
|
592
|
+
return a.length === b.length && a.every(([name, value]) => values.has(name) && workflowJsonEqual(value, values.get(name)));
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// src/workflow-start.ts
|
|
596
|
+
class SupaCloudWorkflowStartError extends SupaCloudApiError {
|
|
597
|
+
mutationMayHaveApplied;
|
|
598
|
+
constructor(mutationMayHaveApplied = false) {
|
|
599
|
+
super("Workflow start could not be validated", 0, {
|
|
600
|
+
code: mutationMayHaveApplied ? "WORKFLOW_START_UNCONFIRMED" : "WORKFLOW_START_INPUT_INVALID",
|
|
601
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
602
|
+
});
|
|
603
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
604
|
+
this.name = "SupaCloudWorkflowStartError";
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
function fail() {
|
|
608
|
+
throw new SupaCloudWorkflowStartError;
|
|
609
|
+
}
|
|
610
|
+
function normalized(value, max) {
|
|
611
|
+
if (typeof value !== "string")
|
|
612
|
+
return fail();
|
|
613
|
+
const result = value.replace(/^ +| +$/g, "");
|
|
614
|
+
let count = 0;
|
|
615
|
+
for (const character of result) {
|
|
616
|
+
const code = character.codePointAt(0);
|
|
617
|
+
if (++count > max || code === 0 || code !== undefined && code >= 55296 && code <= 57343)
|
|
618
|
+
return fail();
|
|
619
|
+
}
|
|
620
|
+
return count > 0 ? result : fail();
|
|
621
|
+
}
|
|
622
|
+
function key3(value) {
|
|
623
|
+
const result = normalized(value, 120);
|
|
624
|
+
return /^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/.test(result) ? result : fail();
|
|
625
|
+
}
|
|
626
|
+
function captureWorkflowStart(value) {
|
|
627
|
+
try {
|
|
628
|
+
if (value === null || typeof value !== "object" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null || Object.getOwnPropertySymbols(value).length !== 0)
|
|
629
|
+
return fail();
|
|
630
|
+
const fields = Object.getOwnPropertyDescriptors(value);
|
|
631
|
+
for (const name of Object.keys(fields)) {
|
|
632
|
+
const field = fields[name];
|
|
633
|
+
if (!["runId", "workflowName", "workflowVersion", "firstStepKey", "input", "maxAttempts"].includes(name) || !field || !field.enumerable || !("value" in field))
|
|
634
|
+
return fail();
|
|
635
|
+
}
|
|
636
|
+
const get = (name) => fields[name]?.value;
|
|
637
|
+
const input = queueJsonSnapshot(get("input") === undefined ? {} : get("input"));
|
|
638
|
+
if (input === null || typeof input !== "object" || Array.isArray(input))
|
|
639
|
+
return fail();
|
|
640
|
+
const maxAttempts = get("maxAttempts") === undefined ? 3 : get("maxAttempts");
|
|
641
|
+
if (typeof maxAttempts !== "number" || !Number.isSafeInteger(maxAttempts) || maxAttempts < 1 || maxAttempts > 100)
|
|
642
|
+
return fail();
|
|
643
|
+
return {
|
|
644
|
+
runId: captureWorkflowRunId(get("runId")),
|
|
645
|
+
workflowName: key3(get("workflowName")),
|
|
646
|
+
workflowVersion: normalized(get("workflowVersion"), 80),
|
|
647
|
+
firstStepKey: key3(get("firstStepKey")),
|
|
648
|
+
input,
|
|
649
|
+
maxAttempts
|
|
650
|
+
};
|
|
651
|
+
} catch {
|
|
652
|
+
return fail();
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
function decodeWorkflowStart(value, request) {
|
|
656
|
+
try {
|
|
657
|
+
const run = decodeWorkflowRun(value, request.runId, true);
|
|
658
|
+
const successors = new Set(run?.steps.map((step) => step.nextStepKey));
|
|
659
|
+
const first = run?.steps.find((step) => !successors.has(step.stepKey));
|
|
660
|
+
if (!run || !first || run.workflowName !== request.workflowName || run.workflowVersion !== request.workflowVersion || first.stepKey !== request.firstStepKey || first.maxAttempts !== request.maxAttempts || !workflowJsonEqual(run.input, request.input) || !workflowJsonEqual(first.input, request.input))
|
|
661
|
+
throw new Error;
|
|
662
|
+
if (!run.idempotent && (run.status !== "queued" || run.steps.length !== 1 || first.status !== "queued" || first.attempts !== 0 || run.rowVersion !== "1"))
|
|
663
|
+
throw new Error;
|
|
664
|
+
return run;
|
|
665
|
+
} catch {
|
|
666
|
+
throw new SupaCloudWorkflowStartError(true);
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// src/workflow-cancel.ts
|
|
671
|
+
class SupaCloudWorkflowCancelError extends SupaCloudApiError {
|
|
672
|
+
mutationMayHaveApplied;
|
|
673
|
+
constructor(mutationMayHaveApplied = false) {
|
|
674
|
+
super("Workflow cancellation could not be validated", 0, {
|
|
675
|
+
code: mutationMayHaveApplied ? "WORKFLOW_CANCEL_UNCONFIRMED" : "WORKFLOW_CANCEL_INPUT_INVALID",
|
|
676
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
677
|
+
});
|
|
678
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
679
|
+
this.name = "SupaCloudWorkflowCancelError";
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
function captureWorkflowCancel(runId, reason) {
|
|
683
|
+
try {
|
|
684
|
+
const capturedId = captureWorkflowRunId(runId);
|
|
685
|
+
if (typeof reason !== "string")
|
|
686
|
+
throw new Error;
|
|
687
|
+
const capturedReason = reason.replace(/^ +| +$/g, "");
|
|
688
|
+
let length = 0;
|
|
689
|
+
for (const character of capturedReason) {
|
|
690
|
+
const point = character.codePointAt(0);
|
|
691
|
+
if (++length > 4000 || point === 0 || point !== undefined && point >= 55296 && point <= 57343)
|
|
692
|
+
throw new Error;
|
|
693
|
+
}
|
|
694
|
+
if (length === 0)
|
|
695
|
+
throw new Error;
|
|
696
|
+
return { runId: capturedId, reason: capturedReason };
|
|
697
|
+
} catch {
|
|
698
|
+
throw new SupaCloudWorkflowCancelError;
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
function decodeWorkflowCancel(value, request) {
|
|
702
|
+
try {
|
|
703
|
+
const run = decodeWorkflowRun(value, request.runId, true);
|
|
704
|
+
if (!run || run.status !== "cancelled" || run.errorMessage !== request.reason || run.completedAt === null)
|
|
705
|
+
throw new Error;
|
|
706
|
+
for (const step of run.steps) {
|
|
707
|
+
if (step.status === "queued" || step.status === "running" || step.status === "cancelled" && (step.errorMessage !== request.reason || step.completedAt === null)) {
|
|
708
|
+
throw new Error;
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
return run;
|
|
712
|
+
} catch {
|
|
713
|
+
throw new SupaCloudWorkflowCancelError(true);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
// src/workflow-attempt.ts
|
|
718
|
+
function workflowRequestFields(value, names) {
|
|
719
|
+
if (value === null || typeof value !== "object" || Array.isArray(value) || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null || Object.getOwnPropertySymbols(value).length !== 0)
|
|
720
|
+
throw new Error;
|
|
721
|
+
const fields = Object.getOwnPropertyDescriptors(value);
|
|
722
|
+
const entries = [];
|
|
723
|
+
for (const name of Object.keys(fields)) {
|
|
724
|
+
const field = fields[name];
|
|
725
|
+
if (!names.includes(name) || !field || !field.enumerable || !("value" in field))
|
|
726
|
+
throw new Error;
|
|
727
|
+
entries.push([name, field.value]);
|
|
728
|
+
}
|
|
729
|
+
return Object.fromEntries(entries);
|
|
730
|
+
}
|
|
731
|
+
function captureWorkflowAttempt(fields) {
|
|
732
|
+
const { messageId, attempt } = fields;
|
|
733
|
+
if (typeof messageId !== "string" || typeof attempt !== "number" || !Number.isSafeInteger(attempt) || attempt < 1 || attempt > 2147483647)
|
|
734
|
+
throw new Error;
|
|
735
|
+
return {
|
|
736
|
+
stepId: captureWorkflowRunId(fields.stepId),
|
|
737
|
+
messageId: queueMessageId(messageId),
|
|
738
|
+
attempt,
|
|
739
|
+
workerId: captureWorkflowClaimRequest({ workerId: fields.workerId }).workerId
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
function captureWorkflowErrorMessage(value) {
|
|
743
|
+
if (typeof value !== "string")
|
|
744
|
+
throw new Error;
|
|
745
|
+
const errorMessage = value.replace(/^ +| +$/g, "");
|
|
746
|
+
let length = 0;
|
|
747
|
+
for (const character of errorMessage) {
|
|
748
|
+
const point = character.codePointAt(0);
|
|
749
|
+
if (++length > 4000 || point === 0 || point !== undefined && point >= 55296 && point <= 57343)
|
|
750
|
+
throw new Error;
|
|
751
|
+
}
|
|
752
|
+
if (length === 0)
|
|
753
|
+
throw new Error;
|
|
754
|
+
return errorMessage;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// src/workflow-complete.ts
|
|
758
|
+
class SupaCloudWorkflowCompleteError extends SupaCloudApiError {
|
|
759
|
+
mutationMayHaveApplied;
|
|
760
|
+
constructor(mutationMayHaveApplied = false) {
|
|
761
|
+
super("Workflow completion could not be validated", 0, {
|
|
762
|
+
code: mutationMayHaveApplied ? "WORKFLOW_COMPLETE_UNCONFIRMED" : "WORKFLOW_COMPLETE_INPUT_INVALID",
|
|
763
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
764
|
+
});
|
|
765
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
766
|
+
this.name = "SupaCloudWorkflowCompleteError";
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
function captureWorkflowComplete(value) {
|
|
770
|
+
try {
|
|
771
|
+
const fields = workflowRequestFields(value, ["stepId", "messageId", "attempt", "workerId", "stepOutput", "runOutput"]);
|
|
772
|
+
return {
|
|
773
|
+
...captureWorkflowAttempt(fields),
|
|
774
|
+
stepOutput: workflowJsonObject(fields.stepOutput),
|
|
775
|
+
runOutput: workflowJsonObject(fields.runOutput)
|
|
776
|
+
};
|
|
777
|
+
} catch {
|
|
778
|
+
throw new SupaCloudWorkflowCompleteError;
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
function decodeWorkflowComplete(value, request) {
|
|
782
|
+
try {
|
|
783
|
+
const snapshot = queueJsonSnapshot(value);
|
|
784
|
+
if (snapshot === null || typeof snapshot !== "object" || Array.isArray(snapshot))
|
|
785
|
+
throw new Error;
|
|
786
|
+
const run = decodeWorkflowRun(snapshot, captureWorkflowRunId(snapshot.runId), true);
|
|
787
|
+
const step = run?.steps.find((item) => item.stepId === request.stepId);
|
|
788
|
+
if (!run || !step || run.status !== "completed" || run.errorMessage !== "" || run.completedAt === null || step.status !== "completed" || step.queueMessageId !== request.messageId || step.attempts !== request.attempt || step.claimedBy !== request.workerId || step.completedAt === null || step.nextStepKey !== null || step.errorMessage !== "" || !workflowJsonEqual(step.output, request.stepOutput) || !workflowJsonEqual(run.output, request.runOutput) || run.steps.some((item) => item.status === "queued" || item.status === "running"))
|
|
789
|
+
throw new Error;
|
|
790
|
+
return run;
|
|
791
|
+
} catch {
|
|
792
|
+
throw new SupaCloudWorkflowCompleteError(true);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
// src/workflow-fail.ts
|
|
797
|
+
class SupaCloudWorkflowFailError extends SupaCloudApiError {
|
|
798
|
+
mutationMayHaveApplied;
|
|
799
|
+
constructor(mutationMayHaveApplied = false) {
|
|
800
|
+
super("Workflow failure transition could not be validated", 0, {
|
|
801
|
+
code: mutationMayHaveApplied ? "WORKFLOW_FAIL_UNCONFIRMED" : "WORKFLOW_FAIL_INPUT_INVALID",
|
|
802
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
803
|
+
});
|
|
804
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
805
|
+
this.name = "SupaCloudWorkflowFailError";
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
function captureWorkflowFail(value) {
|
|
809
|
+
try {
|
|
810
|
+
const fields = workflowRequestFields(value, ["stepId", "messageId", "attempt", "workerId", "errorMessage"]);
|
|
811
|
+
return { ...captureWorkflowAttempt(fields), errorMessage: captureWorkflowErrorMessage(fields.errorMessage) };
|
|
812
|
+
} catch {
|
|
813
|
+
throw new SupaCloudWorkflowFailError;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
function decodeWorkflowFail(value, request) {
|
|
817
|
+
try {
|
|
818
|
+
const snapshot = queueJsonSnapshot(value);
|
|
819
|
+
if (snapshot === null || typeof snapshot !== "object" || Array.isArray(snapshot))
|
|
820
|
+
throw new Error;
|
|
821
|
+
const run = decodeWorkflowRun(snapshot, captureWorkflowRunId(snapshot.runId), true);
|
|
822
|
+
const step = run?.steps.find((item) => item.stepId === request.stepId);
|
|
823
|
+
if (!run || !step || run.status !== "failed" || run.errorMessage !== request.errorMessage || run.completedAt === null || step.status !== "failed" || step.queueMessageId !== request.messageId || step.attempts !== request.attempt || step.claimedBy !== request.workerId || step.completedAt === null || step.errorMessage !== request.errorMessage || run.steps.some((item) => item.status === "queued" || item.status === "running"))
|
|
824
|
+
throw new Error;
|
|
825
|
+
return run;
|
|
826
|
+
} catch {
|
|
827
|
+
throw new SupaCloudWorkflowFailError(true);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
// src/workflow-advance.ts
|
|
832
|
+
class SupaCloudWorkflowAdvanceError extends SupaCloudApiError {
|
|
833
|
+
mutationMayHaveApplied;
|
|
834
|
+
constructor(mutationMayHaveApplied = false) {
|
|
835
|
+
super("Workflow advancement could not be validated", 0, {
|
|
836
|
+
code: mutationMayHaveApplied ? "WORKFLOW_ADVANCE_UNCONFIRMED" : "WORKFLOW_ADVANCE_INPUT_INVALID",
|
|
837
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
838
|
+
});
|
|
839
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
840
|
+
this.name = "SupaCloudWorkflowAdvanceError";
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
function captureWorkflowAdvance(value) {
|
|
844
|
+
try {
|
|
845
|
+
const fields = workflowRequestFields(value, [
|
|
846
|
+
"stepId",
|
|
847
|
+
"messageId",
|
|
848
|
+
"attempt",
|
|
849
|
+
"workerId",
|
|
850
|
+
"output",
|
|
851
|
+
"nextStepKey",
|
|
852
|
+
"nextInput",
|
|
853
|
+
"nextMaxAttempts"
|
|
854
|
+
]);
|
|
855
|
+
if (typeof fields.nextStepKey !== "string")
|
|
856
|
+
throw new Error;
|
|
857
|
+
const nextStepKey = fields.nextStepKey.replace(/^ +| +$/g, "");
|
|
858
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/.test(nextStepKey))
|
|
859
|
+
throw new Error;
|
|
860
|
+
const nextMaxAttempts = fields.nextMaxAttempts === undefined ? 3 : fields.nextMaxAttempts;
|
|
861
|
+
if (typeof nextMaxAttempts !== "number" || !Number.isSafeInteger(nextMaxAttempts) || nextMaxAttempts < 1 || nextMaxAttempts > 100)
|
|
862
|
+
throw new Error;
|
|
863
|
+
return {
|
|
864
|
+
...captureWorkflowAttempt(fields),
|
|
865
|
+
nextStepKey,
|
|
866
|
+
nextMaxAttempts,
|
|
867
|
+
output: workflowJsonObject(fields.output),
|
|
868
|
+
nextInput: workflowJsonObject(fields.nextInput)
|
|
869
|
+
};
|
|
870
|
+
} catch {
|
|
871
|
+
throw new SupaCloudWorkflowAdvanceError;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
function decodeWorkflowAdvance(value, request) {
|
|
875
|
+
try {
|
|
876
|
+
const snapshot = queueJsonSnapshot(value);
|
|
877
|
+
if (snapshot === null || typeof snapshot !== "object" || Array.isArray(snapshot))
|
|
878
|
+
throw new Error;
|
|
879
|
+
const run = decodeWorkflowRun(snapshot, captureWorkflowRunId(snapshot.runId), true);
|
|
880
|
+
const current = run?.steps.find((step) => step.stepId === request.stepId);
|
|
881
|
+
const next = run?.steps.find((step) => step.stepKey === request.nextStepKey);
|
|
882
|
+
if (!run || !current || !next || current.stepId === next.stepId || current.status !== "completed" || current.queueMessageId !== request.messageId || current.attempts !== request.attempt || current.claimedBy !== request.workerId || current.completedAt === null || current.errorMessage !== "" || current.nextStepKey !== request.nextStepKey || next.maxAttempts !== request.nextMaxAttempts || !workflowJsonEqual(current.output, request.output) || !workflowJsonEqual(next.input, request.nextInput)) {
|
|
883
|
+
throw new Error;
|
|
884
|
+
}
|
|
885
|
+
if (!run.idempotent && (run.status !== "running" || next.status !== "queued" || next.attempts !== 0))
|
|
886
|
+
throw new Error;
|
|
887
|
+
return run;
|
|
888
|
+
} catch {
|
|
889
|
+
throw new SupaCloudWorkflowAdvanceError(true);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
// src/workflow-retry.ts
|
|
894
|
+
class SupaCloudWorkflowRetryError extends SupaCloudApiError {
|
|
895
|
+
mutationMayHaveApplied;
|
|
896
|
+
constructor(mutationMayHaveApplied = false) {
|
|
897
|
+
super("Workflow retry could not be validated", 0, {
|
|
898
|
+
code: mutationMayHaveApplied ? "WORKFLOW_RETRY_UNCONFIRMED" : "WORKFLOW_RETRY_INPUT_INVALID",
|
|
899
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
900
|
+
});
|
|
901
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
902
|
+
this.name = "SupaCloudWorkflowRetryError";
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
function captureWorkflowRetry(value) {
|
|
906
|
+
try {
|
|
907
|
+
const fields = workflowRequestFields(value, ["stepId", "messageId", "attempt", "workerId", "errorMessage", "delaySeconds"]);
|
|
908
|
+
const delaySeconds = fields.delaySeconds === undefined ? 0 : fields.delaySeconds;
|
|
909
|
+
if (typeof delaySeconds !== "number" || !Number.isSafeInteger(delaySeconds) || delaySeconds < 0 || delaySeconds > 86400)
|
|
910
|
+
throw new Error;
|
|
911
|
+
return {
|
|
912
|
+
...captureWorkflowAttempt(fields),
|
|
913
|
+
errorMessage: captureWorkflowErrorMessage(fields.errorMessage),
|
|
914
|
+
delaySeconds
|
|
915
|
+
};
|
|
916
|
+
} catch {
|
|
917
|
+
throw new SupaCloudWorkflowRetryError;
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
function decodeWorkflowRetry(value, request) {
|
|
921
|
+
try {
|
|
922
|
+
const snapshot = queueJsonSnapshot(value);
|
|
923
|
+
if (snapshot === null || typeof snapshot !== "object" || Array.isArray(snapshot))
|
|
924
|
+
throw new Error;
|
|
925
|
+
const receipt = snapshot.retryReceipt;
|
|
926
|
+
if (receipt === null || typeof receipt !== "object" || Array.isArray(receipt) || receipt.operation !== "retry" || receipt.stepId !== request.stepId || receipt.messageId !== request.messageId || receipt.attempt !== request.attempt || receipt.workerId !== request.workerId || receipt.errorMessage !== request.errorMessage || receipt.delaySeconds !== request.delaySeconds)
|
|
927
|
+
throw new Error;
|
|
928
|
+
const run = decodeWorkflowRun(snapshot, captureWorkflowRunId(snapshot.runId), true);
|
|
929
|
+
const step = run?.steps.find((item) => item.stepId === request.stepId);
|
|
930
|
+
if (!run || !step || step.queueMessageId !== request.messageId || step.attempts < request.attempt)
|
|
931
|
+
throw new Error;
|
|
932
|
+
if (run.idempotent)
|
|
933
|
+
return run;
|
|
934
|
+
if (step.attempts !== request.attempt || step.claimedBy !== request.workerId || step.errorMessage !== request.errorMessage)
|
|
935
|
+
throw new Error;
|
|
936
|
+
if (request.attempt >= step.maxAttempts) {
|
|
937
|
+
if (step.status !== "dead_lettered" || run.status !== "failed" || run.errorMessage !== request.errorMessage || step.completedAt === null || run.completedAt === null || run.steps.some((item) => item.status === "queued" || item.status === "running"))
|
|
938
|
+
throw new Error;
|
|
939
|
+
} else if (step.status !== "queued" || run.status !== "running" || step.completedAt !== null || step.retryDelaySeconds !== request.delaySeconds)
|
|
940
|
+
throw new Error;
|
|
941
|
+
return run;
|
|
942
|
+
} catch {
|
|
943
|
+
throw new SupaCloudWorkflowRetryError(true);
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
// src/workflow-events.ts
|
|
948
|
+
class SupaCloudWorkflowEventsError extends SupaCloudApiError {
|
|
949
|
+
mutationMayHaveApplied = false;
|
|
950
|
+
constructor(input = false) {
|
|
951
|
+
super("Workflow events could not be validated", 0, {
|
|
952
|
+
code: input ? "WORKFLOW_EVENTS_INPUT_INVALID" : "WORKFLOW_EVENTS_INVALID",
|
|
953
|
+
mutation_may_have_applied: false
|
|
954
|
+
});
|
|
955
|
+
this.name = "SupaCloudWorkflowEventsError";
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
function captureWorkflowEvents(runId, options) {
|
|
959
|
+
try {
|
|
960
|
+
const fields = workflowRequestFields(options, ["afterEventId", "limit"]);
|
|
961
|
+
const afterEventId = fields.afterEventId === undefined ? "0" : fields.afterEventId;
|
|
962
|
+
const limit = fields.limit === undefined ? 100 : fields.limit;
|
|
963
|
+
if (typeof afterEventId !== "string" || afterEventId !== "0" && queueMessageId(afterEventId) !== afterEventId || typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 1 || limit > 500)
|
|
964
|
+
throw new Error;
|
|
965
|
+
return { runId: captureWorkflowRunId(runId), afterEventId, limit };
|
|
966
|
+
} catch {
|
|
967
|
+
throw new SupaCloudWorkflowEventsError(true);
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
function decodeWorkflowEvents(value, request) {
|
|
971
|
+
try {
|
|
972
|
+
const snapshot = queueJsonSnapshot(value);
|
|
973
|
+
if (!Array.isArray(snapshot) || snapshot.length > request.limit)
|
|
974
|
+
throw new Error;
|
|
975
|
+
let previous = BigInt(request.afterEventId);
|
|
976
|
+
return snapshot.map((item) => {
|
|
977
|
+
if (item === null || typeof item !== "object" || Array.isArray(item))
|
|
978
|
+
throw new Error;
|
|
979
|
+
const { eventId, runId, stepId, eventType, attempt, details, createdAt } = item;
|
|
980
|
+
if (typeof eventId !== "string" || queueMessageId(eventId) !== eventId || BigInt(eventId) <= previous || runId !== request.runId || stepId !== null && (typeof stepId !== "string" || captureWorkflowRunId(stepId) !== stepId) || typeof eventType !== "string" || ![
|
|
981
|
+
"run_started",
|
|
982
|
+
"step_claimed",
|
|
983
|
+
"step_retried",
|
|
984
|
+
"step_completed",
|
|
985
|
+
"step_failed",
|
|
986
|
+
"step_dead_lettered",
|
|
987
|
+
"run_completed",
|
|
988
|
+
"run_cancelled"
|
|
989
|
+
].includes(eventType) || attempt !== null && (typeof attempt !== "number" || !Number.isSafeInteger(attempt) || attempt < 1 || attempt > 2147483647) || details === null || typeof details !== "object" || Array.isArray(details) || !isWorkflowTimestamp(createdAt))
|
|
990
|
+
throw new Error;
|
|
991
|
+
previous = BigInt(eventId);
|
|
992
|
+
return { eventId, runId, stepId, eventType, attempt, details, createdAt };
|
|
993
|
+
});
|
|
994
|
+
} catch {
|
|
995
|
+
throw new SupaCloudWorkflowEventsError;
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
// src/workflows.ts
|
|
1000
|
+
class SupaCloudWorkflowsClient {
|
|
1001
|
+
supabase;
|
|
1002
|
+
constructor(supabase) {
|
|
1003
|
+
this.supabase = supabase;
|
|
1004
|
+
}
|
|
1005
|
+
async start(request) {
|
|
1006
|
+
const captured = captureWorkflowStart(request);
|
|
1007
|
+
const result = await invokeWorkflowMutation(this.supabase, "supacloud_workflow_start", captured, () => new SupaCloudWorkflowStartError(true));
|
|
1008
|
+
return decodeWorkflowStart(result, captured);
|
|
1009
|
+
}
|
|
1010
|
+
async claim(request) {
|
|
1011
|
+
const captured = captureWorkflowClaimRequest(request);
|
|
1012
|
+
const result = await invokeWorkflowMutation(this.supabase, "supacloud_workflow_claim", captured, () => new SupaCloudWorkflowClaimError);
|
|
1013
|
+
return decodeWorkflowClaim(result, captured.workerId);
|
|
1014
|
+
}
|
|
1015
|
+
async advance(request) {
|
|
1016
|
+
const captured = captureWorkflowAdvance(request);
|
|
1017
|
+
const result = await invokeWorkflowMutation(this.supabase, "supacloud_workflow_advance", captured, () => new SupaCloudWorkflowAdvanceError(true));
|
|
1018
|
+
return decodeWorkflowAdvance(result, captured);
|
|
1019
|
+
}
|
|
1020
|
+
async complete(request) {
|
|
1021
|
+
const captured = captureWorkflowComplete(request);
|
|
1022
|
+
const result = await invokeWorkflowMutation(this.supabase, "supacloud_workflow_complete", captured, () => new SupaCloudWorkflowCompleteError(true));
|
|
1023
|
+
return decodeWorkflowComplete(result, captured);
|
|
1024
|
+
}
|
|
1025
|
+
async retry(request) {
|
|
1026
|
+
const captured = captureWorkflowRetry(request);
|
|
1027
|
+
const result = await invokeWorkflowMutation(this.supabase, "supacloud_workflow_retry", captured, () => new SupaCloudWorkflowRetryError(true));
|
|
1028
|
+
return decodeWorkflowRetry(result, captured);
|
|
1029
|
+
}
|
|
1030
|
+
async fail(request) {
|
|
1031
|
+
const captured = captureWorkflowFail(request);
|
|
1032
|
+
const result = await invokeWorkflowMutation(this.supabase, "supacloud_workflow_fail", captured, () => new SupaCloudWorkflowFailError(true));
|
|
1033
|
+
return decodeWorkflowFail(result, captured);
|
|
1034
|
+
}
|
|
1035
|
+
async cancel(runId, reason) {
|
|
1036
|
+
const captured = captureWorkflowCancel(runId, reason);
|
|
1037
|
+
const result = await invokeWorkflowMutation(this.supabase, "supacloud_workflow_cancel", captured, () => new SupaCloudWorkflowCancelError(true));
|
|
1038
|
+
return decodeWorkflowCancel(result, captured);
|
|
1039
|
+
}
|
|
1040
|
+
async get(runId) {
|
|
1041
|
+
const captured = captureWorkflowRunId(runId);
|
|
1042
|
+
const result = await invokeWorkflowRead(this.supabase, "supacloud_workflow_get", { runId: captured }, () => new SupaCloudWorkflowReadError);
|
|
1043
|
+
return decodeWorkflowRun(result, captured);
|
|
1044
|
+
}
|
|
1045
|
+
async events(runId, options = {}) {
|
|
1046
|
+
const captured = captureWorkflowEvents(runId, options);
|
|
1047
|
+
const result = await invokeWorkflowRead(this.supabase, "supacloud_workflow_events", captured, () => new SupaCloudWorkflowEventsError);
|
|
1048
|
+
return decodeWorkflowEvents(result, captured);
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
// src/commands.ts
|
|
1053
|
+
import { decodeCommandStatus } from "@supacloud/contracts";
|
|
1054
|
+
class SupaCloudCommandReadError extends SupaCloudApiError {
|
|
1055
|
+
mutationMayHaveApplied = false;
|
|
1056
|
+
constructor() {
|
|
1057
|
+
super("Command read could not be validated", 0, {
|
|
1058
|
+
code: "COMMAND_READ_INVALID",
|
|
1059
|
+
mutation_may_have_applied: false
|
|
1060
|
+
});
|
|
1061
|
+
this.name = "SupaCloudCommandReadError";
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
class SupaCloudCommandSubmitError extends SupaCloudApiError {
|
|
1066
|
+
mutationMayHaveApplied;
|
|
1067
|
+
constructor(mutationMayHaveApplied = true) {
|
|
1068
|
+
super("Command submission could not be validated", 0, {
|
|
1069
|
+
code: "COMMAND_SUBMIT_UNCONFIRMED",
|
|
1070
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
1071
|
+
});
|
|
1072
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
1073
|
+
this.name = "SupaCloudCommandSubmitError";
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
class SupaCloudCommandsClient {
|
|
1078
|
+
supabase;
|
|
1079
|
+
constructor(supabase) {
|
|
1080
|
+
this.supabase = supabase;
|
|
1081
|
+
}
|
|
1082
|
+
async submit(request) {
|
|
1083
|
+
const raw = await this.request("supacloud_command_submit", request, () => new SupaCloudCommandSubmitError);
|
|
1084
|
+
const status = decodeCommandStatus(raw);
|
|
1085
|
+
if (status.commandId !== request.commandId.toLowerCase())
|
|
1086
|
+
throw new TypeError("Invalid command submission");
|
|
1087
|
+
return status;
|
|
1088
|
+
}
|
|
1089
|
+
async get(lookup) {
|
|
1090
|
+
const request = typeof lookup === "string" ? { commandId: lookup } : { ...lookup };
|
|
1091
|
+
const raw = await this.request("supacloud_command_get", request, () => new SupaCloudCommandReadError);
|
|
1092
|
+
if (raw === null)
|
|
1093
|
+
return null;
|
|
1094
|
+
const status = decodeCommandStatus(raw);
|
|
1095
|
+
if ("commandId" in request) {
|
|
1096
|
+
if (status.commandId !== request.commandId.toLowerCase())
|
|
1097
|
+
throw new TypeError("Mismatched command status");
|
|
1098
|
+
} else {
|
|
1099
|
+
if (status.kind !== "execution")
|
|
1100
|
+
throw new TypeError("Missing command execution");
|
|
1101
|
+
for (const key of ["tenantId", "actorId", "command", "operationId"]) {
|
|
1102
|
+
if (status.execution[key] !== request[key])
|
|
1103
|
+
throw new TypeError("Mismatched command reference");
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
return status;
|
|
1107
|
+
}
|
|
1108
|
+
async request(functionName, request, failure) {
|
|
1109
|
+
let result;
|
|
1110
|
+
try {
|
|
1111
|
+
result = await this.supabase.rpc(functionName, { request });
|
|
1112
|
+
} catch {
|
|
1113
|
+
throw failure();
|
|
1114
|
+
}
|
|
1115
|
+
if (result.error) {
|
|
1116
|
+
const error = result.error;
|
|
1117
|
+
const code = error && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : null;
|
|
1118
|
+
if (result.status === 0 || result.status === undefined && !code)
|
|
1119
|
+
throw failure();
|
|
1120
|
+
throw error;
|
|
1121
|
+
}
|
|
1122
|
+
return result.data;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
// src/artifact-read.ts
|
|
1127
|
+
class SupaCloudArtifactReadError extends SupaCloudApiError {
|
|
1128
|
+
mutationMayHaveApplied = false;
|
|
1129
|
+
constructor(input = false) {
|
|
1130
|
+
super("Artifact read could not be validated", 0, {
|
|
1131
|
+
code: input ? "ARTIFACT_READ_INPUT_INVALID" : "ARTIFACT_READ_INVALID",
|
|
1132
|
+
mutation_may_have_applied: false
|
|
1133
|
+
});
|
|
1134
|
+
this.name = "SupaCloudArtifactReadError";
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
function uuid3(value) {
|
|
1138
|
+
if (typeof value !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value))
|
|
1139
|
+
throw new Error;
|
|
1140
|
+
return value;
|
|
1141
|
+
}
|
|
1142
|
+
function captureArtifactId(value) {
|
|
1143
|
+
try {
|
|
1144
|
+
if (typeof value !== "string")
|
|
1145
|
+
throw new Error;
|
|
1146
|
+
return uuid3(value.toLowerCase());
|
|
1147
|
+
} catch {
|
|
1148
|
+
throw new SupaCloudArtifactReadError(true);
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
function record4(value) {
|
|
1152
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
1153
|
+
throw new Error;
|
|
1154
|
+
return value;
|
|
1155
|
+
}
|
|
1156
|
+
function artifactText(value, min = 0, max = 1048576) {
|
|
1157
|
+
if (typeof value !== "string")
|
|
1158
|
+
throw new Error;
|
|
1159
|
+
let count = 0;
|
|
1160
|
+
for (const character of value) {
|
|
1161
|
+
const point = character.codePointAt(0);
|
|
1162
|
+
if (++count > max || point === undefined || point === 0 || point >= 55296 && point <= 57343)
|
|
1163
|
+
throw new Error;
|
|
1164
|
+
}
|
|
1165
|
+
if (count < min)
|
|
1166
|
+
throw new Error;
|
|
1167
|
+
return value;
|
|
1168
|
+
}
|
|
1169
|
+
function artifactKey(value) {
|
|
1170
|
+
const result = artifactText(value, 1, 120);
|
|
1171
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/.test(result))
|
|
1172
|
+
throw new Error;
|
|
1173
|
+
return result;
|
|
1174
|
+
}
|
|
1175
|
+
function timestamp2(value) {
|
|
1176
|
+
if (!isWorkflowTimestamp(value))
|
|
1177
|
+
throw new Error;
|
|
1178
|
+
return value;
|
|
1179
|
+
}
|
|
1180
|
+
function artifactTimestampMicros(value) {
|
|
1181
|
+
timestamp2(value);
|
|
1182
|
+
const fraction = /\.(\d{1,6})/.exec(value)?.[1] ?? "";
|
|
1183
|
+
return BigInt(Date.parse(value)) * 1000n + BigInt(fraction.padEnd(6, "0").slice(3));
|
|
1184
|
+
}
|
|
1185
|
+
function artifactSize(value) {
|
|
1186
|
+
if (typeof value !== "string" || !/^(?:0|[1-9][0-9]{0,18})$/.test(value) || BigInt(value) > 9223372036854775807n)
|
|
1187
|
+
throw new Error;
|
|
1188
|
+
return value;
|
|
1189
|
+
}
|
|
1190
|
+
function artifactPath(value) {
|
|
1191
|
+
const result = artifactText(value, 1);
|
|
1192
|
+
if (result.startsWith("/") || result.includes("\\") || /(^|\/)\.\.?(\/|$)/.test(result))
|
|
1193
|
+
throw new Error;
|
|
1194
|
+
return result;
|
|
1195
|
+
}
|
|
1196
|
+
function decodeArtifactRead(value, artifactId, allowIdempotent = false) {
|
|
1197
|
+
if (value === null)
|
|
1198
|
+
return null;
|
|
1199
|
+
try {
|
|
1200
|
+
const data = record4(queueJsonSnapshot(value));
|
|
1201
|
+
if (uuid3(data.artifactId) !== artifactId || typeof data.idempotent !== "boolean" || !allowIdempotent && data.idempotent)
|
|
1202
|
+
throw new Error;
|
|
1203
|
+
const sizeBytes = artifactSize(data.sizeBytes);
|
|
1204
|
+
const sha256 = data.sha256;
|
|
1205
|
+
if (typeof sha256 !== "string" || !/^[0-9a-f]{64}$/.test(sha256))
|
|
1206
|
+
throw new Error;
|
|
1207
|
+
const objectPath = artifactPath(data.objectPath);
|
|
1208
|
+
const createdAt = timestamp2(data.createdAt);
|
|
1209
|
+
const retentionUntil = data.retentionUntil === null ? null : timestamp2(data.retentionUntil);
|
|
1210
|
+
if (retentionUntil !== null && artifactTimestampMicros(retentionUntil) < artifactTimestampMicros(createdAt))
|
|
1211
|
+
throw new Error;
|
|
1212
|
+
if (!Array.isArray(data.parents))
|
|
1213
|
+
throw new Error;
|
|
1214
|
+
const seen = new Set;
|
|
1215
|
+
const parents = data.parents.map((value) => {
|
|
1216
|
+
const parent = record4(value);
|
|
1217
|
+
const parentId = uuid3(parent.artifactId), relationType = artifactKey(parent.relationType);
|
|
1218
|
+
const identity = `${parentId}:${relationType}`;
|
|
1219
|
+
if (parentId === artifactId || seen.has(identity))
|
|
1220
|
+
throw new Error;
|
|
1221
|
+
seen.add(identity);
|
|
1222
|
+
return {
|
|
1223
|
+
artifactId: parentId,
|
|
1224
|
+
relationType,
|
|
1225
|
+
metadata: record4(parent.metadata),
|
|
1226
|
+
createdAt: timestamp2(parent.createdAt)
|
|
1227
|
+
};
|
|
1228
|
+
});
|
|
1229
|
+
return {
|
|
1230
|
+
artifactId,
|
|
1231
|
+
bucketId: artifactText(data.bucketId, 1),
|
|
1232
|
+
objectPath,
|
|
1233
|
+
objectVersion: artifactText(data.objectVersion),
|
|
1234
|
+
artifactType: artifactKey(data.artifactType),
|
|
1235
|
+
sha256,
|
|
1236
|
+
sizeBytes,
|
|
1237
|
+
mimeType: artifactText(data.mimeType, 1, 255),
|
|
1238
|
+
metadata: record4(data.metadata),
|
|
1239
|
+
retentionUntil,
|
|
1240
|
+
createdBy: data.createdBy === null ? null : uuid3(data.createdBy),
|
|
1241
|
+
createdAt,
|
|
1242
|
+
idempotent: data.idempotent,
|
|
1243
|
+
parents
|
|
1244
|
+
};
|
|
1245
|
+
} catch {
|
|
1246
|
+
throw new SupaCloudArtifactReadError;
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
// src/artifact-register.ts
|
|
1251
|
+
class SupaCloudArtifactRegisterError extends SupaCloudApiError {
|
|
1252
|
+
mutationMayHaveApplied;
|
|
1253
|
+
constructor(mutationMayHaveApplied = false) {
|
|
1254
|
+
super("Artifact registration could not be validated", 0, {
|
|
1255
|
+
code: mutationMayHaveApplied ? "ARTIFACT_REGISTER_UNCONFIRMED" : "ARTIFACT_REGISTER_INPUT_INVALID",
|
|
1256
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
1257
|
+
});
|
|
1258
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
1259
|
+
this.name = "SupaCloudArtifactRegisterError";
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
function trim(value) {
|
|
1263
|
+
return artifactText(value).replace(/^ +| +$/g, "");
|
|
1264
|
+
}
|
|
1265
|
+
function captureArtifactRegister(value) {
|
|
1266
|
+
try {
|
|
1267
|
+
const fields = workflowRequestFields(value, [
|
|
1268
|
+
"artifactId",
|
|
1269
|
+
"bucketId",
|
|
1270
|
+
"objectPath",
|
|
1271
|
+
"artifactType",
|
|
1272
|
+
"sha256",
|
|
1273
|
+
"sizeBytes",
|
|
1274
|
+
"mimeType",
|
|
1275
|
+
"metadata",
|
|
1276
|
+
"retentionUntil",
|
|
1277
|
+
"createdBy"
|
|
1278
|
+
]);
|
|
1279
|
+
let size = fields.sizeBytes;
|
|
1280
|
+
if (typeof size === "number") {
|
|
1281
|
+
if (!Number.isSafeInteger(size) || size < 0)
|
|
1282
|
+
throw new Error;
|
|
1283
|
+
size = String(size);
|
|
1284
|
+
}
|
|
1285
|
+
const sha256 = trim(fields.sha256).toLowerCase();
|
|
1286
|
+
if (!/^[0-9a-f]{64}$/.test(sha256))
|
|
1287
|
+
throw new Error;
|
|
1288
|
+
const retentionUntil = fields.retentionUntil === undefined ? null : artifactText(fields.retentionUntil, 1, 40);
|
|
1289
|
+
if (retentionUntil !== null)
|
|
1290
|
+
artifactTimestampMicros(retentionUntil);
|
|
1291
|
+
return {
|
|
1292
|
+
artifactId: captureArtifactId(fields.artifactId),
|
|
1293
|
+
bucketId: artifactText(trim(fields.bucketId), 1),
|
|
1294
|
+
objectPath: artifactPath(trim(fields.objectPath)),
|
|
1295
|
+
artifactType: artifactKey(trim(fields.artifactType)),
|
|
1296
|
+
sha256,
|
|
1297
|
+
sizeBytes: artifactSize(size),
|
|
1298
|
+
mimeType: artifactText(trim(fields.mimeType).toLowerCase(), 1, 255),
|
|
1299
|
+
metadata: workflowJsonObject(fields.metadata),
|
|
1300
|
+
retentionUntil,
|
|
1301
|
+
createdBy: fields.createdBy === undefined ? null : captureArtifactId(fields.createdBy)
|
|
1302
|
+
};
|
|
1303
|
+
} catch {
|
|
1304
|
+
throw new SupaCloudArtifactRegisterError;
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
function decodeArtifactRegister(value, request) {
|
|
1308
|
+
try {
|
|
1309
|
+
const receipt = decodeArtifactRead(value, request.artifactId, true);
|
|
1310
|
+
if (!receipt || receipt.bucketId !== request.bucketId || receipt.objectPath !== request.objectPath || receipt.artifactType !== request.artifactType || receipt.sha256 !== request.sha256 || receipt.sizeBytes !== request.sizeBytes || receipt.mimeType !== request.mimeType || receipt.createdBy !== request.createdBy || !workflowJsonEqual(receipt.metadata, request.metadata))
|
|
1311
|
+
throw new Error;
|
|
1312
|
+
if (request.retentionUntil === null ? receipt.retentionUntil !== null : receipt.retentionUntil === null || artifactTimestampMicros(receipt.retentionUntil) !== artifactTimestampMicros(request.retentionUntil))
|
|
1313
|
+
throw new Error;
|
|
1314
|
+
if (!receipt.idempotent && receipt.parents.length !== 0)
|
|
1315
|
+
throw new Error;
|
|
1316
|
+
return receipt;
|
|
1317
|
+
} catch {
|
|
1318
|
+
throw new SupaCloudArtifactRegisterError(true);
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
// src/artifact-rpc.ts
|
|
1323
|
+
async function invokeArtifactRpc(supabase, name, request, failure) {
|
|
1324
|
+
const controller = new AbortController;
|
|
1325
|
+
let timer;
|
|
1326
|
+
const deadline = new Promise((_, reject) => {
|
|
1327
|
+
timer = setTimeout(() => {
|
|
1328
|
+
reject(failure());
|
|
1329
|
+
controller.abort();
|
|
1330
|
+
}, 15000);
|
|
1331
|
+
});
|
|
1332
|
+
let result;
|
|
1333
|
+
try {
|
|
1334
|
+
const pending = supabase.rpc(name, { request }).retry(false).abortSignal(controller.signal);
|
|
1335
|
+
result = await Promise.race([pending, deadline]);
|
|
1336
|
+
} catch {
|
|
1337
|
+
throw failure();
|
|
1338
|
+
} finally {
|
|
1339
|
+
clearTimeout(timer);
|
|
1340
|
+
}
|
|
1341
|
+
if (result.error && result.status >= 400 && result.status < 500)
|
|
1342
|
+
throw result.error;
|
|
1343
|
+
if (result.error || result.status !== 200)
|
|
1344
|
+
throw failure();
|
|
1345
|
+
return result.data;
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
// src/artifact-link.ts
|
|
1349
|
+
class SupaCloudArtifactLinkError extends SupaCloudApiError {
|
|
1350
|
+
mutationMayHaveApplied;
|
|
1351
|
+
constructor(mutationMayHaveApplied = false) {
|
|
1352
|
+
super("Artifact link could not be validated", 0, {
|
|
1353
|
+
code: mutationMayHaveApplied ? "ARTIFACT_LINK_UNCONFIRMED" : "ARTIFACT_LINK_INPUT_INVALID",
|
|
1354
|
+
mutation_may_have_applied: mutationMayHaveApplied
|
|
1355
|
+
});
|
|
1356
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
1357
|
+
this.name = "SupaCloudArtifactLinkError";
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
function captureArtifactLink(value) {
|
|
1361
|
+
try {
|
|
1362
|
+
const fields = workflowRequestFields(value, ["parentArtifactId", "childArtifactId", "relationType", "metadata"]);
|
|
1363
|
+
const parentArtifactId = captureArtifactId(fields.parentArtifactId);
|
|
1364
|
+
const childArtifactId = captureArtifactId(fields.childArtifactId);
|
|
1365
|
+
if (parentArtifactId === childArtifactId)
|
|
1366
|
+
throw new Error;
|
|
1367
|
+
return {
|
|
1368
|
+
parentArtifactId,
|
|
1369
|
+
childArtifactId,
|
|
1370
|
+
relationType: artifactKey(artifactText(fields.relationType).replace(/^ +| +$/g, "")),
|
|
1371
|
+
metadata: workflowJsonObject(fields.metadata)
|
|
1372
|
+
};
|
|
1373
|
+
} catch {
|
|
1374
|
+
throw new SupaCloudArtifactLinkError;
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
function decodeArtifactLink(value, request) {
|
|
1378
|
+
try {
|
|
1379
|
+
const receipt = decodeArtifactRead(value, request.childArtifactId, true);
|
|
1380
|
+
const edge = receipt?.parents.find((parent) => parent.artifactId === request.parentArtifactId && parent.relationType === request.relationType);
|
|
1381
|
+
if (!receipt || !edge || !workflowJsonEqual(edge.metadata, request.metadata))
|
|
1382
|
+
throw new Error;
|
|
1383
|
+
return receipt;
|
|
1384
|
+
} catch {
|
|
1385
|
+
throw new SupaCloudArtifactLinkError(true);
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
// src/artifacts.ts
|
|
1390
|
+
class SupaCloudArtifactsClient {
|
|
1391
|
+
supabase;
|
|
1392
|
+
constructor(supabase) {
|
|
1393
|
+
this.supabase = supabase;
|
|
1394
|
+
}
|
|
1395
|
+
async register(request) {
|
|
1396
|
+
const captured = captureArtifactRegister(request);
|
|
1397
|
+
const result = await invokeArtifactRpc(this.supabase, "supacloud_artifact_register", captured, () => new SupaCloudArtifactRegisterError(true));
|
|
1398
|
+
return decodeArtifactRegister(result, captured);
|
|
1399
|
+
}
|
|
1400
|
+
async get(artifactId) {
|
|
1401
|
+
const captured = captureArtifactId(artifactId);
|
|
1402
|
+
const result = await invokeArtifactRpc(this.supabase, "supacloud_artifact_get", {
|
|
1403
|
+
artifactId: captured
|
|
1404
|
+
}, () => new SupaCloudArtifactReadError);
|
|
1405
|
+
return decodeArtifactRead(result, captured);
|
|
1406
|
+
}
|
|
1407
|
+
async link(request) {
|
|
1408
|
+
const captured = captureArtifactLink(request);
|
|
1409
|
+
const result = await invokeArtifactRpc(this.supabase, "supacloud_artifact_link", captured, () => new SupaCloudArtifactLinkError(true));
|
|
1410
|
+
return decodeArtifactLink(result, captured);
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
// src/bounded-rpc-fetch.ts
|
|
1415
|
+
var maxBytes = 1024 * 1024;
|
|
1416
|
+
function createBoundedRpcFetch(path, failure, fetchImpl = globalThis.fetch.bind(globalThis)) {
|
|
1417
|
+
return async (input, init) => {
|
|
1418
|
+
const url = new URL(input instanceof Request ? input.url : input.toString());
|
|
1419
|
+
if (!path.test(url.pathname))
|
|
1420
|
+
return fetchImpl(input, init);
|
|
1421
|
+
const request = new Request(input, init);
|
|
1422
|
+
if (request.signal.aborted)
|
|
1423
|
+
throw failure();
|
|
1424
|
+
const controller = new AbortController;
|
|
1425
|
+
const cancel = () => controller.abort();
|
|
1426
|
+
request.signal.addEventListener("abort", cancel, { once: true });
|
|
1427
|
+
let reader;
|
|
1428
|
+
const abortRead = () => {
|
|
1429
|
+
reader?.cancel().catch(() => {});
|
|
1430
|
+
};
|
|
1431
|
+
let rejectAbort = () => {};
|
|
1432
|
+
const aborted = new Promise((_, reject) => {
|
|
1433
|
+
rejectAbort = () => {
|
|
1434
|
+
abortRead();
|
|
1435
|
+
reject(failure());
|
|
1436
|
+
};
|
|
1437
|
+
controller.signal.addEventListener("abort", rejectAbort, { once: true });
|
|
1438
|
+
});
|
|
1439
|
+
const timer = setTimeout(cancel, 15000);
|
|
1440
|
+
const read = async () => {
|
|
1441
|
+
const response = await fetchImpl(new Request(request, {
|
|
1442
|
+
signal: controller.signal,
|
|
1443
|
+
redirect: "error",
|
|
1444
|
+
cache: "no-store"
|
|
1445
|
+
}));
|
|
1446
|
+
if (controller.signal.aborted) {
|
|
1447
|
+
response.body?.cancel().catch(() => {});
|
|
1448
|
+
throw failure();
|
|
1449
|
+
}
|
|
1450
|
+
try {
|
|
1451
|
+
if (response.redirected || response.status >= 300 && response.status < 400 || !response.body)
|
|
1452
|
+
throw failure();
|
|
1453
|
+
const mediaType = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
|
|
1454
|
+
const length = response.headers.get("content-length");
|
|
1455
|
+
if (mediaType !== "application/json" || length !== null && (!/^\d+$/.test(length) || Number(length) > maxBytes))
|
|
1456
|
+
throw failure();
|
|
1457
|
+
reader = response.body.getReader();
|
|
1458
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
1459
|
+
let bytes = 0;
|
|
1460
|
+
let content = "";
|
|
1461
|
+
while (true) {
|
|
1462
|
+
controller.signal.throwIfAborted();
|
|
1463
|
+
const chunk = await reader.read();
|
|
1464
|
+
controller.signal.throwIfAborted();
|
|
1465
|
+
if (chunk.done)
|
|
1466
|
+
break;
|
|
1467
|
+
bytes += chunk.value.byteLength;
|
|
1468
|
+
if (bytes > maxBytes)
|
|
1469
|
+
throw failure();
|
|
1470
|
+
content += decoder.decode(chunk.value, { stream: true });
|
|
1471
|
+
}
|
|
1472
|
+
content += decoder.decode();
|
|
1473
|
+
const headers = new Headers(response.headers);
|
|
1474
|
+
headers.delete("content-length");
|
|
1475
|
+
headers.delete("content-encoding");
|
|
1476
|
+
return new Response(content, { status: response.status, statusText: response.statusText, headers });
|
|
1477
|
+
} finally {
|
|
1478
|
+
if (reader) {
|
|
1479
|
+
abortRead();
|
|
1480
|
+
reader.releaseLock();
|
|
1481
|
+
} else {
|
|
1482
|
+
response.body?.cancel().catch(() => {});
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
};
|
|
1486
|
+
try {
|
|
1487
|
+
return await Promise.race([read(), aborted]);
|
|
1488
|
+
} catch {
|
|
1489
|
+
throw failure();
|
|
1490
|
+
} finally {
|
|
1491
|
+
clearTimeout(timer);
|
|
1492
|
+
controller.abort();
|
|
1493
|
+
request.signal.removeEventListener("abort", cancel);
|
|
1494
|
+
controller.signal.removeEventListener("abort", rejectAbort);
|
|
1495
|
+
}
|
|
1496
|
+
};
|
|
8
1497
|
}
|
|
9
1498
|
|
|
10
|
-
// src/
|
|
11
|
-
class
|
|
12
|
-
|
|
13
|
-
constructor(
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
return invokeServiceRoleRpc(this.supabase, "supacloud_workflow_start", request);
|
|
18
|
-
}
|
|
19
|
-
claim(request) {
|
|
20
|
-
return invokeServiceRoleRpc(this.supabase, "supacloud_workflow_claim", request);
|
|
1499
|
+
// src/oauth-clients.ts
|
|
1500
|
+
class SupaCloudOAuthClientError extends SupaCloudApiError {
|
|
1501
|
+
mutationMayHaveApplied;
|
|
1502
|
+
constructor(code, status = 0, mutationMayHaveApplied = false) {
|
|
1503
|
+
super("OAuth client operation failed", status, { code, mutation_may_have_applied: mutationMayHaveApplied });
|
|
1504
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
1505
|
+
this.name = "SupaCloudOAuthClientError";
|
|
21
1506
|
}
|
|
22
|
-
|
|
23
|
-
|
|
1507
|
+
}
|
|
1508
|
+
function invalid4() {
|
|
1509
|
+
throw new SupaCloudOAuthClientError("INVALID_OAUTH_CLIENT_RESPONSE");
|
|
1510
|
+
}
|
|
1511
|
+
function isRecord2(value) {
|
|
1512
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1513
|
+
}
|
|
1514
|
+
function record5(value) {
|
|
1515
|
+
return isRecord2(value) ? value : invalid4();
|
|
1516
|
+
}
|
|
1517
|
+
function text3(value, max = 2048) {
|
|
1518
|
+
if (typeof value !== "string" || new TextEncoder().encode(value).length > max || /[\u0000-\u001f\u007f]/.test(value))
|
|
1519
|
+
return invalid4();
|
|
1520
|
+
return value;
|
|
1521
|
+
}
|
|
1522
|
+
function id3(value) {
|
|
1523
|
+
const valueId = text3(value, 36);
|
|
1524
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(valueId) ? valueId : invalid4();
|
|
1525
|
+
}
|
|
1526
|
+
function uri(value, redirect = false) {
|
|
1527
|
+
const input = text3(value);
|
|
1528
|
+
if (!input && !redirect)
|
|
1529
|
+
return input;
|
|
1530
|
+
if (!input || /[\s\\#]/.test(input))
|
|
1531
|
+
return invalid4();
|
|
1532
|
+
let url;
|
|
1533
|
+
try {
|
|
1534
|
+
url = new URL(input);
|
|
1535
|
+
} catch {
|
|
1536
|
+
return invalid4();
|
|
1537
|
+
}
|
|
1538
|
+
if (url.username || url.password || (redirect ? /^(javascript|data|blob|file|about):$/.test(url.protocol) : !/^https?:$/.test(url.protocol)))
|
|
1539
|
+
return invalid4();
|
|
1540
|
+
return input;
|
|
1541
|
+
}
|
|
1542
|
+
function array(value, decode, max) {
|
|
1543
|
+
if (!Array.isArray(value) || !value.length || value.length > max)
|
|
1544
|
+
return invalid4();
|
|
1545
|
+
const result = value.map((value) => decode(value));
|
|
1546
|
+
if (new Set(result).size !== result.length)
|
|
1547
|
+
return invalid4();
|
|
1548
|
+
return result;
|
|
1549
|
+
}
|
|
1550
|
+
function method(value) {
|
|
1551
|
+
return value === "none" || value === "client_secret_basic" || value === "client_secret_post" ? value : invalid4();
|
|
1552
|
+
}
|
|
1553
|
+
function date(value) {
|
|
1554
|
+
const input = text3(value, 64);
|
|
1555
|
+
const parts = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|[+-](\d{2}):(\d{2}))$/.exec(input);
|
|
1556
|
+
if (!parts)
|
|
1557
|
+
return invalid4();
|
|
1558
|
+
const year = Number(parts[1]), month = Number(parts[2]), day = Number(parts[3]);
|
|
1559
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
1560
|
+
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
1561
|
+
if (month < 1 || month > 12 || day < 1 || day > (days[month - 1] ?? 0) || Number(parts[4]) > 23 || Number(parts[5]) > 59 || Number(parts[6]) > 59 || Number(parts[7] ?? 0) > 23 || Number(parts[8] ?? 0) > 59 || !Number.isFinite(Date.parse(input)))
|
|
1562
|
+
return invalid4();
|
|
1563
|
+
return input;
|
|
1564
|
+
}
|
|
1565
|
+
function fields(data) {
|
|
1566
|
+
const result = {};
|
|
1567
|
+
if (data.client_name !== undefined)
|
|
1568
|
+
result.client_name = text3(data.client_name, 1024);
|
|
1569
|
+
if (data.redirect_uris !== undefined)
|
|
1570
|
+
result.redirect_uris = array(data.redirect_uris, (value) => uri(value, true), 100);
|
|
1571
|
+
if (data.token_endpoint_auth_method !== undefined)
|
|
1572
|
+
result.token_endpoint_auth_method = method(data.token_endpoint_auth_method);
|
|
1573
|
+
if (data.grant_types !== undefined) {
|
|
1574
|
+
result.grant_types = array(data.grant_types, (value) => value === "authorization_code" || value === "refresh_token" ? value : invalid4(), 2);
|
|
1575
|
+
}
|
|
1576
|
+
if (data.client_uri !== undefined)
|
|
1577
|
+
result.client_uri = uri(data.client_uri);
|
|
1578
|
+
if (data.logo_uri !== undefined)
|
|
1579
|
+
result.logo_uri = uri(data.logo_uri);
|
|
1580
|
+
return result;
|
|
1581
|
+
}
|
|
1582
|
+
function decodeClient(value, secret = false) {
|
|
1583
|
+
const data = record5(value);
|
|
1584
|
+
const { token_endpoint_auth_method: authMethod, ...optional } = fields(data);
|
|
1585
|
+
const metadata = { ...optional, client_id: id3(data.client_id) };
|
|
1586
|
+
if (data.response_types !== undefined)
|
|
1587
|
+
metadata.response_types = array(data.response_types, (value) => value === "code" ? value : invalid4(), 1);
|
|
1588
|
+
if (data.registration_type !== undefined) {
|
|
1589
|
+
if (data.registration_type !== "manual" && data.registration_type !== "dynamic")
|
|
1590
|
+
return invalid4();
|
|
1591
|
+
metadata.registration_type = data.registration_type;
|
|
1592
|
+
}
|
|
1593
|
+
if (data.created_at !== undefined)
|
|
1594
|
+
metadata.created_at = date(data.created_at);
|
|
1595
|
+
if (data.updated_at !== undefined)
|
|
1596
|
+
metadata.updated_at = date(data.updated_at);
|
|
1597
|
+
if (data.client_type === "public") {
|
|
1598
|
+
if (data.client_secret !== undefined || authMethod !== undefined && authMethod !== "none")
|
|
1599
|
+
return invalid4();
|
|
1600
|
+
return { ...metadata, client_type: "public", ...authMethod === undefined ? {} : { token_endpoint_auth_method: "none" } };
|
|
1601
|
+
}
|
|
1602
|
+
if (data.client_type !== "confidential" || authMethod === "none")
|
|
1603
|
+
return invalid4();
|
|
1604
|
+
const result = {
|
|
1605
|
+
...metadata,
|
|
1606
|
+
client_type: "confidential",
|
|
1607
|
+
...authMethod === undefined ? {} : { token_endpoint_auth_method: authMethod }
|
|
1608
|
+
};
|
|
1609
|
+
if (!secret && data.client_secret !== undefined)
|
|
1610
|
+
return invalid4();
|
|
1611
|
+
if (secret) {
|
|
1612
|
+
const clientSecret = text3(data.client_secret, 4096);
|
|
1613
|
+
if (!clientSecret || clientSecret !== clientSecret.trim())
|
|
1614
|
+
return invalid4();
|
|
1615
|
+
result.client_secret = clientSecret;
|
|
1616
|
+
}
|
|
1617
|
+
return result;
|
|
1618
|
+
}
|
|
1619
|
+
function decodeCreated(value) {
|
|
1620
|
+
const client = decodeClient(value, true);
|
|
1621
|
+
if (client.client_type === "public")
|
|
1622
|
+
return client;
|
|
1623
|
+
if (!client.client_secret)
|
|
1624
|
+
return invalid4();
|
|
1625
|
+
return { ...client, client_secret: client.client_secret };
|
|
1626
|
+
}
|
|
1627
|
+
function decodeList(value) {
|
|
1628
|
+
const data = record5(value);
|
|
1629
|
+
if (!Array.isArray(data.clients) || data.clients.length > 5000)
|
|
1630
|
+
return invalid4();
|
|
1631
|
+
const clients = data.clients.map((value) => decodeClient(value));
|
|
1632
|
+
if (new Set(clients.map((client) => client.client_id)).size !== clients.length)
|
|
1633
|
+
return invalid4();
|
|
1634
|
+
return { clients };
|
|
1635
|
+
}
|
|
1636
|
+
function updateInput(value, create = false) {
|
|
1637
|
+
const data = record5(value);
|
|
1638
|
+
const allowed = ["client_name", "redirect_uris", "token_endpoint_auth_method", "grant_types", "client_uri", "logo_uri"];
|
|
1639
|
+
if (create)
|
|
1640
|
+
allowed.push("client_type");
|
|
1641
|
+
if (Object.keys(data).some((key) => !allowed.includes(key)))
|
|
1642
|
+
return invalid4();
|
|
1643
|
+
const result = fields(data);
|
|
1644
|
+
if (!create && !Object.keys(result).length)
|
|
1645
|
+
return invalid4();
|
|
1646
|
+
return result;
|
|
1647
|
+
}
|
|
1648
|
+
function createInput(value) {
|
|
1649
|
+
const data = record5(value);
|
|
1650
|
+
const { token_endpoint_auth_method: authMethod, ...rest } = updateInput(value, true);
|
|
1651
|
+
if (!rest.redirect_uris)
|
|
1652
|
+
return invalid4();
|
|
1653
|
+
const common = { ...rest, redirect_uris: rest.redirect_uris };
|
|
1654
|
+
if (data.client_type === "public") {
|
|
1655
|
+
if (authMethod !== undefined && authMethod !== "none")
|
|
1656
|
+
return invalid4();
|
|
1657
|
+
return { ...common, client_type: "public", ...authMethod === undefined ? {} : { token_endpoint_auth_method: "none" } };
|
|
1658
|
+
}
|
|
1659
|
+
if (data.client_type === "confidential") {
|
|
1660
|
+
if (authMethod === "none")
|
|
1661
|
+
return invalid4();
|
|
1662
|
+
return { ...common, client_type: "confidential", ...authMethod === undefined ? {} : { token_endpoint_auth_method: authMethod } };
|
|
1663
|
+
}
|
|
1664
|
+
if (data.client_type !== undefined)
|
|
1665
|
+
return invalid4();
|
|
1666
|
+
return { ...common, ...authMethod === undefined ? {} : { token_endpoint_auth_method: authMethod } };
|
|
1667
|
+
}
|
|
1668
|
+
function validateInput(decode) {
|
|
1669
|
+
try {
|
|
1670
|
+
return decode();
|
|
1671
|
+
} catch {
|
|
1672
|
+
throw new SupaCloudOAuthClientError("INVALID_OAUTH_CLIENT_INPUT");
|
|
24
1673
|
}
|
|
25
|
-
|
|
26
|
-
|
|
1674
|
+
}
|
|
1675
|
+
function matches(client, input) {
|
|
1676
|
+
for (const key of ["client_name", "client_uri", "logo_uri"]) {
|
|
1677
|
+
if (input[key] !== undefined && input[key] !== (client[key] ?? ""))
|
|
1678
|
+
return invalid4();
|
|
27
1679
|
}
|
|
28
|
-
|
|
29
|
-
return
|
|
1680
|
+
if (input.token_endpoint_auth_method !== undefined && input.token_endpoint_auth_method !== client.token_endpoint_auth_method)
|
|
1681
|
+
return invalid4();
|
|
1682
|
+
for (const key of ["redirect_uris", "grant_types"]) {
|
|
1683
|
+
const expected = input[key], actual = client[key];
|
|
1684
|
+
const expectedValues = new Set(expected);
|
|
1685
|
+
if (expected && (!actual || actual.length !== expected.length || actual.some((value) => !expectedValues.has(value))))
|
|
1686
|
+
return invalid4();
|
|
30
1687
|
}
|
|
31
|
-
|
|
32
|
-
|
|
1688
|
+
}
|
|
1689
|
+
function baseUrl(value, session) {
|
|
1690
|
+
if (/[\s\\?#]/.test(value))
|
|
1691
|
+
return invalid4();
|
|
1692
|
+
if (session && value === "")
|
|
1693
|
+
return "";
|
|
1694
|
+
let url;
|
|
1695
|
+
try {
|
|
1696
|
+
url = new URL(value);
|
|
1697
|
+
} catch {
|
|
1698
|
+
return invalid4();
|
|
1699
|
+
}
|
|
1700
|
+
if (!/^https?:$/.test(url.protocol) || url.username || url.password || url.search || url.hash || url.href.replace(/\/$/, "") !== value.replace(/\/$/, ""))
|
|
1701
|
+
return invalid4();
|
|
1702
|
+
if (session)
|
|
1703
|
+
return invalid4();
|
|
1704
|
+
return url.href.replace(/\/$/, "");
|
|
1705
|
+
}
|
|
1706
|
+
async function readText(response, signal, max) {
|
|
1707
|
+
if (!response.body)
|
|
1708
|
+
return "";
|
|
1709
|
+
const reader = response.body.getReader();
|
|
1710
|
+
const abort = () => {
|
|
1711
|
+
reader.cancel().catch(() => {});
|
|
1712
|
+
};
|
|
1713
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
1714
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
1715
|
+
let size = 0, text = "";
|
|
1716
|
+
try {
|
|
1717
|
+
signal.throwIfAborted();
|
|
1718
|
+
for (;; ) {
|
|
1719
|
+
const part = await reader.read();
|
|
1720
|
+
signal.throwIfAborted();
|
|
1721
|
+
if (part.done)
|
|
1722
|
+
break;
|
|
1723
|
+
size += part.value.byteLength;
|
|
1724
|
+
if (size > max)
|
|
1725
|
+
return invalid4();
|
|
1726
|
+
text += decoder.decode(part.value, { stream: true });
|
|
1727
|
+
}
|
|
1728
|
+
return text + decoder.decode();
|
|
1729
|
+
} finally {
|
|
1730
|
+
signal.removeEventListener("abort", abort);
|
|
1731
|
+
reader.cancel().catch(() => {});
|
|
1732
|
+
reader.releaseLock();
|
|
33
1733
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
class SupaCloudOAuthClientsClient {
|
|
1737
|
+
base;
|
|
1738
|
+
send;
|
|
1739
|
+
token;
|
|
1740
|
+
constructor(options) {
|
|
1741
|
+
this.base = validateInput(() => {
|
|
1742
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(options.projectRef))
|
|
1743
|
+
return invalid4();
|
|
1744
|
+
return `${baseUrl(options.managementApiUrl, options.sessionRequest !== undefined)}/v1/projects/${options.projectRef}/auth/oauth-clients`;
|
|
38
1745
|
});
|
|
1746
|
+
if (options.sessionRequest !== undefined) {
|
|
1747
|
+
if (typeof options.sessionRequest !== "function" || options.getAccessToken !== undefined || options.request !== undefined) {
|
|
1748
|
+
throw new SupaCloudOAuthClientError("INVALID_OAUTH_CLIENT_INPUT");
|
|
1749
|
+
}
|
|
1750
|
+
this.send = options.sessionRequest;
|
|
1751
|
+
this.token = null;
|
|
1752
|
+
} else {
|
|
1753
|
+
if (typeof options.getAccessToken !== "function" || options.request !== undefined && typeof options.request !== "function") {
|
|
1754
|
+
throw new SupaCloudOAuthClientError("INVALID_OAUTH_CLIENT_INPUT");
|
|
1755
|
+
}
|
|
1756
|
+
this.send = options.request ?? ((url, options) => fetch(url, options));
|
|
1757
|
+
this.token = options.getAccessToken;
|
|
1758
|
+
}
|
|
39
1759
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
1760
|
+
async request(suffix, method, body, status, decode, options) {
|
|
1761
|
+
const signal = options.signal, timeoutMs = options.timeoutMs ?? 15000;
|
|
1762
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 120000) {
|
|
1763
|
+
throw new SupaCloudOAuthClientError("INVALID_OAUTH_CLIENT_INPUT");
|
|
1764
|
+
}
|
|
1765
|
+
const encoded = body === undefined ? undefined : JSON.stringify(body);
|
|
1766
|
+
const controller = new AbortController;
|
|
1767
|
+
let rejectStopped = () => {};
|
|
1768
|
+
const stopped = new Promise((_, reject) => {
|
|
1769
|
+
rejectStopped = reject;
|
|
47
1770
|
});
|
|
1771
|
+
const mutation = method !== "GET";
|
|
1772
|
+
let sent = false;
|
|
1773
|
+
const stop = (code) => {
|
|
1774
|
+
controller.abort();
|
|
1775
|
+
rejectStopped(new SupaCloudOAuthClientError(code, 0, sent && mutation));
|
|
1776
|
+
};
|
|
1777
|
+
const abort = () => stop("OAUTH_CLIENT_REQUEST_CANCELLED");
|
|
1778
|
+
if (signal?.aborted)
|
|
1779
|
+
throw new SupaCloudOAuthClientError("OAUTH_CLIENT_REQUEST_CANCELLED");
|
|
1780
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
1781
|
+
const timer = setTimeout(() => stop("OAUTH_CLIENT_REQUEST_TIMED_OUT"), timeoutMs);
|
|
1782
|
+
const work = async () => {
|
|
1783
|
+
const headers = new Headers({ accept: "application/json" });
|
|
1784
|
+
if (this.token) {
|
|
1785
|
+
const token = await this.token();
|
|
1786
|
+
controller.signal.throwIfAborted();
|
|
1787
|
+
if (typeof token !== "string" || !token || /[\s\u0000-\u001f\u007f]/.test(token)) {
|
|
1788
|
+
throw new SupaCloudOAuthClientError("OAUTH_CLIENT_TOKEN_UNAVAILABLE");
|
|
1789
|
+
}
|
|
1790
|
+
headers.set("authorization", `Bearer ${token}`);
|
|
1791
|
+
}
|
|
1792
|
+
if (encoded !== undefined)
|
|
1793
|
+
headers.set("content-type", "application/json");
|
|
1794
|
+
controller.signal.throwIfAborted();
|
|
1795
|
+
sent = true;
|
|
1796
|
+
const response = await this.send(`${this.base}${suffix}`, {
|
|
1797
|
+
method,
|
|
1798
|
+
headers,
|
|
1799
|
+
...encoded === undefined ? {} : { body: encoded },
|
|
1800
|
+
signal: controller.signal,
|
|
1801
|
+
redirect: "error",
|
|
1802
|
+
cache: "no-store",
|
|
1803
|
+
credentials: this.token ? "omit" : "same-origin"
|
|
1804
|
+
});
|
|
1805
|
+
try {
|
|
1806
|
+
controller.signal.throwIfAborted();
|
|
1807
|
+
if (response.redirected || response.status >= 300 && response.status < 400)
|
|
1808
|
+
return invalid4();
|
|
1809
|
+
if (response.status === 204 && status === 204) {
|
|
1810
|
+
if (await readText(response, controller.signal, 0) !== "")
|
|
1811
|
+
return invalid4();
|
|
1812
|
+
return decode(undefined);
|
|
1813
|
+
}
|
|
1814
|
+
if (!/^application\/(?:json|[a-z0-9.+-]+\+json)(?:;|$)/i.test(response.headers.get("content-type") ?? ""))
|
|
1815
|
+
return invalid4();
|
|
1816
|
+
const value = JSON.parse(await readText(response, controller.signal, response.ok && suffix === "" && method === "GET" ? 1024 * 1024 : 64 * 1024));
|
|
1817
|
+
if (!response.ok) {
|
|
1818
|
+
const data = record5(value);
|
|
1819
|
+
if (data.mutation_may_have_applied !== undefined && typeof data.mutation_may_have_applied !== "boolean")
|
|
1820
|
+
return invalid4();
|
|
1821
|
+
const code = typeof data.code === "string" && /^[A-Z0-9_]{1,80}$/.test(data.code) ? data.code : "OAUTH_CLIENT_REQUEST_FAILED";
|
|
1822
|
+
throw new SupaCloudOAuthClientError(code, response.status, mutation && (data.mutation_may_have_applied === true || response.status >= 500));
|
|
1823
|
+
}
|
|
1824
|
+
if (response.status !== status)
|
|
1825
|
+
return invalid4();
|
|
1826
|
+
return decode(value);
|
|
1827
|
+
} finally {
|
|
1828
|
+
response.body?.cancel().catch(() => {});
|
|
1829
|
+
}
|
|
1830
|
+
};
|
|
1831
|
+
try {
|
|
1832
|
+
return await Promise.race([work(), stopped]);
|
|
1833
|
+
} catch (error) {
|
|
1834
|
+
if (error instanceof SupaCloudOAuthClientError) {
|
|
1835
|
+
if (error.code === "INVALID_OAUTH_CLIENT_RESPONSE") {
|
|
1836
|
+
throw new SupaCloudOAuthClientError(error.code, error.status, sent && mutation);
|
|
1837
|
+
}
|
|
1838
|
+
throw error;
|
|
1839
|
+
}
|
|
1840
|
+
throw new SupaCloudOAuthClientError("OAUTH_CLIENT_REQUEST_FAILED", 0, sent && mutation);
|
|
1841
|
+
} finally {
|
|
1842
|
+
clearTimeout(timer);
|
|
1843
|
+
signal?.removeEventListener("abort", abort);
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
list(options = {}) {
|
|
1847
|
+
return this.request("", "GET", undefined, 200, decodeList, options);
|
|
1848
|
+
}
|
|
1849
|
+
async get(clientId, options = {}) {
|
|
1850
|
+
const target = validateInput(() => id3(clientId));
|
|
1851
|
+
return this.request(`/${target}`, "GET", undefined, 200, (value) => {
|
|
1852
|
+
const client = decodeClient(value);
|
|
1853
|
+
if (client.client_id !== target)
|
|
1854
|
+
return invalid4();
|
|
1855
|
+
return client;
|
|
1856
|
+
}, options);
|
|
1857
|
+
}
|
|
1858
|
+
async create(input, options = {}) {
|
|
1859
|
+
const submitted = validateInput(() => createInput(input));
|
|
1860
|
+
return this.request("", "POST", submitted, 201, (value) => {
|
|
1861
|
+
const client = decodeCreated(value);
|
|
1862
|
+
matches(client, submitted);
|
|
1863
|
+
const expectedType = submitted.client_type ?? (submitted.token_endpoint_auth_method === "none" ? "public" : "confidential");
|
|
1864
|
+
if (client.client_type !== expectedType || client.registration_type !== "manual")
|
|
1865
|
+
return invalid4();
|
|
1866
|
+
return client;
|
|
1867
|
+
}, options);
|
|
1868
|
+
}
|
|
1869
|
+
async update(clientId, input, options = {}) {
|
|
1870
|
+
const target = validateInput(() => id3(clientId)), submitted = validateInput(() => updateInput(input));
|
|
1871
|
+
return this.request(`/${target}`, "PUT", submitted, 200, (value) => {
|
|
1872
|
+
const client = decodeClient(value);
|
|
1873
|
+
if (client.client_id !== target)
|
|
1874
|
+
return invalid4();
|
|
1875
|
+
matches(client, submitted);
|
|
1876
|
+
return client;
|
|
1877
|
+
}, options);
|
|
1878
|
+
}
|
|
1879
|
+
async delete(clientId, options = {}) {
|
|
1880
|
+
const target = validateInput(() => id3(clientId));
|
|
1881
|
+
return this.request(`/${target}`, "DELETE", undefined, 204, (value) => {
|
|
1882
|
+
if (value !== undefined)
|
|
1883
|
+
return invalid4();
|
|
1884
|
+
}, options);
|
|
1885
|
+
}
|
|
1886
|
+
async regenerateSecret(clientId, options = {}) {
|
|
1887
|
+
const target = validateInput(() => id3(clientId));
|
|
1888
|
+
return this.request(`/${target}/regenerate-secret`, "POST", undefined, 200, (value) => {
|
|
1889
|
+
const client = decodeCreated(value);
|
|
1890
|
+
if (client.client_id !== target || client.client_type !== "confidential")
|
|
1891
|
+
return invalid4();
|
|
1892
|
+
return client;
|
|
1893
|
+
}, options);
|
|
48
1894
|
}
|
|
49
1895
|
}
|
|
50
1896
|
|
|
51
|
-
// src/
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
this.
|
|
1897
|
+
// src/oauth-server.ts
|
|
1898
|
+
class SupaCloudOAuthServerError extends SupaCloudApiError {
|
|
1899
|
+
code;
|
|
1900
|
+
mutationMayHaveApplied;
|
|
1901
|
+
constructor(message, code, mutationMayHaveApplied = false, status = 0) {
|
|
1902
|
+
super(message, status, { code, mutation_may_have_applied: mutationMayHaveApplied });
|
|
1903
|
+
this.code = code;
|
|
1904
|
+
this.mutationMayHaveApplied = mutationMayHaveApplied;
|
|
1905
|
+
this.name = "SupaCloudOAuthServerError";
|
|
58
1906
|
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
1907
|
+
}
|
|
1908
|
+
function invalid5(field = "payload") {
|
|
1909
|
+
throw new SupaCloudOAuthServerError(`Invalid OAuth Server response: ${field}`, "OAUTH_SERVER_INVALID");
|
|
1910
|
+
}
|
|
1911
|
+
function isRecord3(value) {
|
|
1912
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1913
|
+
}
|
|
1914
|
+
function record6(value) {
|
|
1915
|
+
return isRecord3(value) ? value : invalid5();
|
|
1916
|
+
}
|
|
1917
|
+
function text4(value, field, max = 4096) {
|
|
1918
|
+
return typeof value === "string" && value.length > 0 && value.length <= max && !/[\u0000-\u001f\u007f]/.test(value) ? value : invalid5(field);
|
|
1919
|
+
}
|
|
1920
|
+
function flag(value, field) {
|
|
1921
|
+
return typeof value === "boolean" ? value : invalid5(field);
|
|
1922
|
+
}
|
|
1923
|
+
function strings(value, field) {
|
|
1924
|
+
if (!Array.isArray(value) || value.length > 64)
|
|
1925
|
+
return invalid5(field);
|
|
1926
|
+
const result = value.map((item) => text4(item, field));
|
|
1927
|
+
return new Set(result).size === result.length ? result : invalid5(field);
|
|
1928
|
+
}
|
|
1929
|
+
function httpUrl(value, field) {
|
|
1930
|
+
const input = text4(value, field);
|
|
1931
|
+
let parsed;
|
|
1932
|
+
try {
|
|
1933
|
+
parsed = new URL(input);
|
|
1934
|
+
} catch {
|
|
1935
|
+
return invalid5(field);
|
|
65
1936
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
1937
|
+
if (!/^https?:$/.test(parsed.protocol) || parsed.username || parsed.password || /[\s\\?#]/.test(input) || parsed.href.replace(/\/$/, "") !== input.replace(/\/$/, ""))
|
|
1938
|
+
return invalid5(field);
|
|
1939
|
+
return input;
|
|
1940
|
+
}
|
|
1941
|
+
function authorizationPath(value) {
|
|
1942
|
+
const input = text4(value, "authorization_path");
|
|
1943
|
+
let decoded;
|
|
1944
|
+
try {
|
|
1945
|
+
decoded = decodeURIComponent(input);
|
|
1946
|
+
} catch {
|
|
1947
|
+
return invalid5("authorization_path");
|
|
1948
|
+
}
|
|
1949
|
+
if (!input.startsWith("/") || [input, decoded].some((part) => /[\\?#\u0000-\u001f\u007f]/.test(part) || part.includes("//") || part.split("/").some((segment) => segment === "." || segment === ".."))) {
|
|
1950
|
+
return invalid5("authorization_path");
|
|
1951
|
+
}
|
|
1952
|
+
return input;
|
|
1953
|
+
}
|
|
1954
|
+
function decodeStatus(value, projectRef) {
|
|
1955
|
+
const data = record6(value);
|
|
1956
|
+
if (data.project_ref !== projectRef)
|
|
1957
|
+
return invalid5("project_ref does not match request");
|
|
1958
|
+
if (data.account_isolated !== true)
|
|
1959
|
+
return invalid5("account_isolated");
|
|
1960
|
+
if (data.state_source !== "configuration")
|
|
1961
|
+
return invalid5("state_source");
|
|
1962
|
+
if (data.runtime_verified !== false)
|
|
1963
|
+
return invalid5("runtime_verified");
|
|
1964
|
+
const issuer = httpUrl(data.issuer, "issuer");
|
|
1965
|
+
if (issuer.endsWith("/"))
|
|
1966
|
+
return invalid5("issuer");
|
|
1967
|
+
function endpoint(field, suffix) {
|
|
1968
|
+
return data[field] === `${issuer}${suffix}` ? httpUrl(data[field], field) : invalid5(field);
|
|
1969
|
+
}
|
|
1970
|
+
const metadata = httpUrl(data.oauth_authorization_server_metadata_url, "oauth_authorization_server_metadata_url");
|
|
1971
|
+
if (!new URL(metadata).pathname.endsWith("/.well-known/oauth-authorization-server/auth/v1")) {
|
|
1972
|
+
return invalid5("oauth_authorization_server_metadata_url");
|
|
1973
|
+
}
|
|
1974
|
+
const common = {
|
|
1975
|
+
project_ref: projectRef,
|
|
1976
|
+
organization_id: data.organization_id === null ? null : text4(data.organization_id, "organization_id", 128),
|
|
1977
|
+
account_isolated: true,
|
|
1978
|
+
state_source: "configuration",
|
|
1979
|
+
runtime_verified: false,
|
|
1980
|
+
enabled: flag(data.enabled, "enabled"),
|
|
1981
|
+
allow_dynamic_registration: flag(data.allow_dynamic_registration, "allow_dynamic_registration"),
|
|
1982
|
+
issuer,
|
|
1983
|
+
authorization_path: authorizationPath(data.authorization_path),
|
|
1984
|
+
discovery_url: endpoint("discovery_url", "/.well-known/openid-configuration"),
|
|
1985
|
+
oauth_authorization_server_metadata_url: metadata,
|
|
1986
|
+
jwks_url: endpoint("jwks_url", "/.well-known/jwks.json"),
|
|
1987
|
+
authorization_endpoint: endpoint("authorization_endpoint", "/oauth/authorize"),
|
|
1988
|
+
token_endpoint: endpoint("token_endpoint", "/oauth/token"),
|
|
1989
|
+
userinfo_endpoint: endpoint("userinfo_endpoint", "/oauth/userinfo"),
|
|
1990
|
+
registration_endpoint: endpoint("registration_endpoint", "/oauth/clients/register"),
|
|
1991
|
+
warnings: strings(data.warnings, "warnings")
|
|
1992
|
+
};
|
|
1993
|
+
if (data.signing_alg === "not_migrated") {
|
|
1994
|
+
if (data.key_id !== undefined)
|
|
1995
|
+
return invalid5("key_id");
|
|
1996
|
+
if (data.oidc_id_token_ready !== false)
|
|
1997
|
+
return invalid5("oidc_id_token_ready");
|
|
1998
|
+
if (data.migration_status !== "not_migrated")
|
|
1999
|
+
return invalid5("migration_status");
|
|
2000
|
+
return { ...common, signing_alg: "not_migrated", oidc_id_token_ready: false, migration_status: "not_migrated" };
|
|
2001
|
+
}
|
|
2002
|
+
if (data.signing_alg !== "ES256" && data.signing_alg !== "RS256")
|
|
2003
|
+
return invalid5("signing_alg");
|
|
2004
|
+
if (data.oidc_id_token_ready !== true)
|
|
2005
|
+
return invalid5("oidc_id_token_ready");
|
|
2006
|
+
const key_id = text4(data.key_id, "key_id", 256);
|
|
2007
|
+
if (data.signing_alg === "ES256") {
|
|
2008
|
+
if (data.migration_status !== "oidc_es256_migrated")
|
|
2009
|
+
return invalid5("migration_status");
|
|
2010
|
+
return { ...common, signing_alg: "ES256", key_id, oidc_id_token_ready: true, migration_status: "oidc_es256_migrated" };
|
|
2011
|
+
}
|
|
2012
|
+
if (data.migration_status !== "oidc_rs256_migrated")
|
|
2013
|
+
return invalid5("migration_status");
|
|
2014
|
+
return { ...common, signing_alg: "RS256", key_id, oidc_id_token_ready: true, migration_status: "oidc_rs256_migrated" };
|
|
2015
|
+
}
|
|
2016
|
+
function decodeDiscovery(value, status) {
|
|
2017
|
+
const data = record6(value);
|
|
2018
|
+
for (const [key, expected] of [
|
|
2019
|
+
["issuer", status.issuer],
|
|
2020
|
+
["authorization_endpoint", status.authorization_endpoint],
|
|
2021
|
+
["token_endpoint", status.token_endpoint],
|
|
2022
|
+
["jwks_uri", status.jwks_url]
|
|
2023
|
+
])
|
|
2024
|
+
if (data[key] !== expected)
|
|
2025
|
+
return invalid5(`discovery.${key}`);
|
|
2026
|
+
const responseTypes = strings(data.response_types_supported, "response_types_supported");
|
|
2027
|
+
const subjects = strings(data.subject_types_supported, "subject_types_supported");
|
|
2028
|
+
const algorithms = strings(data.id_token_signing_alg_values_supported, "id_token_signing_alg_values_supported");
|
|
2029
|
+
if (!responseTypes.includes("code") || subjects.length === 0 || subjects.some((subject) => subject !== "public" && subject !== "pairwise") || !algorithms.includes(status.signing_alg))
|
|
2030
|
+
return invalid5("discovery capabilities");
|
|
2031
|
+
const result = {
|
|
2032
|
+
issuer: status.issuer,
|
|
2033
|
+
authorization_endpoint: status.authorization_endpoint,
|
|
2034
|
+
token_endpoint: status.token_endpoint,
|
|
2035
|
+
jwks_uri: status.jwks_url,
|
|
2036
|
+
response_types_supported: responseTypes,
|
|
2037
|
+
subject_types_supported: subjects,
|
|
2038
|
+
id_token_signing_alg_values_supported: algorithms
|
|
2039
|
+
};
|
|
2040
|
+
for (const field of ["userinfo_endpoint", "registration_endpoint"]) {
|
|
2041
|
+
if (data[field] === undefined)
|
|
2042
|
+
continue;
|
|
2043
|
+
if (data[field] !== status[field])
|
|
2044
|
+
return invalid5(`discovery.${field}`);
|
|
2045
|
+
result[field] = status[field];
|
|
2046
|
+
}
|
|
2047
|
+
return result;
|
|
2048
|
+
}
|
|
2049
|
+
function base64url(value, field) {
|
|
2050
|
+
const encoded = text4(value, field, 2048);
|
|
2051
|
+
if (!/^[A-Za-z0-9_-]+$/.test(encoded))
|
|
2052
|
+
return invalid5(field);
|
|
2053
|
+
let binary;
|
|
2054
|
+
try {
|
|
2055
|
+
binary = atob(encoded.replace(/-/g, "+").replace(/_/g, "/"));
|
|
2056
|
+
} catch {
|
|
2057
|
+
return invalid5(field);
|
|
2058
|
+
}
|
|
2059
|
+
if (btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") !== encoded)
|
|
2060
|
+
return invalid5(field);
|
|
2061
|
+
return { encoded, bytes: Uint8Array.from(binary, (char) => char.charCodeAt(0)) };
|
|
2062
|
+
}
|
|
2063
|
+
async function decodeJwks(value, status) {
|
|
2064
|
+
const input = record6(value).keys;
|
|
2065
|
+
if (!Array.isArray(input) || input.length === 0 || input.length > 16)
|
|
2066
|
+
return invalid5("jwks.keys");
|
|
2067
|
+
const keys = [];
|
|
2068
|
+
const ids = new Set;
|
|
2069
|
+
for (const item of input) {
|
|
2070
|
+
const data = record6(item);
|
|
2071
|
+
if (["d", "p", "q", "dp", "dq", "qi", "oth", "k"].some((field) => (field in data)))
|
|
2072
|
+
return invalid5("private JWK");
|
|
2073
|
+
const kid = text4(data.kid, "kid", 256);
|
|
2074
|
+
if (ids.has(kid))
|
|
2075
|
+
return invalid5("duplicate kid");
|
|
2076
|
+
ids.add(kid);
|
|
2077
|
+
if (data.use !== undefined && data.use !== "sig")
|
|
2078
|
+
return invalid5("JWK use");
|
|
2079
|
+
if (data.key_ops !== undefined && strings(data.key_ops, "key_ops").join(",") !== "verify")
|
|
2080
|
+
return invalid5("key_ops");
|
|
2081
|
+
let key;
|
|
2082
|
+
if (data.kty === "EC") {
|
|
2083
|
+
if (data.crv !== "P-256" || data.alg !== "ES256")
|
|
2084
|
+
return invalid5("EC algorithm");
|
|
2085
|
+
const x = base64url(data.x, "x"), y = base64url(data.y, "y");
|
|
2086
|
+
if (x.bytes.length !== 32 || y.bytes.length !== 32)
|
|
2087
|
+
return invalid5("EC coordinates");
|
|
2088
|
+
key = { kty: "EC", crv: "P-256", x: x.encoded, y: y.encoded, alg: "ES256", kid, use: "sig" };
|
|
2089
|
+
} else if (data.kty === "RSA") {
|
|
2090
|
+
if (data.alg !== "RS256")
|
|
2091
|
+
return invalid5("RSA algorithm");
|
|
2092
|
+
const n = base64url(data.n, "n"), e = base64url(data.e, "e");
|
|
2093
|
+
const first = n.bytes[0];
|
|
2094
|
+
if (first === undefined || first === 0 || n.bytes.length > 1024 || (n.bytes.length - 1) * 8 + (32 - Math.clz32(first)) < 2048 || e.bytes.length === 0 || e.bytes.length > 4 || e.bytes[0] === 0)
|
|
2095
|
+
return invalid5("RSA parameters");
|
|
2096
|
+
const exponent = e.bytes.reduce((result, byte) => result * 256 + byte, 0);
|
|
2097
|
+
if (exponent < 3 || exponent % 2 === 0)
|
|
2098
|
+
return invalid5("RSA exponent");
|
|
2099
|
+
key = { kty: "RSA", n: n.encoded, e: e.encoded, alg: "RS256", kid, use: "sig" };
|
|
2100
|
+
} else
|
|
2101
|
+
return invalid5("JWK kty");
|
|
2102
|
+
try {
|
|
2103
|
+
await crypto.subtle.importKey("jwk", key, key.kty === "EC" ? { name: "ECDSA", namedCurve: "P-256" } : { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]);
|
|
2104
|
+
} catch {
|
|
2105
|
+
return invalid5("JWK public material");
|
|
2106
|
+
}
|
|
2107
|
+
keys.push(key);
|
|
2108
|
+
}
|
|
2109
|
+
if (!keys.some((key) => key.kid === status.key_id && key.alg === status.signing_alg))
|
|
2110
|
+
return invalid5("configured JWK");
|
|
2111
|
+
return { keys };
|
|
2112
|
+
}
|
|
2113
|
+
|
|
2114
|
+
class Operation {
|
|
2115
|
+
controller = new AbortController;
|
|
2116
|
+
mutationStarted = false;
|
|
2117
|
+
bodies = new Set;
|
|
2118
|
+
async run(work) {
|
|
2119
|
+
let timer;
|
|
2120
|
+
const timeout = new Promise((_, reject) => {
|
|
2121
|
+
timer = setTimeout(() => {
|
|
2122
|
+
this.controller.abort();
|
|
2123
|
+
reject(new SupaCloudOAuthServerError("OAuth Server request timed out", "OAUTH_SERVER_TIMEOUT", this.mutationStarted));
|
|
2124
|
+
}, 15000);
|
|
2125
|
+
});
|
|
2126
|
+
try {
|
|
2127
|
+
return await Promise.race([work(), timeout]);
|
|
2128
|
+
} catch (error) {
|
|
2129
|
+
if (error instanceof SupaCloudOAuthServerError) {
|
|
2130
|
+
throw new SupaCloudOAuthServerError(error.message, error.code, error.mutationMayHaveApplied || this.mutationStarted, error.status);
|
|
81
2131
|
}
|
|
2132
|
+
throw new SupaCloudOAuthServerError("OAuth Server request failed", "OAUTH_SERVER_REQUEST_FAILED", this.mutationStarted);
|
|
2133
|
+
} finally {
|
|
2134
|
+
clearTimeout(timer);
|
|
2135
|
+
this.controller.abort();
|
|
2136
|
+
for (const body of this.bodies)
|
|
2137
|
+
body.cancel().catch(() => {});
|
|
82
2138
|
}
|
|
83
|
-
return status;
|
|
84
2139
|
}
|
|
85
|
-
async
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
2140
|
+
async json(url, init = {}) {
|
|
2141
|
+
this.controller.signal.throwIfAborted();
|
|
2142
|
+
const response = await fetch(url, {
|
|
2143
|
+
...init,
|
|
2144
|
+
redirect: "error",
|
|
2145
|
+
credentials: "omit",
|
|
2146
|
+
cache: "no-store",
|
|
2147
|
+
signal: this.controller.signal
|
|
2148
|
+
});
|
|
2149
|
+
if (this.controller.signal.aborted) {
|
|
2150
|
+
response.body?.cancel().catch(() => {});
|
|
2151
|
+
this.controller.signal.throwIfAborted();
|
|
2152
|
+
}
|
|
2153
|
+
const body = response.body;
|
|
2154
|
+
if (body)
|
|
2155
|
+
this.bodies.add(body);
|
|
2156
|
+
if (response.redirected || response.status >= 300 && response.status < 400) {
|
|
2157
|
+
throw new SupaCloudOAuthServerError("OAuth Server returned an unsuccessful response", "OAUTH_SERVER_HTTP_ERROR", this.mutationStarted, response.status);
|
|
2158
|
+
}
|
|
2159
|
+
if (!body)
|
|
2160
|
+
return invalid5("empty body");
|
|
2161
|
+
const type = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
|
|
2162
|
+
if (type !== "application/json" && type !== "application/jwk-set+json")
|
|
2163
|
+
return invalid5("content-type");
|
|
2164
|
+
const length = response.headers.get("content-length");
|
|
2165
|
+
if (length !== null && (!/^\d+$/.test(length) || Number(length) > 65536))
|
|
2166
|
+
return invalid5("body size");
|
|
2167
|
+
const reader = body.getReader();
|
|
2168
|
+
const abort = () => {
|
|
2169
|
+
reader.cancel().catch(() => {});
|
|
2170
|
+
};
|
|
2171
|
+
this.controller.signal.addEventListener("abort", abort, { once: true });
|
|
2172
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
2173
|
+
let size = 0, content = "";
|
|
2174
|
+
try {
|
|
2175
|
+
while (true) {
|
|
2176
|
+
this.controller.signal.throwIfAborted();
|
|
2177
|
+
const chunk = await reader.read();
|
|
2178
|
+
this.controller.signal.throwIfAborted();
|
|
2179
|
+
if (chunk.done)
|
|
2180
|
+
break;
|
|
2181
|
+
size += chunk.value.byteLength;
|
|
2182
|
+
if (size > 65536)
|
|
2183
|
+
return invalid5("body size");
|
|
2184
|
+
content += decoder.decode(chunk.value, { stream: true });
|
|
2185
|
+
}
|
|
2186
|
+
content += decoder.decode();
|
|
2187
|
+
const value = JSON.parse(content);
|
|
2188
|
+
if (response.status !== 200) {
|
|
2189
|
+
const data = record6(value);
|
|
2190
|
+
const code = response.status === 503 && data.code === "SUPAUTH_DEPENDENT_REFRESH_FAILED" ? "SUPAUTH_DEPENDENT_REFRESH_FAILED" : "OAUTH_SERVER_HTTP_ERROR";
|
|
2191
|
+
throw new SupaCloudOAuthServerError("OAuth Server returned an unsuccessful response", code, this.mutationStarted, response.status);
|
|
2192
|
+
}
|
|
2193
|
+
return value;
|
|
2194
|
+
} finally {
|
|
2195
|
+
this.controller.signal.removeEventListener("abort", abort);
|
|
2196
|
+
reader.cancel().catch(() => {});
|
|
2197
|
+
reader.releaseLock();
|
|
2198
|
+
this.bodies.delete(body);
|
|
2199
|
+
}
|
|
90
2200
|
}
|
|
91
2201
|
}
|
|
92
2202
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
2203
|
+
class SupaCloudOAuthServerClient {
|
|
2204
|
+
base;
|
|
2205
|
+
projectRef;
|
|
2206
|
+
getAccessToken;
|
|
2207
|
+
constructor(options) {
|
|
2208
|
+
if (typeof options.projectRef !== "string" || !/^[A-Za-z0-9_-]{1,128}$/.test(options.projectRef))
|
|
2209
|
+
invalid5("project_ref");
|
|
2210
|
+
this.projectRef = options.projectRef;
|
|
2211
|
+
this.base = httpUrl(options.managementApiUrl, "managementApiUrl").replace(/\/$/, "") + `/v1/projects/${this.projectRef}/auth/oauth-server`;
|
|
2212
|
+
this.getAccessToken = options.getAccessToken;
|
|
2213
|
+
}
|
|
2214
|
+
async status(operation) {
|
|
2215
|
+
const token = text4(await this.getAccessToken(), "access token", 16384);
|
|
2216
|
+
return decodeStatus(await operation.json(this.base, {
|
|
2217
|
+
method: "GET",
|
|
2218
|
+
headers: { authorization: `Bearer ${token}` }
|
|
2219
|
+
}), this.projectRef);
|
|
2220
|
+
}
|
|
2221
|
+
getStatus() {
|
|
2222
|
+
const operation = new Operation;
|
|
2223
|
+
return operation.run(() => this.status(operation));
|
|
2224
|
+
}
|
|
2225
|
+
migrateToOidc(options = {}) {
|
|
2226
|
+
const operation = new Operation;
|
|
2227
|
+
return operation.run(async () => {
|
|
2228
|
+
const input = record6(options);
|
|
2229
|
+
const allow = input.allowDynamicRegistration === undefined ? false : flag(input.allowDynamicRegistration, "allowDynamicRegistration");
|
|
2230
|
+
const path = input.authorizationPath === undefined ? undefined : authorizationPath(input.authorizationPath);
|
|
2231
|
+
const before = await this.status(operation);
|
|
2232
|
+
const token = text4(await this.getAccessToken(), "access token", 16384);
|
|
2233
|
+
operation.controller.signal.throwIfAborted();
|
|
2234
|
+
operation.mutationStarted = true;
|
|
2235
|
+
const after = decodeStatus(await operation.json(`${this.base}/migrate`, {
|
|
2236
|
+
method: "POST",
|
|
2237
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
|
2238
|
+
body: JSON.stringify({ allow_dynamic_registration: allow, ...path === undefined ? {} : { authorization_path: path } })
|
|
2239
|
+
}), this.projectRef);
|
|
2240
|
+
if (!after.enabled || !after.oidc_id_token_ready || after.allow_dynamic_registration !== allow || after.authorization_path !== (path ?? before.authorization_path) || after.issuer !== before.issuer || after.organization_id !== before.organization_id || after.signing_alg !== (before.signing_alg === "not_migrated" ? "ES256" : before.signing_alg) || before.key_id !== undefined && after.key_id !== before.key_id)
|
|
2241
|
+
return invalid5("migration receipt");
|
|
2242
|
+
return after;
|
|
2243
|
+
});
|
|
101
2244
|
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
2245
|
+
publicDocument(field, decode) {
|
|
2246
|
+
const operation = new Operation;
|
|
2247
|
+
return operation.run(async () => {
|
|
2248
|
+
const status = await this.status(operation);
|
|
2249
|
+
if (!status.enabled || !status.oidc_id_token_ready)
|
|
2250
|
+
return invalid5("OAuth Server not configured");
|
|
2251
|
+
const value = await decode(await operation.json(status[field]), status);
|
|
2252
|
+
const after = await this.status(operation);
|
|
2253
|
+
if (JSON.stringify(status) !== JSON.stringify(after))
|
|
2254
|
+
return invalid5("configuration changed during public read");
|
|
2255
|
+
return value;
|
|
105
2256
|
});
|
|
106
2257
|
}
|
|
107
|
-
|
|
108
|
-
return
|
|
2258
|
+
getDiscovery() {
|
|
2259
|
+
return this.publicDocument("discovery_url", decodeDiscovery);
|
|
2260
|
+
}
|
|
2261
|
+
getJwks() {
|
|
2262
|
+
return this.publicDocument("jwks_url", decodeJwks);
|
|
2263
|
+
}
|
|
2264
|
+
buildAuthorizeUrl(options) {
|
|
2265
|
+
const operation = new Operation;
|
|
2266
|
+
return operation.run(async () => {
|
|
2267
|
+
const input = record6(options);
|
|
2268
|
+
const params = new URLSearchParams;
|
|
2269
|
+
params.set("client_id", text4(input.clientId, "clientId", 256));
|
|
2270
|
+
const redirect = text4(input.redirectUri, "redirectUri");
|
|
2271
|
+
let parsed;
|
|
2272
|
+
try {
|
|
2273
|
+
parsed = new URL(redirect);
|
|
2274
|
+
} catch {
|
|
2275
|
+
return invalid5("redirectUri");
|
|
2276
|
+
}
|
|
2277
|
+
if (!/^https?:$/.test(parsed.protocol) && !/^[a-z][a-z0-9+.-]*:$/.test(parsed.protocol) || /^(javascript|data|file|vbscript):$/.test(parsed.protocol) || parsed.username || parsed.password || parsed.hash || /[\s\\]/.test(redirect))
|
|
2278
|
+
return invalid5("redirectUri");
|
|
2279
|
+
params.set("redirect_uri", redirect);
|
|
2280
|
+
if (input.responseType !== undefined && input.responseType !== "code")
|
|
2281
|
+
return invalid5("responseType");
|
|
2282
|
+
params.set("response_type", "code");
|
|
2283
|
+
if (input.scope !== undefined) {
|
|
2284
|
+
const scope = Array.isArray(input.scope) ? strings(input.scope, "scope").join(" ") : text4(input.scope, "scope");
|
|
2285
|
+
if (!/^[\x21\x23-\x5b\x5d-\x7e]+(?: [\x21\x23-\x5b\x5d-\x7e]+)*$/.test(scope))
|
|
2286
|
+
return invalid5("scope");
|
|
2287
|
+
params.set("scope", scope);
|
|
2288
|
+
}
|
|
2289
|
+
for (const field of ["state", "nonce"])
|
|
2290
|
+
if (input[field] !== undefined)
|
|
2291
|
+
params.set(field, text4(input[field], field));
|
|
2292
|
+
if (input.resource !== undefined)
|
|
2293
|
+
params.set("resource", httpUrl(input.resource, "resource"));
|
|
2294
|
+
if (input.codeChallenge !== undefined || input.codeChallengeMethod !== undefined) {
|
|
2295
|
+
const challenge = text4(input.codeChallenge, "codeChallenge", 128);
|
|
2296
|
+
const method = input.codeChallengeMethod;
|
|
2297
|
+
if (method !== "S256" && method !== "plain")
|
|
2298
|
+
return invalid5("codeChallengeMethod");
|
|
2299
|
+
if (method === "S256" ? base64url(challenge, "codeChallenge").bytes.length !== 32 : !/^[A-Za-z0-9._~-]{43,128}$/.test(challenge))
|
|
2300
|
+
return invalid5("codeChallenge");
|
|
2301
|
+
params.set("code_challenge", challenge);
|
|
2302
|
+
params.set("code_challenge_method", method);
|
|
2303
|
+
}
|
|
2304
|
+
const status = await this.status(operation);
|
|
2305
|
+
if (!status.enabled)
|
|
2306
|
+
return invalid5("OAuth Server disabled");
|
|
2307
|
+
return `${status.authorization_endpoint}?${params}`;
|
|
2308
|
+
});
|
|
109
2309
|
}
|
|
110
2310
|
}
|
|
111
|
-
|
|
112
2311
|
// src/auth-fetch.ts
|
|
113
2312
|
function requestMethod(input, init) {
|
|
114
2313
|
return (init?.method || (input instanceof Request ? input.method : "GET")).toUpperCase();
|
|
@@ -196,11 +2395,26 @@ function createSupaCloudOAuthFetch(options = {}) {
|
|
|
196
2395
|
return fetchImpl(replacementRequest(request, endpoint, body));
|
|
197
2396
|
};
|
|
198
2397
|
}
|
|
2398
|
+
// src/workflow-fetch.ts
|
|
2399
|
+
var workflowPath = /\/rpc\/supacloud_workflow_(?:start|claim|advance|complete|retry|fail|cancel|get|events)$/;
|
|
2400
|
+
function createSupaCloudWorkflowFetch(options = {}) {
|
|
2401
|
+
return createBoundedRpcFetch(workflowPath, () => new Error("Workflow HTTP response could not be validated"), options.fetch);
|
|
2402
|
+
}
|
|
2403
|
+
// src/command-fetch.ts
|
|
2404
|
+
var commandPath = /\/rpc\/supacloud_command_(?:submit|get)$/;
|
|
2405
|
+
function createSupaCloudCommandFetch(options = {}) {
|
|
2406
|
+
return createBoundedRpcFetch(commandPath, () => new Error("Command HTTP response could not be validated"), options.fetch);
|
|
2407
|
+
}
|
|
2408
|
+
// src/artifact-fetch.ts
|
|
2409
|
+
var artifactPath2 = /\/rpc\/supacloud_artifact_(?:register|get|link)$/;
|
|
2410
|
+
function createSupaCloudArtifactFetch(options = {}) {
|
|
2411
|
+
return createBoundedRpcFetch(artifactPath2, () => new Error("Artifact HTTP response could not be validated"), options.fetch);
|
|
2412
|
+
}
|
|
199
2413
|
|
|
200
2414
|
// src/index.ts
|
|
201
|
-
var SUPACLOUD_JS_VERSION = "0.27.1";
|
|
202
|
-
|
|
203
2415
|
class SupaCloudTaskSubmitError extends Error {
|
|
2416
|
+
code = "TASK_SUBMIT_UNCONFIRMED";
|
|
2417
|
+
mutationMayHaveApplied = true;
|
|
204
2418
|
responseBody;
|
|
205
2419
|
constructor(message, responseBody) {
|
|
206
2420
|
super(message);
|
|
@@ -208,34 +2422,45 @@ class SupaCloudTaskSubmitError extends Error {
|
|
|
208
2422
|
this.responseBody = responseBody;
|
|
209
2423
|
}
|
|
210
2424
|
}
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
super(message);
|
|
218
|
-
this.name = "SupaCloudApiError";
|
|
219
|
-
this.status = status;
|
|
220
|
-
this.responseBody = responseBody;
|
|
221
|
-
this.code = extractErrorCode(responseBody);
|
|
2425
|
+
var boundedTaskHttpFailures = new WeakSet;
|
|
2426
|
+
function matchesForeignTaskHttpError(error, response) {
|
|
2427
|
+
try {
|
|
2428
|
+
return error instanceof Error && Object.getOwnPropertyDescriptor(error, "name")?.value === "FunctionsHttpError" && Object.getOwnPropertyDescriptor(error, "context")?.value === response;
|
|
2429
|
+
} catch {
|
|
2430
|
+
return false;
|
|
222
2431
|
}
|
|
223
2432
|
}
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
2433
|
+
function createSupaCloudTaskFetch(options) {
|
|
2434
|
+
const captured = queueJsonSnapshot(options.functionUrls);
|
|
2435
|
+
if (!Array.isArray(captured) || captured.length === 0)
|
|
2436
|
+
throw new Error("Invalid task function URLs");
|
|
2437
|
+
const urls = new Set(captured.map((value) => {
|
|
2438
|
+
if (typeof value !== "string" || value.trim() !== value || /[\u0000-\u001f\u007f]/.test(value)) {
|
|
2439
|
+
throw new Error("Invalid task function URLs");
|
|
2440
|
+
}
|
|
2441
|
+
let url;
|
|
2442
|
+
try {
|
|
2443
|
+
url = new URL(value);
|
|
2444
|
+
} catch {
|
|
2445
|
+
throw new Error("Invalid task function URLs");
|
|
2446
|
+
}
|
|
2447
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
|
|
2448
|
+
throw new Error("Invalid task function URLs");
|
|
2449
|
+
}
|
|
2450
|
+
return url.origin + url.pathname;
|
|
2451
|
+
}));
|
|
2452
|
+
const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
2453
|
+
const bounded = createBoundedRpcFetch(/./, () => new SupaCloudTaskSubmitError("Background task submission could not be confirmed", undefined), fetchImpl);
|
|
2454
|
+
return async (input, init) => {
|
|
2455
|
+
const url = new URL(input instanceof Request ? input.url : input.toString());
|
|
2456
|
+
if (!urls.has(url.origin + url.pathname))
|
|
2457
|
+
return fetchImpl(input, init);
|
|
2458
|
+
const response = await bounded(input, init);
|
|
2459
|
+
if (response.status >= 400 && response.status < 500 && response.headers.get("x-relay-error") !== "true") {
|
|
2460
|
+
boundedTaskHttpFailures.add(response);
|
|
2461
|
+
}
|
|
2462
|
+
return response;
|
|
2463
|
+
};
|
|
239
2464
|
}
|
|
240
2465
|
var TERMINAL_STATUSES = new Set([
|
|
241
2466
|
"succeeded",
|
|
@@ -256,7 +2481,7 @@ function waitForPollingInterval(intervalMs, signal) {
|
|
|
256
2481
|
settle();
|
|
257
2482
|
};
|
|
258
2483
|
const onAbort = () => finish(() => {
|
|
259
|
-
reject(signal
|
|
2484
|
+
reject(signal ? signal.reason : new DOMException("Aborted", "AbortError"));
|
|
260
2485
|
});
|
|
261
2486
|
const timer = setTimeout(() => finish(resolve), intervalMs);
|
|
262
2487
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -273,19 +2498,51 @@ function toArray(value) {
|
|
|
273
2498
|
return Array.isArray(value) ? value : [value];
|
|
274
2499
|
}
|
|
275
2500
|
function createQueryString(filters = {}) {
|
|
2501
|
+
let captured;
|
|
2502
|
+
try {
|
|
2503
|
+
captured = responseRecord(queueJsonSnapshot(filters), "task filters");
|
|
2504
|
+
} catch {
|
|
2505
|
+
throw new Error("Invalid task list filters");
|
|
2506
|
+
}
|
|
2507
|
+
if (Object.keys(captured).some((key) => !["status", "taskType", "functionSlug", "dlq", "limit"].includes(key))) {
|
|
2508
|
+
throw new Error("Invalid task list filters");
|
|
2509
|
+
}
|
|
2510
|
+
const text = (value, commaAllowed = false) => {
|
|
2511
|
+
if (typeof value !== "string" || !value || value.trim() !== value || /[\u0000-\u001f\u007f]/.test(value) || !commaAllowed && value.includes(",")) {
|
|
2512
|
+
throw new Error("Invalid task list filters");
|
|
2513
|
+
}
|
|
2514
|
+
try {
|
|
2515
|
+
encodeURIComponent(value);
|
|
2516
|
+
} catch {
|
|
2517
|
+
throw new Error("Invalid task list filters");
|
|
2518
|
+
}
|
|
2519
|
+
return value;
|
|
2520
|
+
};
|
|
2521
|
+
const values = (value) => {
|
|
2522
|
+
const items = Array.isArray(value) ? value : [value];
|
|
2523
|
+
if (items.length === 0)
|
|
2524
|
+
throw new Error("Invalid task list filters");
|
|
2525
|
+
return items.map((item) => text(item));
|
|
2526
|
+
};
|
|
276
2527
|
const params = new URLSearchParams;
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
if (
|
|
280
|
-
params.set("
|
|
281
|
-
if (
|
|
282
|
-
params.set("
|
|
283
|
-
if (
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
2528
|
+
if (Object.hasOwn(captured, "status"))
|
|
2529
|
+
params.set("status", values(captured.status).join(","));
|
|
2530
|
+
if (Object.hasOwn(captured, "taskType"))
|
|
2531
|
+
params.set("task_type", values(captured.taskType).join(","));
|
|
2532
|
+
if (Object.hasOwn(captured, "functionSlug"))
|
|
2533
|
+
params.set("function_slug", text(captured.functionSlug, true));
|
|
2534
|
+
if (Object.hasOwn(captured, "dlq")) {
|
|
2535
|
+
if (typeof captured.dlq !== "boolean")
|
|
2536
|
+
throw new Error("Invalid task list filters");
|
|
2537
|
+
if (captured.dlq)
|
|
2538
|
+
params.set("dlq", "true");
|
|
2539
|
+
}
|
|
2540
|
+
if (Object.hasOwn(captured, "limit")) {
|
|
2541
|
+
if (typeof captured.limit !== "number" || !Number.isSafeInteger(captured.limit) || captured.limit < 1) {
|
|
2542
|
+
throw new Error("Invalid task list filters");
|
|
2543
|
+
}
|
|
2544
|
+
params.set("limit", String(captured.limit));
|
|
2545
|
+
}
|
|
289
2546
|
const query = params.toString();
|
|
290
2547
|
return query.length > 0 ? `?${query}` : "";
|
|
291
2548
|
}
|
|
@@ -304,25 +2561,7 @@ function createQueueQueryString(filters = {}) {
|
|
|
304
2561
|
return query.length > 0 ? `?${query}` : "";
|
|
305
2562
|
}
|
|
306
2563
|
function normalizeSecondsFromOptions(options = {}) {
|
|
307
|
-
|
|
308
|
-
return Math.max(0, Math.floor(options.sleepSeconds));
|
|
309
|
-
if (typeof options.sleep_seconds === "number")
|
|
310
|
-
return Math.max(0, Math.floor(options.sleep_seconds));
|
|
311
|
-
if (typeof options.visibilityTimeoutSec === "number")
|
|
312
|
-
return Math.max(0, Math.floor(options.visibilityTimeoutSec));
|
|
313
|
-
if (typeof options.delayMs === "number")
|
|
314
|
-
return Math.max(0, Math.floor(options.delayMs / 1000));
|
|
315
|
-
return 0;
|
|
316
|
-
}
|
|
317
|
-
function normalizeMessageId(value) {
|
|
318
|
-
const parsed = Number(value);
|
|
319
|
-
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : 0;
|
|
320
|
-
}
|
|
321
|
-
function firstRpcValue(value) {
|
|
322
|
-
return isUnknownArray(value) ? value[0] : value;
|
|
323
|
-
}
|
|
324
|
-
function isUnknownArray(value) {
|
|
325
|
-
return Array.isArray(value);
|
|
2564
|
+
return queueSeconds(options);
|
|
326
2565
|
}
|
|
327
2566
|
function valueRecord2(value) {
|
|
328
2567
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
@@ -350,31 +2589,175 @@ function responseNumber(record, key, label) {
|
|
|
350
2589
|
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
351
2590
|
throw new Error(`Invalid ${label} response: ${key} is required`);
|
|
352
2591
|
}
|
|
353
|
-
return value;
|
|
2592
|
+
return value;
|
|
2593
|
+
}
|
|
2594
|
+
function decodeVoid(value) {
|
|
2595
|
+
if (value !== undefined)
|
|
2596
|
+
throw new Error("Expected an empty response");
|
|
2597
|
+
}
|
|
2598
|
+
function taskText(value) {
|
|
2599
|
+
if (typeof value !== "string")
|
|
2600
|
+
throw new Error("Invalid task response: expected text");
|
|
2601
|
+
return value;
|
|
2602
|
+
}
|
|
2603
|
+
function taskNumber(value) {
|
|
2604
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
2605
|
+
throw new Error("Invalid task response: expected number");
|
|
2606
|
+
return value;
|
|
2607
|
+
}
|
|
2608
|
+
function taskNullable(value, decode) {
|
|
2609
|
+
return value === null ? null : decode(value);
|
|
2610
|
+
}
|
|
2611
|
+
function taskArray(value, decode) {
|
|
2612
|
+
if (!Array.isArray(value))
|
|
2613
|
+
throw new Error("Invalid task response: expected array");
|
|
2614
|
+
return value.map(decode);
|
|
2615
|
+
}
|
|
2616
|
+
function decodeTaskLog(value) {
|
|
2617
|
+
const data = responseRecord(value, "task log");
|
|
2618
|
+
if (data.stream !== "stdout" && data.stream !== "stderr")
|
|
2619
|
+
throw new Error("Invalid task log response: stream");
|
|
2620
|
+
return {
|
|
2621
|
+
timestamp: taskText(data.timestamp),
|
|
2622
|
+
stream: data.stream,
|
|
2623
|
+
level: taskText(data.level),
|
|
2624
|
+
message: taskText(data.message)
|
|
2625
|
+
};
|
|
2626
|
+
}
|
|
2627
|
+
function decodeTaskAttempt(value) {
|
|
2628
|
+
const data = responseRecord(value, "task attempt");
|
|
2629
|
+
return {
|
|
2630
|
+
attempt_no: taskNumber(data.attempt_no),
|
|
2631
|
+
status: taskText(data.status),
|
|
2632
|
+
started_at: taskNullable(data.started_at, taskText),
|
|
2633
|
+
completed_at: taskNullable(data.completed_at, taskText),
|
|
2634
|
+
duration_ms: taskNullable(data.duration_ms, taskNumber),
|
|
2635
|
+
response_status: taskNullable(data.response_status, taskNumber),
|
|
2636
|
+
error: taskNullable(data.error, taskText),
|
|
2637
|
+
logs: taskArray(data.logs, decodeTaskLog)
|
|
2638
|
+
};
|
|
2639
|
+
}
|
|
2640
|
+
function decodeTaskDetail(value) {
|
|
2641
|
+
const record = responseRecord(value, "task");
|
|
2642
|
+
let executor;
|
|
2643
|
+
let capabilities;
|
|
2644
|
+
if (Object.hasOwn(record, "executor")) {
|
|
2645
|
+
const source = responseRecord(record.executor, "task executor");
|
|
2646
|
+
executor = {
|
|
2647
|
+
kind: taskText(source.kind),
|
|
2648
|
+
version: taskText(source.version),
|
|
2649
|
+
definition: taskText(source.definition),
|
|
2650
|
+
run_id: taskText(source.run_id),
|
|
2651
|
+
native_status: taskText(source.native_status)
|
|
2652
|
+
};
|
|
2653
|
+
}
|
|
2654
|
+
if (Object.hasOwn(record, "capabilities")) {
|
|
2655
|
+
const source = responseRecord(record.capabilities, "task capabilities");
|
|
2656
|
+
if (typeof source.cancel !== "boolean" || typeof source.retry !== "boolean") {
|
|
2657
|
+
throw new Error("Invalid task capabilities");
|
|
2658
|
+
}
|
|
2659
|
+
capabilities = { cancel: source.cancel, retry: source.retry };
|
|
2660
|
+
}
|
|
2661
|
+
for (const key of [
|
|
2662
|
+
"function_slug",
|
|
2663
|
+
"function_version",
|
|
2664
|
+
"error",
|
|
2665
|
+
"error_message",
|
|
2666
|
+
"correlation_id",
|
|
2667
|
+
"business_task_id",
|
|
2668
|
+
"updated_at",
|
|
2669
|
+
"created_at",
|
|
2670
|
+
"blocked_reason"
|
|
2671
|
+
]) {
|
|
2672
|
+
if (Object.hasOwn(record, key))
|
|
2673
|
+
taskNullable(record[key], taskText);
|
|
2674
|
+
}
|
|
2675
|
+
for (const key of ["attempt", "max_attempts", "progress"]) {
|
|
2676
|
+
if (Object.hasOwn(record, key))
|
|
2677
|
+
taskNullable(record[key], taskNumber);
|
|
2678
|
+
}
|
|
2679
|
+
if (Object.hasOwn(record, "task_type"))
|
|
2680
|
+
taskText(record.task_type);
|
|
2681
|
+
for (const key of ["total_steps", "finished_steps"]) {
|
|
2682
|
+
if (Object.hasOwn(record, key)) {
|
|
2683
|
+
const count = taskNumber(record[key]);
|
|
2684
|
+
if (!Number.isSafeInteger(count) || count < 0)
|
|
2685
|
+
throw new Error("Invalid task step count");
|
|
2686
|
+
}
|
|
2687
|
+
}
|
|
2688
|
+
if (Object.hasOwn(record, "payload"))
|
|
2689
|
+
responseRecord(record.payload, "task payload");
|
|
2690
|
+
if (Object.hasOwn(record, "metadata") && record.metadata !== null)
|
|
2691
|
+
responseRecord(record.metadata, "task metadata");
|
|
2692
|
+
return {
|
|
2693
|
+
...record,
|
|
2694
|
+
id: responseString(record, "id", "task"),
|
|
2695
|
+
project_ref: responseString(record, "project_ref", "task"),
|
|
2696
|
+
status: responseString(record, "status", "task"),
|
|
2697
|
+
...executor === undefined ? {} : { executor },
|
|
2698
|
+
...capabilities === undefined ? {} : { capabilities },
|
|
2699
|
+
...Object.hasOwn(record, "attempts") ? { attempts: taskArray(record.attempts, decodeTaskAttempt) } : {},
|
|
2700
|
+
...Object.hasOwn(record, "latest_logs") ? { latest_logs: taskArray(record.latest_logs, decodeTaskLog) } : {}
|
|
2701
|
+
};
|
|
2702
|
+
}
|
|
2703
|
+
function decodeTaskDetails(value) {
|
|
2704
|
+
if (!Array.isArray(value))
|
|
2705
|
+
throw new Error("Invalid task list response");
|
|
2706
|
+
return value.map(decodeTaskDetail);
|
|
2707
|
+
}
|
|
2708
|
+
|
|
2709
|
+
class SupaCloudTaskResponseError extends SupaCloudApiError {
|
|
2710
|
+
mutationMayHaveApplied;
|
|
2711
|
+
constructor(operation) {
|
|
2712
|
+
const mutation = operation !== "get";
|
|
2713
|
+
super("Invalid task response: could not validate the requested task", 0, {
|
|
2714
|
+
code: operation === "get" ? "TASK_READ_INVALID" : `TASK_${operation.toUpperCase()}_UNCONFIRMED`,
|
|
2715
|
+
mutation_may_have_applied: mutation
|
|
2716
|
+
});
|
|
2717
|
+
this.name = "SupaCloudTaskResponseError";
|
|
2718
|
+
this.mutationMayHaveApplied = mutation;
|
|
2719
|
+
}
|
|
2720
|
+
}
|
|
2721
|
+
|
|
2722
|
+
class SupaCloudTaskDecoderError extends SupaCloudApiError {
|
|
2723
|
+
operation;
|
|
2724
|
+
code = "TASK_RESULT_INVALID";
|
|
2725
|
+
mutationMayHaveApplied;
|
|
2726
|
+
constructor(operation) {
|
|
2727
|
+
const mutation = operation === "cancel" || operation === "retry";
|
|
2728
|
+
super("Task result could not be decoded", 0, {
|
|
2729
|
+
code: "TASK_RESULT_INVALID",
|
|
2730
|
+
mutation_may_have_applied: mutation
|
|
2731
|
+
});
|
|
2732
|
+
this.operation = operation;
|
|
2733
|
+
this.name = "SupaCloudTaskDecoderError";
|
|
2734
|
+
this.mutationMayHaveApplied = mutation;
|
|
2735
|
+
}
|
|
354
2736
|
}
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
2737
|
+
class SupaCloudTaskAuthenticationError extends SupaCloudApiError {
|
|
2738
|
+
mutationMayHaveApplied = false;
|
|
2739
|
+
constructor(code = "TASK_AUTH_INVALID") {
|
|
2740
|
+
super("Task authentication could not be validated", 0, {
|
|
2741
|
+
code,
|
|
2742
|
+
mutation_may_have_applied: false
|
|
2743
|
+
});
|
|
2744
|
+
this.name = "SupaCloudTaskAuthenticationError";
|
|
359
2745
|
}
|
|
360
|
-
return value;
|
|
361
|
-
}
|
|
362
|
-
function decodeVoid(value) {
|
|
363
|
-
if (value !== undefined)
|
|
364
|
-
throw new Error("Expected an empty response");
|
|
365
|
-
}
|
|
366
|
-
function decodeTaskDetail(value) {
|
|
367
|
-
const record = responseRecord(value, "task");
|
|
368
|
-
return {
|
|
369
|
-
...record,
|
|
370
|
-
id: responseString(record, "id", "task"),
|
|
371
|
-
status: responseString(record, "status", "task")
|
|
372
|
-
};
|
|
373
2746
|
}
|
|
374
|
-
function
|
|
375
|
-
if (
|
|
376
|
-
throw new Error("Invalid task
|
|
377
|
-
|
|
2747
|
+
function captureTaskId(value) {
|
|
2748
|
+
if (typeof value !== "string" || value.length === 0 || value.trim() !== value || value === "." || value === ".." || /[\u0000-\u001f\u007f]/.test(value)) {
|
|
2749
|
+
throw new Error("Invalid task ID");
|
|
2750
|
+
}
|
|
2751
|
+
try {
|
|
2752
|
+
encodeURIComponent(value);
|
|
2753
|
+
} catch {
|
|
2754
|
+
throw new Error("Invalid task ID");
|
|
2755
|
+
}
|
|
2756
|
+
const candidate = value.startsWith("{") && value.endsWith("}") ? value.slice(1, -1) : value;
|
|
2757
|
+
if (!/^[0-9a-f]{4}(?:-?[0-9a-f]{4}){7}$/i.test(candidate))
|
|
2758
|
+
return value;
|
|
2759
|
+
const hex = candidate.replaceAll("-", "").toLowerCase();
|
|
2760
|
+
return [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join("-");
|
|
378
2761
|
}
|
|
379
2762
|
function captureTaskDecoder(value) {
|
|
380
2763
|
if (typeof value !== "function")
|
|
@@ -385,27 +2768,32 @@ function decodeTaskResult(task, decoder, operation) {
|
|
|
385
2768
|
if (!Object.hasOwn(task, "result"))
|
|
386
2769
|
return task;
|
|
387
2770
|
try {
|
|
388
|
-
|
|
2771
|
+
const input = task.result === undefined ? undefined : queueJsonSnapshot(task.result);
|
|
2772
|
+
return { ...task, result: decoder(input) };
|
|
389
2773
|
} catch {
|
|
390
2774
|
throw new SupaCloudTaskDecoderError(operation);
|
|
391
2775
|
}
|
|
392
2776
|
}
|
|
393
|
-
function
|
|
394
|
-
|
|
395
|
-
const messageValue = record.message ?? record.payload;
|
|
396
|
-
const message = valueRecord2(messageValue);
|
|
397
|
-
return {
|
|
398
|
-
...record,
|
|
399
|
-
id: responseString(record, "id", "queue message"),
|
|
400
|
-
msg_id: responseNumber(record, "msg_id", "queue message"),
|
|
401
|
-
message,
|
|
402
|
-
payload: message
|
|
403
|
-
};
|
|
2777
|
+
function decodeTaskDetailsWithResult(value, decoder) {
|
|
2778
|
+
return decodeTaskDetails(value).map((task) => decodeTaskResult(task, decoder, "list"));
|
|
404
2779
|
}
|
|
405
|
-
function
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
2780
|
+
function decodeBoundTask(value, taskId, operation) {
|
|
2781
|
+
try {
|
|
2782
|
+
const task = decodeTaskDetail(value);
|
|
2783
|
+
if (task.id !== taskId)
|
|
2784
|
+
throw new Error("Mismatched task ID");
|
|
2785
|
+
return task;
|
|
2786
|
+
} catch {
|
|
2787
|
+
throw new SupaCloudTaskResponseError(operation);
|
|
2788
|
+
}
|
|
2789
|
+
}
|
|
2790
|
+
function decodeQueueMessages(value, queueName) {
|
|
2791
|
+
if (!Array.isArray(value) || value.length > 1e4)
|
|
2792
|
+
throw new SupaCloudQueueError;
|
|
2793
|
+
const messages = value.map((row) => queueMessage(row, { queueName }));
|
|
2794
|
+
if (new Set(messages.map((row) => row.id)).size !== messages.length)
|
|
2795
|
+
throw new SupaCloudQueueError;
|
|
2796
|
+
return messages;
|
|
409
2797
|
}
|
|
410
2798
|
function decodeQueueStats(value) {
|
|
411
2799
|
const record = responseRecord(value, "queue stats");
|
|
@@ -440,116 +2828,6 @@ function decodeQueueInfos(value) {
|
|
|
440
2828
|
throw new Error("Invalid queue info list response");
|
|
441
2829
|
return value.map(decodeQueueInfo);
|
|
442
2830
|
}
|
|
443
|
-
function decodeOAuthServerStatus(value) {
|
|
444
|
-
const record = responseRecord(value, "OAuth Server");
|
|
445
|
-
return {
|
|
446
|
-
...record,
|
|
447
|
-
project_ref: responseString(record, "project_ref", "OAuth Server"),
|
|
448
|
-
account_isolated: responseBoolean(record, "account_isolated", "OAuth Server"),
|
|
449
|
-
enabled: responseBoolean(record, "enabled", "OAuth Server"),
|
|
450
|
-
allow_dynamic_registration: responseBoolean(record, "allow_dynamic_registration", "OAuth Server"),
|
|
451
|
-
issuer: responseString(record, "issuer", "OAuth Server"),
|
|
452
|
-
discovery_url: responseString(record, "discovery_url", "OAuth Server"),
|
|
453
|
-
jwks_url: responseString(record, "jwks_url", "OAuth Server"),
|
|
454
|
-
authorization_endpoint: responseString(record, "authorization_endpoint", "OAuth Server"),
|
|
455
|
-
token_endpoint: responseString(record, "token_endpoint", "OAuth Server")
|
|
456
|
-
};
|
|
457
|
-
}
|
|
458
|
-
function decodeOAuthClient(value) {
|
|
459
|
-
const record = responseRecord(value, "OAuth client");
|
|
460
|
-
return {
|
|
461
|
-
...record,
|
|
462
|
-
client_id: responseString(record, "client_id", "OAuth client")
|
|
463
|
-
};
|
|
464
|
-
}
|
|
465
|
-
function decodeOAuthClientList(value) {
|
|
466
|
-
const record = responseRecord(value, "OAuth client list");
|
|
467
|
-
const clients = record.clients;
|
|
468
|
-
if (clients === undefined)
|
|
469
|
-
return record;
|
|
470
|
-
if (!Array.isArray(clients))
|
|
471
|
-
throw new Error("Invalid OAuth client list response");
|
|
472
|
-
return { ...record, clients: clients.map(decodeOAuthClient) };
|
|
473
|
-
}
|
|
474
|
-
function decodeSupAuthStepResult(value) {
|
|
475
|
-
const record = responseRecord(value, "SupAuth step");
|
|
476
|
-
return {
|
|
477
|
-
...record,
|
|
478
|
-
step: responseString(record, "step", "SupAuth step"),
|
|
479
|
-
status: responseString(record, "status", "SupAuth step")
|
|
480
|
-
};
|
|
481
|
-
}
|
|
482
|
-
function decodeSupAuthProvisionResult(value) {
|
|
483
|
-
const record = responseRecord(value, "SupAuth provision");
|
|
484
|
-
const steps = record.steps;
|
|
485
|
-
if (steps !== undefined && !Array.isArray(steps)) {
|
|
486
|
-
throw new Error("Invalid SupAuth provision response");
|
|
487
|
-
}
|
|
488
|
-
return {
|
|
489
|
-
...record,
|
|
490
|
-
projectRef: responseString(record, "projectRef", "SupAuth provision"),
|
|
491
|
-
status: responseString(record, "status", "SupAuth provision"),
|
|
492
|
-
...steps === undefined ? {} : { steps: steps.map(decodeSupAuthStepResult) }
|
|
493
|
-
};
|
|
494
|
-
}
|
|
495
|
-
function decodeSupAuthReconcileResult(value) {
|
|
496
|
-
const record = responseRecord(value, "SupAuth reconcile");
|
|
497
|
-
const steps = record.steps;
|
|
498
|
-
if (steps !== undefined && !Array.isArray(steps)) {
|
|
499
|
-
throw new Error("Invalid SupAuth reconcile response");
|
|
500
|
-
}
|
|
501
|
-
return {
|
|
502
|
-
...record,
|
|
503
|
-
projectRef: responseString(record, "projectRef", "SupAuth reconcile"),
|
|
504
|
-
changed: responseBoolean(record, "changed", "SupAuth reconcile"),
|
|
505
|
-
...steps === undefined ? {} : { steps: steps.map(decodeSupAuthStepResult) }
|
|
506
|
-
};
|
|
507
|
-
}
|
|
508
|
-
function decodeSupAuthRollbackResult(value) {
|
|
509
|
-
const record = responseRecord(value, "SupAuth rollback");
|
|
510
|
-
const steps = record.steps;
|
|
511
|
-
if (steps !== undefined && !Array.isArray(steps)) {
|
|
512
|
-
throw new Error("Invalid SupAuth rollback response");
|
|
513
|
-
}
|
|
514
|
-
return {
|
|
515
|
-
...record,
|
|
516
|
-
projectRef: responseString(record, "projectRef", "SupAuth rollback"),
|
|
517
|
-
status: responseString(record, "status", "SupAuth rollback"),
|
|
518
|
-
...steps === undefined ? {} : { steps: steps.map(decodeSupAuthStepResult) }
|
|
519
|
-
};
|
|
520
|
-
}
|
|
521
|
-
function decodeSupAuthClientConfig(value) {
|
|
522
|
-
const record = responseRecord(value, "SupAuth client config");
|
|
523
|
-
return {
|
|
524
|
-
...record,
|
|
525
|
-
projectRef: responseString(record, "projectRef", "SupAuth client config"),
|
|
526
|
-
supabaseUrl: responseString(record, "supabaseUrl", "SupAuth client config"),
|
|
527
|
-
authUrl: responseString(record, "authUrl", "SupAuth client config"),
|
|
528
|
-
restUrl: responseString(record, "restUrl", "SupAuth client config"),
|
|
529
|
-
storageUrl: responseString(record, "storageUrl", "SupAuth client config"),
|
|
530
|
-
realtimeUrl: responseString(record, "realtimeUrl", "SupAuth client config"),
|
|
531
|
-
functionsUrl: responseString(record, "functionsUrl", "SupAuth client config")
|
|
532
|
-
};
|
|
533
|
-
}
|
|
534
|
-
function decodeSupAuthVerification(value) {
|
|
535
|
-
const record = responseRecord(value, "SupAuth verification");
|
|
536
|
-
const checks = record.checks;
|
|
537
|
-
if (!isUnknownArray(checks))
|
|
538
|
-
throw new Error("Invalid SupAuth verification response");
|
|
539
|
-
return {
|
|
540
|
-
...record,
|
|
541
|
-
projectRef: responseString(record, "projectRef", "SupAuth verification"),
|
|
542
|
-
healthy: responseBoolean(record, "healthy", "SupAuth verification"),
|
|
543
|
-
checks: checks.map((check) => {
|
|
544
|
-
const record = responseRecord(check, "SupAuth check");
|
|
545
|
-
return {
|
|
546
|
-
...record,
|
|
547
|
-
name: responseString(record, "name", "SupAuth check"),
|
|
548
|
-
status: responseString(record, "status", "SupAuth check")
|
|
549
|
-
};
|
|
550
|
-
})
|
|
551
|
-
};
|
|
552
|
-
}
|
|
553
2831
|
function decodePurgeResult(value) {
|
|
554
2832
|
const record = responseRecord(value, "queue purge");
|
|
555
2833
|
return {
|
|
@@ -557,82 +2835,6 @@ function decodePurgeResult(value) {
|
|
|
557
2835
|
purged: responseNumber(record, "purged", "queue purge")
|
|
558
2836
|
};
|
|
559
2837
|
}
|
|
560
|
-
function decodeProjectCapabilities(value) {
|
|
561
|
-
const record = responseRecord(value, "project capabilities");
|
|
562
|
-
const rawCapabilities = valueRecord2(record.capabilities);
|
|
563
|
-
const capabilities = {};
|
|
564
|
-
for (const [key, item] of Object.entries(rawCapabilities)) {
|
|
565
|
-
const capRecord = valueRecord2(item);
|
|
566
|
-
capabilities[key] = {
|
|
567
|
-
available: typeof capRecord.available === "boolean" ? capRecord.available : false,
|
|
568
|
-
source: typeof capRecord.source === "string" ? capRecord.source : "unknown",
|
|
569
|
-
version: typeof capRecord.version === "string" ? capRecord.version : null,
|
|
570
|
-
reason_code: typeof capRecord.reason_code === "string" ? capRecord.reason_code : null,
|
|
571
|
-
...typeof capRecord.authority_project_ref === "string" ? { authority_project_ref: capRecord.authority_project_ref } : {},
|
|
572
|
-
...typeof capRecord.managed_by_owner === "boolean" ? { managed_by_owner: capRecord.managed_by_owner } : {}
|
|
573
|
-
};
|
|
574
|
-
}
|
|
575
|
-
return {
|
|
576
|
-
...record,
|
|
577
|
-
project_ref: responseString(record, "project_ref", "project capabilities"),
|
|
578
|
-
auth_runtime: typeof record.auth_runtime === "string" ? record.auth_runtime : "unknown",
|
|
579
|
-
schema_version: typeof record.schema_version === "number" ? record.schema_version : 1,
|
|
580
|
-
platform_version: typeof record.platform_version === "string" ? record.platform_version : undefined,
|
|
581
|
-
environment: typeof record.environment === "string" ? record.environment : undefined,
|
|
582
|
-
storage_backend: typeof record.storage_backend === "string" ? record.storage_backend : undefined,
|
|
583
|
-
capabilities
|
|
584
|
-
};
|
|
585
|
-
}
|
|
586
|
-
function decodeStoragePlatformConstraints(value) {
|
|
587
|
-
const record = responseRecord(value, "storage constraints");
|
|
588
|
-
return {
|
|
589
|
-
max_upload_size_bytes: responseNumber(record, "max_upload_size_bytes", "storage constraints"),
|
|
590
|
-
max_upload_size_mb: responseNumber(record, "max_upload_size_mb", "storage constraints"),
|
|
591
|
-
tus_max_size_bytes: responseNumber(record, "tus_max_size_bytes", "storage constraints"),
|
|
592
|
-
tus_chunk_max_size_bytes: responseNumber(record, "tus_chunk_max_size_bytes", "storage constraints"),
|
|
593
|
-
streaming_upload_supported: responseBoolean(record, "streaming_upload_supported", "storage constraints")
|
|
594
|
-
};
|
|
595
|
-
}
|
|
596
|
-
function normalizeRpcMessage(queueName, value, status) {
|
|
597
|
-
const row = firstRpcValue(value);
|
|
598
|
-
if (!row || typeof row !== "object")
|
|
599
|
-
return null;
|
|
600
|
-
const record = valueRecord2(row);
|
|
601
|
-
const message = record.message && typeof record.message === "object" && !Array.isArray(record.message) ? valueRecord2(record.message) : {};
|
|
602
|
-
const msgId = normalizeMessageId(record.msg_id ?? record.id);
|
|
603
|
-
return {
|
|
604
|
-
...record,
|
|
605
|
-
id: String(msgId),
|
|
606
|
-
msg_id: msgId,
|
|
607
|
-
message,
|
|
608
|
-
payload: message,
|
|
609
|
-
status,
|
|
610
|
-
queue_name: queueName,
|
|
611
|
-
task_type: `queue:${queueName}`
|
|
612
|
-
};
|
|
613
|
-
}
|
|
614
|
-
function normalizeRpcMessages(queueName, value, status) {
|
|
615
|
-
const rows = isUnknownArray(value) ? value : value == null ? [] : [value];
|
|
616
|
-
return rows.map((row) => normalizeRpcMessage(queueName, row, status)).filter((row) => Boolean(row));
|
|
617
|
-
}
|
|
618
|
-
function normalizeRpcMessageId(value) {
|
|
619
|
-
const row = firstRpcValue(value);
|
|
620
|
-
if (row && typeof row === "object") {
|
|
621
|
-
const record = valueRecord2(row);
|
|
622
|
-
return normalizeMessageId(record.msg_id ?? record.send ?? record.send_batch ?? record.id);
|
|
623
|
-
}
|
|
624
|
-
return normalizeMessageId(row);
|
|
625
|
-
}
|
|
626
|
-
function normalizeRpcMessageIds(value) {
|
|
627
|
-
const rows = isUnknownArray(value) ? value : value == null ? [] : [value];
|
|
628
|
-
return rows.map((row) => normalizeRpcMessageId(row)).filter((id) => id > 0);
|
|
629
|
-
}
|
|
630
|
-
function extractErrorCode(body) {
|
|
631
|
-
if (!body || typeof body !== "object")
|
|
632
|
-
return null;
|
|
633
|
-
const code = valueRecord2(body).code;
|
|
634
|
-
return typeof code === "string" ? code : null;
|
|
635
|
-
}
|
|
636
2838
|
async function readResponseBody(response) {
|
|
637
2839
|
const text = await response.text();
|
|
638
2840
|
if (!text)
|
|
@@ -650,16 +2852,111 @@ async function defaultAccessTokenResolver(supabase) {
|
|
|
650
2852
|
throw error;
|
|
651
2853
|
return data.session?.access_token ?? null;
|
|
652
2854
|
}
|
|
653
|
-
function
|
|
654
|
-
|
|
655
|
-
|
|
2855
|
+
function validateTaskProject(record, projectRef) {
|
|
2856
|
+
if (!Object.hasOwn(record, "project_ref") || record.project_ref !== projectRef) {
|
|
2857
|
+
throw new Error("Invalid task response project");
|
|
2858
|
+
}
|
|
2859
|
+
}
|
|
2860
|
+
var MAX_TASK_TIMER_MS = 2147483647;
|
|
2861
|
+
function taskTimerMs(value, allowZero = false) {
|
|
2862
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < (allowZero ? 0 : 1) || value > MAX_TASK_TIMER_MS) {
|
|
2863
|
+
throw new Error("Invalid task timer interval");
|
|
2864
|
+
}
|
|
2865
|
+
return value;
|
|
2866
|
+
}
|
|
2867
|
+
function captureTaskWaitOptions(options) {
|
|
2868
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) {
|
|
2869
|
+
throw new Error("Invalid task wait options");
|
|
2870
|
+
}
|
|
2871
|
+
const prototype = Object.getPrototypeOf(options);
|
|
2872
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
2873
|
+
throw new Error("Invalid task wait options");
|
|
2874
|
+
let intervalMs;
|
|
2875
|
+
let signal;
|
|
2876
|
+
for (const key of Reflect.ownKeys(options)) {
|
|
2877
|
+
const property = Object.getOwnPropertyDescriptor(options, key);
|
|
2878
|
+
if (key !== "intervalMs" && key !== "signal" || !property || !("value" in property)) {
|
|
2879
|
+
throw new Error("Invalid task wait options");
|
|
2880
|
+
}
|
|
2881
|
+
const value = property.value;
|
|
2882
|
+
if (value === undefined)
|
|
2883
|
+
continue;
|
|
2884
|
+
if (key === "intervalMs")
|
|
2885
|
+
intervalMs = taskTimerMs(value);
|
|
2886
|
+
else {
|
|
2887
|
+
if (!(value instanceof AbortSignal))
|
|
2888
|
+
throw new Error("Invalid task wait options");
|
|
2889
|
+
signal = value;
|
|
2890
|
+
}
|
|
2891
|
+
}
|
|
2892
|
+
return {
|
|
2893
|
+
...intervalMs === undefined ? {} : { intervalMs },
|
|
2894
|
+
...signal === undefined ? {} : { signal }
|
|
2895
|
+
};
|
|
2896
|
+
}
|
|
2897
|
+
function captureTaskRealtimeSource(value) {
|
|
2898
|
+
if (value === undefined)
|
|
2899
|
+
return null;
|
|
2900
|
+
try {
|
|
2901
|
+
const source = responseRecord(queueJsonSnapshot(value), "task Realtime source");
|
|
2902
|
+
if (Object.keys(source).some((key) => key !== "schema" && key !== "table"))
|
|
2903
|
+
throw new Error;
|
|
2904
|
+
const schema = responseString(source, "schema", "task Realtime source");
|
|
2905
|
+
const table = responseString(source, "table", "task Realtime source");
|
|
2906
|
+
if (![schema, table].every((name) => /^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(name)))
|
|
2907
|
+
throw new Error;
|
|
2908
|
+
return { schema, table };
|
|
2909
|
+
} catch {
|
|
2910
|
+
throw new Error("Invalid task Realtime source");
|
|
2911
|
+
}
|
|
2912
|
+
}
|
|
2913
|
+
function captureTaskSubscribeOptions(options) {
|
|
2914
|
+
if (!options || typeof options !== "object" || Array.isArray(options) || Object.getPrototypeOf(options) !== Object.prototype && Object.getPrototypeOf(options) !== null) {
|
|
2915
|
+
throw new Error("Invalid task subscription options");
|
|
2916
|
+
}
|
|
2917
|
+
const allowed = new Set([
|
|
2918
|
+
"realtime",
|
|
2919
|
+
"pollingIntervalMs",
|
|
2920
|
+
"realtimeTimeoutMs",
|
|
2921
|
+
"reconcileIntervalMs",
|
|
2922
|
+
"onUpdate",
|
|
2923
|
+
"onStateChange",
|
|
2924
|
+
"onError",
|
|
2925
|
+
"stopOnTerminal"
|
|
2926
|
+
]);
|
|
2927
|
+
for (const key of Reflect.ownKeys(options)) {
|
|
2928
|
+
const property = Object.getOwnPropertyDescriptor(options, key);
|
|
2929
|
+
if (typeof key !== "string" || !allowed.has(key) || !property || !("value" in property)) {
|
|
2930
|
+
throw new Error("Invalid task subscription options");
|
|
2931
|
+
}
|
|
2932
|
+
}
|
|
2933
|
+
const captured = { ...options };
|
|
2934
|
+
if (typeof captured.onUpdate !== "function" || captured.onStateChange !== undefined && typeof captured.onStateChange !== "function" || captured.onError !== undefined && typeof captured.onError !== "function" || captured.stopOnTerminal !== undefined && typeof captured.stopOnTerminal !== "boolean") {
|
|
2935
|
+
throw new Error("Invalid task subscription options");
|
|
2936
|
+
}
|
|
2937
|
+
const realtime = captureTaskRealtimeSource(captured.realtime);
|
|
2938
|
+
if (realtime)
|
|
2939
|
+
captured.realtime = realtime;
|
|
2940
|
+
return captured;
|
|
2941
|
+
}
|
|
2942
|
+
function normalizeTaskSnapshot(task, taskId, projectRef, decoder) {
|
|
2943
|
+
let value;
|
|
2944
|
+
try {
|
|
2945
|
+
value = decodeBoundTask(queueJsonSnapshot(task), taskId, "get");
|
|
2946
|
+
validateTaskProject(value, projectRef);
|
|
2947
|
+
if (Object.hasOwn(value, "updatedAt"))
|
|
2948
|
+
taskNullable(value.updatedAt, taskText);
|
|
2949
|
+
} catch {
|
|
2950
|
+
throw new SupaCloudTaskResponseError("get");
|
|
2951
|
+
}
|
|
2952
|
+
const decoded = decoder === undefined ? value : decodeTaskResult(value, decoder, "subscribe");
|
|
656
2953
|
return {
|
|
657
|
-
id:
|
|
658
|
-
status:
|
|
659
|
-
progress: typeof
|
|
660
|
-
error: typeof
|
|
661
|
-
updatedAt: typeof
|
|
662
|
-
raw
|
|
2954
|
+
id: decoded.id,
|
|
2955
|
+
status: decoded.status,
|
|
2956
|
+
progress: typeof decoded.progress === "number" ? decoded.progress : null,
|
|
2957
|
+
error: typeof decoded.error === "string" ? decoded.error : typeof decoded.error_message === "string" ? decoded.error_message : null,
|
|
2958
|
+
updatedAt: typeof decoded.updated_at === "string" ? decoded.updated_at : typeof decoded.updatedAt === "string" ? decoded.updatedAt : null,
|
|
2959
|
+
raw: decoded
|
|
663
2960
|
};
|
|
664
2961
|
}
|
|
665
2962
|
|
|
@@ -668,23 +2965,25 @@ class SupaCloudManagementClient {
|
|
|
668
2965
|
constructor(options) {
|
|
669
2966
|
this.options = options;
|
|
670
2967
|
}
|
|
671
|
-
async resolveAccessToken() {
|
|
2968
|
+
async resolveAccessToken(_signal) {
|
|
672
2969
|
const token = await this.options.getAccessToken();
|
|
673
2970
|
if (!token) {
|
|
674
2971
|
throw new Error("No SupaCloud management API access token available. Pass getAccessToken() or ensure supabase.auth has an active session.");
|
|
675
2972
|
}
|
|
676
2973
|
return token;
|
|
677
2974
|
}
|
|
678
|
-
async request(path, method, body, decode) {
|
|
679
|
-
|
|
680
|
-
const
|
|
2975
|
+
async request(path, method, body, decode, transport = globalThis.fetch.bind(globalThis), signal) {
|
|
2976
|
+
signal?.throwIfAborted();
|
|
2977
|
+
const accessToken = await this.resolveAccessToken(signal);
|
|
2978
|
+
signal?.throwIfAborted();
|
|
2979
|
+
const response = await transport(`${this.options.managementApiUrl}${path}`, {
|
|
681
2980
|
method,
|
|
682
2981
|
headers: {
|
|
683
2982
|
authorization: `Bearer ${accessToken}`,
|
|
684
|
-
"x-client-info": `supacloud-js/${SUPACLOUD_JS_VERSION}`,
|
|
685
2983
|
...body !== undefined ? { "content-type": "application/json" } : {}
|
|
686
2984
|
},
|
|
687
|
-
...body !== undefined ? { body: JSON.stringify(body) } : {}
|
|
2985
|
+
...body !== undefined ? { body: JSON.stringify(body) } : {},
|
|
2986
|
+
...signal === undefined ? {} : { signal }
|
|
688
2987
|
});
|
|
689
2988
|
if (response.status === 204)
|
|
690
2989
|
return decode(undefined);
|
|
@@ -699,6 +2998,67 @@ class SupaCloudManagementClient {
|
|
|
699
2998
|
}
|
|
700
2999
|
|
|
701
3000
|
class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
3001
|
+
async resolveAccessToken(signal) {
|
|
3002
|
+
signal?.throwIfAborted();
|
|
3003
|
+
let timer;
|
|
3004
|
+
let onAbort = () => {};
|
|
3005
|
+
const aborted = new Promise((_, reject) => {
|
|
3006
|
+
onAbort = () => reject(signal?.reason);
|
|
3007
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3008
|
+
});
|
|
3009
|
+
const timeoutError = new SupaCloudTaskAuthenticationError("TASK_AUTH_TIMEOUT");
|
|
3010
|
+
const deadline = new Promise((_, reject) => {
|
|
3011
|
+
timer = setTimeout(() => reject(timeoutError), 15000);
|
|
3012
|
+
});
|
|
3013
|
+
try {
|
|
3014
|
+
const token = await Promise.race([super.resolveAccessToken(), deadline, aborted]);
|
|
3015
|
+
signal?.throwIfAborted();
|
|
3016
|
+
if (typeof token !== "string" || !/^[\x21-\x7e]+$/.test(token)) {
|
|
3017
|
+
throw new SupaCloudTaskAuthenticationError;
|
|
3018
|
+
}
|
|
3019
|
+
return token;
|
|
3020
|
+
} catch (error) {
|
|
3021
|
+
signal?.throwIfAborted();
|
|
3022
|
+
if (error === timeoutError)
|
|
3023
|
+
throw timeoutError;
|
|
3024
|
+
throw new SupaCloudTaskAuthenticationError;
|
|
3025
|
+
} finally {
|
|
3026
|
+
clearTimeout(timer);
|
|
3027
|
+
signal?.removeEventListener("abort", onAbort);
|
|
3028
|
+
}
|
|
3029
|
+
}
|
|
3030
|
+
request(path, method, body, decode, _transport, signal) {
|
|
3031
|
+
const operation = method === "POST" ? path.endsWith("/cancel") ? "cancel" : "retry" : "get";
|
|
3032
|
+
const projectRef = this.options.projectRef;
|
|
3033
|
+
const failure = () => new SupaCloudTaskResponseError(operation);
|
|
3034
|
+
const bounded = createBoundedRpcFetch(/./, failure);
|
|
3035
|
+
const transport = async (input, init) => {
|
|
3036
|
+
const response = await bounded(input, init);
|
|
3037
|
+
if (response.status >= 500 || response.ok && response.status !== 200)
|
|
3038
|
+
throw failure();
|
|
3039
|
+
return response;
|
|
3040
|
+
};
|
|
3041
|
+
return super.request(path, method, body, (value) => {
|
|
3042
|
+
try {
|
|
3043
|
+
const rows = Array.isArray(value) ? value : [value];
|
|
3044
|
+
for (const task of rows) {
|
|
3045
|
+
const record = responseRecord(task, "task");
|
|
3046
|
+
validateTaskProject(record, projectRef);
|
|
3047
|
+
}
|
|
3048
|
+
return decode(value);
|
|
3049
|
+
} catch (error) {
|
|
3050
|
+
if (error instanceof SupaCloudTaskDecoderError)
|
|
3051
|
+
throw error;
|
|
3052
|
+
throw failure();
|
|
3053
|
+
}
|
|
3054
|
+
}, transport, signal).then((value) => {
|
|
3055
|
+
signal?.throwIfAborted();
|
|
3056
|
+
return value;
|
|
3057
|
+
}, (error) => {
|
|
3058
|
+
signal?.throwIfAborted();
|
|
3059
|
+
throw error;
|
|
3060
|
+
});
|
|
3061
|
+
}
|
|
702
3062
|
createReceipt(taskId, status) {
|
|
703
3063
|
return {
|
|
704
3064
|
taskId,
|
|
@@ -707,7 +3067,7 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
707
3067
|
wait: (options) => this.wait(taskId, options),
|
|
708
3068
|
cancel: () => this.cancel(taskId),
|
|
709
3069
|
retry: () => this.retry(taskId),
|
|
710
|
-
subscribe: (options) => this.
|
|
3070
|
+
subscribe: (options) => this.subscribe(taskId, options)
|
|
711
3071
|
};
|
|
712
3072
|
}
|
|
713
3073
|
createTypedReceipt(taskId, status, decoder) {
|
|
@@ -718,11 +3078,12 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
718
3078
|
wait: (options) => this.waitTyped(taskId, decoder, options),
|
|
719
3079
|
cancel: () => this.cancelTyped(taskId, decoder),
|
|
720
3080
|
retry: () => this.retryTyped(taskId, decoder),
|
|
721
|
-
subscribe: (options) => this.
|
|
3081
|
+
subscribe: (options) => this.subscribeTypedInternal(taskId, options, decoder)
|
|
722
3082
|
};
|
|
723
3083
|
}
|
|
724
|
-
async
|
|
725
|
-
const
|
|
3084
|
+
async submitInternal(functionName, options = {}, decoder) {
|
|
3085
|
+
const projectRef = this.options.projectRef;
|
|
3086
|
+
const { body, headers = {}, idempotencyKey, method } = options;
|
|
726
3087
|
const invokeHeaders = {
|
|
727
3088
|
...headers,
|
|
728
3089
|
...idempotencyKey ? { "x-supacloud-idempotency-key": idempotencyKey } : {},
|
|
@@ -730,40 +3091,92 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
730
3091
|
...options.businessTaskId ? { "x-supacloud-business-task-id": options.businessTaskId } : {},
|
|
731
3092
|
...options.metadata ? { "x-supacloud-task-metadata": JSON.stringify(options.metadata) } : {}
|
|
732
3093
|
};
|
|
733
|
-
const
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
3094
|
+
const controller = new AbortController;
|
|
3095
|
+
const failure = () => new SupaCloudTaskSubmitError("Background task submission could not be confirmed", undefined);
|
|
3096
|
+
const timeoutError = new SupaCloudTaskSubmitError("Background task submission timed out; outcome is unconfirmed", undefined);
|
|
3097
|
+
let timer;
|
|
3098
|
+
const deadline = new Promise((_, reject) => {
|
|
3099
|
+
timer = setTimeout(() => {
|
|
3100
|
+
reject(timeoutError);
|
|
3101
|
+
controller.abort(timeoutError);
|
|
3102
|
+
}, 15000);
|
|
737
3103
|
});
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
3104
|
+
let invocation;
|
|
3105
|
+
try {
|
|
3106
|
+
invocation = await Promise.race([
|
|
3107
|
+
this.options.supabase.functions.invoke(functionName, {
|
|
3108
|
+
...body === undefined ? {} : { body },
|
|
3109
|
+
...method === undefined ? {} : { method },
|
|
3110
|
+
headers: invokeHeaders,
|
|
3111
|
+
signal: controller.signal
|
|
3112
|
+
}),
|
|
3113
|
+
deadline
|
|
3114
|
+
]);
|
|
3115
|
+
} catch (error) {
|
|
3116
|
+
if (error === timeoutError)
|
|
3117
|
+
throw timeoutError;
|
|
3118
|
+
throw failure();
|
|
3119
|
+
} finally {
|
|
3120
|
+
clearTimeout(timer);
|
|
3121
|
+
}
|
|
3122
|
+
const { data, error, response } = invocation;
|
|
3123
|
+
const boundedHttpFailure = response instanceof Response && boundedTaskHttpFailures.delete(response);
|
|
3124
|
+
if (error !== null && error !== undefined) {
|
|
3125
|
+
if (error instanceof FunctionsHttpError && response instanceof Response && error.context === response && !response.redirected && response.status >= 400 && response.status < 500) {
|
|
3126
|
+
throw error;
|
|
3127
|
+
}
|
|
3128
|
+
if (boundedHttpFailure && response instanceof Response && !response.redirected && response.status >= 400 && response.status < 500 && matchesForeignTaskHttpError(error, response)) {
|
|
3129
|
+
throw new FunctionsHttpError(response);
|
|
3130
|
+
}
|
|
3131
|
+
if (response instanceof Response)
|
|
3132
|
+
response.body?.cancel().catch(() => {});
|
|
3133
|
+
throw failure();
|
|
745
3134
|
}
|
|
746
|
-
|
|
3135
|
+
if (!(response instanceof Response) || response.status !== 202 || response.redirected) {
|
|
3136
|
+
if (response instanceof Response)
|
|
3137
|
+
response.body?.cancel().catch(() => {});
|
|
3138
|
+
throw failure();
|
|
3139
|
+
}
|
|
3140
|
+
try {
|
|
3141
|
+
const payload = responseRecord(queueJsonSnapshot(data), "task submission");
|
|
3142
|
+
validateTaskProject(payload, projectRef);
|
|
3143
|
+
const snakeId = Object.hasOwn(payload, "task_id") ? captureTaskId(payload.task_id) : undefined;
|
|
3144
|
+
const camelId = Object.hasOwn(payload, "taskId") ? captureTaskId(payload.taskId) : undefined;
|
|
3145
|
+
const taskId = snakeId ?? camelId;
|
|
3146
|
+
if (taskId === undefined || snakeId !== undefined && camelId !== undefined && snakeId !== camelId) {
|
|
3147
|
+
throw new Error("Invalid task receipt identity");
|
|
3148
|
+
}
|
|
3149
|
+
const status = responseString(payload, "status", "task submission");
|
|
3150
|
+
if (status.trim() !== status || /[\u0000-\u001f\u007f]/.test(status)) {
|
|
3151
|
+
throw new Error("Invalid task receipt status");
|
|
3152
|
+
}
|
|
3153
|
+
return decoder === undefined ? this.createReceipt(taskId, status) : this.createTypedReceipt(taskId, status, decoder);
|
|
3154
|
+
} catch {
|
|
3155
|
+
throw new SupaCloudTaskSubmitError("Background task submission could not be confirmed", data);
|
|
3156
|
+
}
|
|
3157
|
+
}
|
|
3158
|
+
async submit(functionName, options = {}) {
|
|
3159
|
+
return this.submitInternal(functionName, options);
|
|
747
3160
|
}
|
|
748
3161
|
async submitTyped(functionName, decoderOrOptions, optionsOrDecoder) {
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
return this.createTypedReceipt(receipt.taskId, receipt.status, decoder);
|
|
3162
|
+
const decoder = typeof decoderOrOptions === "function" ? captureTaskDecoder(decoderOrOptions) : captureTaskDecoder(optionsOrDecoder);
|
|
3163
|
+
const options = typeof decoderOrOptions === "function" ? optionsOrDecoder ?? {} : decoderOrOptions;
|
|
3164
|
+
return this.submitInternal(functionName, options, decoder);
|
|
3165
|
+
}
|
|
3166
|
+
getInternal(taskId, decoder, signal) {
|
|
3167
|
+
const captured = captureTaskId(taskId);
|
|
3168
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/${encodeURIComponent(captured)}`, "GET", undefined, (value) => {
|
|
3169
|
+
const task = decodeBoundTask(value, captured, "get");
|
|
3170
|
+
return decoder === undefined ? task : decodeTaskResult(task, decoder, "get");
|
|
3171
|
+
}, undefined, signal);
|
|
760
3172
|
}
|
|
761
|
-
async get(taskId) {
|
|
762
|
-
return this.
|
|
3173
|
+
async get(taskId, signal) {
|
|
3174
|
+
return this.getInternal(taskId, undefined, signal);
|
|
763
3175
|
}
|
|
764
|
-
async getTyped(taskId,
|
|
765
|
-
const
|
|
766
|
-
|
|
3176
|
+
async getTyped(taskId, decoderOrSignal, signalOrDecoder) {
|
|
3177
|
+
const decoder = typeof decoderOrSignal === "function" ? captureTaskDecoder(decoderOrSignal) : captureTaskDecoder(signalOrDecoder);
|
|
3178
|
+
const signal = typeof decoderOrSignal === "function" ? signalOrDecoder : decoderOrSignal;
|
|
3179
|
+
return this.getInternal(taskId, decoder, signal);
|
|
767
3180
|
}
|
|
768
3181
|
async list(filters = {}) {
|
|
769
3182
|
return this.request(`/v1/projects/${this.options.projectRef}/tasks${createQueryString(filters)}`, "GET", undefined, decodeTaskDetails);
|
|
@@ -771,42 +3184,61 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
771
3184
|
async listTyped(decoderOrFilters, filtersOrDecoder) {
|
|
772
3185
|
const decoder = typeof decoderOrFilters === "function" ? captureTaskDecoder(decoderOrFilters) : captureTaskDecoder(filtersOrDecoder);
|
|
773
3186
|
const filters = typeof decoderOrFilters === "function" ? filtersOrDecoder : decoderOrFilters;
|
|
774
|
-
return (
|
|
3187
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks${createQueryString(filters)}`, "GET", undefined, (value) => decodeTaskDetailsWithResult(value, decoder));
|
|
3188
|
+
}
|
|
3189
|
+
cancelInternal(taskId, decoder) {
|
|
3190
|
+
const captured = captureTaskId(taskId);
|
|
3191
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/${encodeURIComponent(captured)}/cancel`, "POST", undefined, (value) => {
|
|
3192
|
+
const task = decodeBoundTask(value, captured, "cancel");
|
|
3193
|
+
return decoder === undefined ? task : decodeTaskResult(task, decoder, "cancel");
|
|
3194
|
+
});
|
|
775
3195
|
}
|
|
776
3196
|
async cancel(taskId) {
|
|
777
|
-
return this.
|
|
3197
|
+
return this.cancelInternal(taskId);
|
|
778
3198
|
}
|
|
779
3199
|
async cancelTyped(taskId, decoder) {
|
|
780
|
-
return
|
|
3200
|
+
return this.cancelInternal(taskId, captureTaskDecoder(decoder));
|
|
3201
|
+
}
|
|
3202
|
+
retryInternal(taskId, decoder) {
|
|
3203
|
+
const captured = captureTaskId(taskId);
|
|
3204
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/${encodeURIComponent(captured)}/retry`, "POST", undefined, (value) => {
|
|
3205
|
+
const task = decodeBoundTask(value, captured, "retry");
|
|
3206
|
+
return decoder === undefined ? task : decodeTaskResult(task, decoder, "retry");
|
|
3207
|
+
});
|
|
781
3208
|
}
|
|
782
3209
|
async retry(taskId) {
|
|
783
|
-
return this.
|
|
3210
|
+
return this.retryInternal(taskId);
|
|
784
3211
|
}
|
|
785
3212
|
async retryTyped(taskId, decoder) {
|
|
786
|
-
return
|
|
3213
|
+
return this.retryInternal(taskId, captureTaskDecoder(decoder));
|
|
787
3214
|
}
|
|
788
3215
|
async listDlq(limit = 100) {
|
|
789
|
-
return this.
|
|
3216
|
+
return this.list({ dlq: true, limit });
|
|
790
3217
|
}
|
|
791
3218
|
async listDlqTyped(decoder, limit = 100) {
|
|
792
3219
|
return this.listTyped({ dlq: true, limit }, captureTaskDecoder(decoder));
|
|
793
3220
|
}
|
|
794
|
-
async
|
|
795
|
-
|
|
3221
|
+
async waitInternal(taskId, decoder, options = {}) {
|
|
3222
|
+
options = captureTaskWaitOptions(options);
|
|
3223
|
+
const { signal } = options;
|
|
3224
|
+
const intervalMs = taskTimerMs(options.intervalMs === undefined ? this.options.pollingIntervalMs : options.intervalMs);
|
|
796
3225
|
while (true) {
|
|
797
|
-
if (
|
|
798
|
-
throw
|
|
3226
|
+
if (signal?.aborted) {
|
|
3227
|
+
throw signal.reason;
|
|
799
3228
|
}
|
|
800
|
-
const task = await this.get(taskId);
|
|
801
|
-
if (TERMINAL_STATUSES.has(
|
|
3229
|
+
const task = decoder === undefined ? await this.get(taskId, signal) : await this.getTyped(taskId, decoder, signal);
|
|
3230
|
+
if (TERMINAL_STATUSES.has(task.status))
|
|
802
3231
|
return task;
|
|
803
|
-
await waitForPollingInterval(intervalMs,
|
|
3232
|
+
await waitForPollingInterval(intervalMs, signal);
|
|
804
3233
|
}
|
|
805
3234
|
}
|
|
3235
|
+
async wait(taskId, options = {}) {
|
|
3236
|
+
return this.waitInternal(taskId, undefined, options);
|
|
3237
|
+
}
|
|
806
3238
|
async waitTyped(taskId, decoderOrOptions, optionsOrDecoder) {
|
|
807
3239
|
const decoder = typeof decoderOrOptions === "function" ? captureTaskDecoder(decoderOrOptions) : captureTaskDecoder(optionsOrDecoder);
|
|
808
3240
|
const options = typeof decoderOrOptions === "function" ? optionsOrDecoder : decoderOrOptions;
|
|
809
|
-
return
|
|
3241
|
+
return this.waitInternal(taskId, decoder, options);
|
|
810
3242
|
}
|
|
811
3243
|
subscribe(taskId, options) {
|
|
812
3244
|
return this.subscribeInternal(taskId, options);
|
|
@@ -814,24 +3246,54 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
814
3246
|
subscribeTyped(taskId, decoderOrOptions, optionsOrDecoder) {
|
|
815
3247
|
const decoder = typeof decoderOrOptions === "function" ? captureTaskDecoder(decoderOrOptions) : captureTaskDecoder(optionsOrDecoder);
|
|
816
3248
|
const options = typeof decoderOrOptions === "function" ? optionsOrDecoder : decoderOrOptions;
|
|
3249
|
+
return this.subscribeTypedInternal(taskId, options, decoder);
|
|
3250
|
+
}
|
|
3251
|
+
subscribeTypedInternal(taskId, options, decoder) {
|
|
817
3252
|
return this.subscribeInternal(taskId, options, decoder);
|
|
818
3253
|
}
|
|
819
3254
|
subscribeInternal(taskId, options, decoder) {
|
|
3255
|
+
taskId = captureTaskId(taskId);
|
|
3256
|
+
options = captureTaskSubscribeOptions(options);
|
|
3257
|
+
const realtime = captureTaskRealtimeSource(options.realtime);
|
|
3258
|
+
const projectRef = this.options.projectRef;
|
|
820
3259
|
let closed = false;
|
|
821
3260
|
let channel = null;
|
|
822
3261
|
let pollTimer = null;
|
|
823
3262
|
let realtimeTimeoutTimer = null;
|
|
824
3263
|
let reconcileTimer = null;
|
|
825
3264
|
let mode = "connecting";
|
|
826
|
-
const pollingIntervalMs = options.pollingIntervalMs
|
|
827
|
-
const realtimeTimeoutMs = options.realtimeTimeoutMs
|
|
828
|
-
const reconcileIntervalMs = options.reconcileIntervalMs
|
|
3265
|
+
const pollingIntervalMs = taskTimerMs(options.pollingIntervalMs === undefined ? this.options.pollingIntervalMs : options.pollingIntervalMs);
|
|
3266
|
+
const realtimeTimeoutMs = taskTimerMs(options.realtimeTimeoutMs === undefined ? 1e4 : options.realtimeTimeoutMs, true);
|
|
3267
|
+
const reconcileIntervalMs = taskTimerMs(options.reconcileIntervalMs === undefined ? Math.min(MAX_TASK_TIMER_MS, Math.max(30000, pollingIntervalMs * 10)) : options.reconcileIntervalMs, true);
|
|
829
3268
|
const stopOnTerminal = options.stopOnTerminal ?? true;
|
|
3269
|
+
const readController = new AbortController;
|
|
3270
|
+
const readTask = async (signal) => decoder === undefined ? await this.get(taskId, signal) : await this.getTyped(taskId, decoder, signal);
|
|
3271
|
+
let callbackFailed = false;
|
|
3272
|
+
const callCallback = (callback, onFailure) => {
|
|
3273
|
+
try {
|
|
3274
|
+
const result = callback();
|
|
3275
|
+
if (result !== undefined)
|
|
3276
|
+
Promise.resolve(result).catch(onFailure);
|
|
3277
|
+
} catch (error) {
|
|
3278
|
+
onFailure(error);
|
|
3279
|
+
}
|
|
3280
|
+
};
|
|
3281
|
+
const handleCallbackFailure = (error, report = true) => {
|
|
3282
|
+
if (callbackFailed)
|
|
3283
|
+
return;
|
|
3284
|
+
callbackFailed = true;
|
|
3285
|
+
close();
|
|
3286
|
+
if (report)
|
|
3287
|
+
reportError(error);
|
|
3288
|
+
};
|
|
3289
|
+
const reportError = (error) => {
|
|
3290
|
+
callCallback(() => options.onError?.(error), (cause) => handleCallbackFailure(cause, false));
|
|
3291
|
+
};
|
|
830
3292
|
const setMode = (next, details) => {
|
|
831
|
-
if (closed || mode === next)
|
|
3293
|
+
if (closed && next !== "closed" || mode === next)
|
|
832
3294
|
return;
|
|
833
3295
|
mode = next;
|
|
834
|
-
options.onStateChange?.(next, details);
|
|
3296
|
+
callCallback(() => options.onStateChange?.(next, details), handleCallbackFailure);
|
|
835
3297
|
};
|
|
836
3298
|
const stopPolling = () => {
|
|
837
3299
|
if (pollTimer) {
|
|
@@ -855,22 +3317,38 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
855
3317
|
if (channel) {
|
|
856
3318
|
const current = channel;
|
|
857
3319
|
channel = null;
|
|
858
|
-
|
|
3320
|
+
try {
|
|
3321
|
+
await this.options.supabase.removeChannel(current);
|
|
3322
|
+
} catch (error) {
|
|
3323
|
+
reportError(error);
|
|
3324
|
+
}
|
|
859
3325
|
}
|
|
860
3326
|
};
|
|
861
3327
|
const close = async () => {
|
|
862
3328
|
if (closed)
|
|
863
3329
|
return;
|
|
3330
|
+
closed = true;
|
|
3331
|
+
readController.abort();
|
|
864
3332
|
stopPolling();
|
|
865
3333
|
stopRealtimeTimeout();
|
|
866
3334
|
stopReconcile();
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
3335
|
+
try {
|
|
3336
|
+
await teardownRealtime();
|
|
3337
|
+
} finally {
|
|
3338
|
+
setMode("closed");
|
|
3339
|
+
}
|
|
870
3340
|
};
|
|
871
3341
|
const emitTask = (task) => {
|
|
872
|
-
|
|
873
|
-
|
|
3342
|
+
if (closed)
|
|
3343
|
+
return;
|
|
3344
|
+
let snapshot;
|
|
3345
|
+
try {
|
|
3346
|
+
snapshot = normalizeTaskSnapshot(task, taskId, projectRef, decoder);
|
|
3347
|
+
} catch (error) {
|
|
3348
|
+
reportError(error);
|
|
3349
|
+
return;
|
|
3350
|
+
}
|
|
3351
|
+
callCallback(() => options.onUpdate(snapshot), handleCallbackFailure);
|
|
874
3352
|
if (stopOnTerminal && TERMINAL_STATUSES.has(snapshot.status)) {
|
|
875
3353
|
close();
|
|
876
3354
|
}
|
|
@@ -879,10 +3357,11 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
879
3357
|
if (closed)
|
|
880
3358
|
return;
|
|
881
3359
|
try {
|
|
882
|
-
const task = await
|
|
3360
|
+
const task = await readTask(readController.signal);
|
|
883
3361
|
emitTask(task);
|
|
884
3362
|
} catch (error) {
|
|
885
|
-
|
|
3363
|
+
if (!closed)
|
|
3364
|
+
reportError(error);
|
|
886
3365
|
} finally {
|
|
887
3366
|
if (!closed && mode === "polling") {
|
|
888
3367
|
pollTimer = setTimeout(() => {
|
|
@@ -895,9 +3374,10 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
895
3374
|
if (closed || mode !== "realtime")
|
|
896
3375
|
return;
|
|
897
3376
|
try {
|
|
898
|
-
emitTask(await
|
|
3377
|
+
emitTask(await readTask(readController.signal));
|
|
899
3378
|
} catch (error) {
|
|
900
|
-
|
|
3379
|
+
if (!closed)
|
|
3380
|
+
reportError(error);
|
|
901
3381
|
} finally {
|
|
902
3382
|
if (!closed && mode === "realtime") {
|
|
903
3383
|
reconcileTimer = setTimeout(() => {
|
|
@@ -923,26 +3403,42 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
923
3403
|
setMode("polling", { error });
|
|
924
3404
|
pollOnce();
|
|
925
3405
|
};
|
|
3406
|
+
const subscription = {
|
|
3407
|
+
get connectionState() {
|
|
3408
|
+
return mode;
|
|
3409
|
+
},
|
|
3410
|
+
unsubscribe() {
|
|
3411
|
+
close();
|
|
3412
|
+
}
|
|
3413
|
+
};
|
|
3414
|
+
if (!realtime) {
|
|
3415
|
+
startPolling();
|
|
3416
|
+
return subscription;
|
|
3417
|
+
}
|
|
926
3418
|
channel = this.options.supabase.channel(`supacloud-task:${this.options.projectRef}:${taskId}`).on("postgres_changes", {
|
|
927
3419
|
event: "*",
|
|
928
|
-
schema:
|
|
929
|
-
table:
|
|
3420
|
+
schema: realtime.schema,
|
|
3421
|
+
table: realtime.table,
|
|
930
3422
|
filter: `id=eq.${taskId}`
|
|
931
3423
|
}, (payload) => {
|
|
932
3424
|
const next = payload.new && Object.keys(payload.new).length > 0 ? payload.new : payload.old;
|
|
933
3425
|
if (next)
|
|
934
3426
|
emitTask(next);
|
|
935
|
-
})
|
|
3427
|
+
});
|
|
3428
|
+
channel.subscribe(async (status, error) => {
|
|
936
3429
|
if (closed)
|
|
937
3430
|
return;
|
|
938
3431
|
if (status === "SUBSCRIBED") {
|
|
939
3432
|
stopPolling();
|
|
940
3433
|
stopRealtimeTimeout();
|
|
941
3434
|
setMode("realtime");
|
|
3435
|
+
if (closed)
|
|
3436
|
+
return;
|
|
942
3437
|
try {
|
|
943
|
-
emitTask(await
|
|
3438
|
+
emitTask(await readTask(readController.signal));
|
|
944
3439
|
} catch (err) {
|
|
945
|
-
|
|
3440
|
+
if (!closed)
|
|
3441
|
+
reportError(err);
|
|
946
3442
|
}
|
|
947
3443
|
startReconcile();
|
|
948
3444
|
return;
|
|
@@ -952,7 +3448,7 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
952
3448
|
startPolling(error);
|
|
953
3449
|
}
|
|
954
3450
|
});
|
|
955
|
-
if (realtimeTimeoutMs > 0) {
|
|
3451
|
+
if (!closed && realtimeTimeoutMs > 0) {
|
|
956
3452
|
realtimeTimeoutTimer = setTimeout(() => {
|
|
957
3453
|
if (!closed && mode === "connecting") {
|
|
958
3454
|
teardownRealtime().finally(() => {
|
|
@@ -962,14 +3458,7 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
|
|
|
962
3458
|
}, realtimeTimeoutMs);
|
|
963
3459
|
}
|
|
964
3460
|
setMode("connecting");
|
|
965
|
-
return
|
|
966
|
-
get connectionState() {
|
|
967
|
-
return mode;
|
|
968
|
-
},
|
|
969
|
-
unsubscribe() {
|
|
970
|
-
close();
|
|
971
|
-
}
|
|
972
|
-
};
|
|
3461
|
+
return subscription;
|
|
973
3462
|
}
|
|
974
3463
|
}
|
|
975
3464
|
|
|
@@ -978,62 +3467,81 @@ class SupaCloudQueueClient extends SupaCloudManagementClient {
|
|
|
978
3467
|
constructor(options, name) {
|
|
979
3468
|
super(options);
|
|
980
3469
|
this.name = name;
|
|
3470
|
+
if (typeof name !== "string" || !/^[a-z0-9][a-z0-9_-]{0,127}$/.test(name) || name.startsWith("supacloud_internal_"))
|
|
3471
|
+
throw new SupaCloudQueueError;
|
|
981
3472
|
}
|
|
982
3473
|
get encodedName() {
|
|
983
3474
|
return encodeURIComponent(this.name);
|
|
984
3475
|
}
|
|
985
3476
|
async rpc(fn, params, decode) {
|
|
986
3477
|
const scopedClient = this.options.supabase.schema("pgmq_public");
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
3478
|
+
try {
|
|
3479
|
+
const rpcResult = await scopedClient.rpc(fn, params).retry(false);
|
|
3480
|
+
const { data, error } = rpcResult;
|
|
3481
|
+
if (error)
|
|
3482
|
+
throw new SupaCloudQueueError(true, "QUEUE_RPC_FAILED");
|
|
3483
|
+
return decode(data);
|
|
3484
|
+
} catch (error) {
|
|
3485
|
+
throw new SupaCloudQueueError(true, error instanceof SupaCloudQueueError ? error.code ?? "QUEUE_CONTRACT_INVALID" : "QUEUE_RPC_FAILED");
|
|
3486
|
+
}
|
|
992
3487
|
}
|
|
993
3488
|
async send(payload = {}, options = {}) {
|
|
3489
|
+
const captured = queueJsonSnapshot(payload);
|
|
994
3490
|
const msgId = await this.rpc("send", {
|
|
995
3491
|
queue_name: this.name,
|
|
996
|
-
message:
|
|
3492
|
+
message: captured,
|
|
997
3493
|
sleep_seconds: normalizeSecondsFromOptions(options)
|
|
998
|
-
},
|
|
3494
|
+
}, queueRpcId);
|
|
999
3495
|
return {
|
|
1000
3496
|
id: String(msgId),
|
|
1001
3497
|
msg_id: msgId,
|
|
1002
3498
|
queue_name: this.name,
|
|
1003
3499
|
status: "pending",
|
|
1004
|
-
payload
|
|
3500
|
+
payload: captured
|
|
1005
3501
|
};
|
|
1006
3502
|
}
|
|
1007
3503
|
async sendBatch(messages, options = {}) {
|
|
3504
|
+
if (!Array.isArray(messages) || messages.length === 0 || messages.length > 1e4)
|
|
3505
|
+
throw new SupaCloudQueueError;
|
|
3506
|
+
const captured = queueJsonSnapshot(messages);
|
|
3507
|
+
if (!Array.isArray(captured))
|
|
3508
|
+
throw new SupaCloudQueueError;
|
|
1008
3509
|
const ids = await this.rpc("send_batch", {
|
|
1009
3510
|
queue_name: this.name,
|
|
1010
|
-
messages,
|
|
3511
|
+
messages: captured,
|
|
1011
3512
|
sleep_seconds: normalizeSecondsFromOptions(options)
|
|
1012
|
-
},
|
|
1013
|
-
return ids.map((msgId, index) =>
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
3513
|
+
}, (value) => queueRpcIds(value, captured.length));
|
|
3514
|
+
return ids.map((msgId, index) => {
|
|
3515
|
+
const payload = captured[index];
|
|
3516
|
+
if (payload === undefined)
|
|
3517
|
+
throw new SupaCloudQueueError(true);
|
|
3518
|
+
return {
|
|
3519
|
+
id: msgId,
|
|
3520
|
+
msg_id: msgId,
|
|
3521
|
+
queue_name: this.name,
|
|
3522
|
+
status: "pending",
|
|
3523
|
+
payload
|
|
3524
|
+
};
|
|
3525
|
+
});
|
|
1020
3526
|
}
|
|
1021
3527
|
async read(options = {}) {
|
|
3528
|
+
const count = queueReadCount(options);
|
|
1022
3529
|
return this.rpc("read", {
|
|
1023
3530
|
queue_name: this.name,
|
|
1024
3531
|
sleep_seconds: normalizeSecondsFromOptions(options),
|
|
1025
|
-
n:
|
|
1026
|
-
}, (value) =>
|
|
3532
|
+
n: count
|
|
3533
|
+
}, (value) => queueRpcMessages(this.name, value, count, "leased"));
|
|
1027
3534
|
}
|
|
1028
3535
|
async receive(options = {}) {
|
|
3536
|
+
queueReadCount(options, true);
|
|
1029
3537
|
const messages = await this.read({ ...options, n: 1 });
|
|
1030
3538
|
return messages[0] ?? null;
|
|
1031
3539
|
}
|
|
1032
3540
|
async pop() {
|
|
1033
|
-
return this.rpc("pop", { queue_name: this.name }, (value) =>
|
|
3541
|
+
return this.rpc("pop", { queue_name: this.name }, (value) => queueRpcMessages(this.name, value, 1, "deleted")[0] ?? null);
|
|
1034
3542
|
}
|
|
1035
3543
|
async list(filters = {}) {
|
|
1036
|
-
return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages${createQueueQueryString(filters)}`, "GET", undefined, decodeQueueMessages);
|
|
3544
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages${createQueueQueryString(filters)}`, "GET", undefined, (value) => decodeQueueMessages(value, this.name));
|
|
1037
3545
|
}
|
|
1038
3546
|
async listFailed(limit = 100) {
|
|
1039
3547
|
return this.list({ archived: true, dlq: true, limit });
|
|
@@ -1051,29 +3559,35 @@ class SupaCloudQueueClient extends SupaCloudManagementClient {
|
|
|
1051
3559
|
return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/settings`, "PATCH", settings, decodeQueueSettings);
|
|
1052
3560
|
}
|
|
1053
3561
|
async archive(messageId) {
|
|
1054
|
-
const msgId =
|
|
3562
|
+
const msgId = queueMessageId(messageId);
|
|
1055
3563
|
const success = await this.rpc("archive", {
|
|
1056
3564
|
queue_name: this.name,
|
|
1057
3565
|
message_id: msgId
|
|
1058
|
-
},
|
|
3566
|
+
}, queueRpcBoolean);
|
|
1059
3567
|
return { id: String(msgId), msg_id: msgId, queue_name: this.name, status: "archived", success };
|
|
1060
3568
|
}
|
|
1061
3569
|
async ack(messageId) {
|
|
1062
3570
|
return this.archive(messageId);
|
|
1063
3571
|
}
|
|
1064
3572
|
async delete(messageId) {
|
|
1065
|
-
const msgId =
|
|
3573
|
+
const msgId = queueMessageId(messageId);
|
|
1066
3574
|
const success = await this.rpc("delete", {
|
|
1067
3575
|
queue_name: this.name,
|
|
1068
3576
|
message_id: msgId
|
|
1069
|
-
},
|
|
3577
|
+
}, queueRpcBoolean);
|
|
1070
3578
|
return { id: String(msgId), msg_id: msgId, queue_name: this.name, status: "deleted", success };
|
|
1071
3579
|
}
|
|
1072
3580
|
async release(messageId, options = {}) {
|
|
1073
|
-
|
|
3581
|
+
const msgId = queueMessageId(messageId);
|
|
3582
|
+
const body = {
|
|
1074
3583
|
sleep_seconds: normalizeSecondsFromOptions(options),
|
|
1075
3584
|
...options.error ? { error: options.error } : {}
|
|
1076
|
-
}
|
|
3585
|
+
};
|
|
3586
|
+
try {
|
|
3587
|
+
return await this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${msgId}/release`, "POST", body, (value) => queueMessage(value, { queueName: this.name, messageId: msgId }));
|
|
3588
|
+
} catch {
|
|
3589
|
+
throw new SupaCloudQueueError(true, "QUEUE_MANAGEMENT_FAILED");
|
|
3590
|
+
}
|
|
1077
3591
|
}
|
|
1078
3592
|
async purge() {
|
|
1079
3593
|
return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/purge`, "POST", undefined, decodePurgeResult);
|
|
@@ -1082,10 +3596,12 @@ class SupaCloudQueueClient extends SupaCloudManagementClient {
|
|
|
1082
3596
|
return this.archive(messageId);
|
|
1083
3597
|
}
|
|
1084
3598
|
async get(messageId) {
|
|
1085
|
-
|
|
3599
|
+
const msgId = queueMessageId(messageId);
|
|
3600
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${msgId}`, "GET", undefined, (value) => queueMessage(value, { queueName: this.name, messageId: msgId }));
|
|
1086
3601
|
}
|
|
1087
3602
|
async retry(messageId) {
|
|
1088
|
-
|
|
3603
|
+
const msgId = queueMessageId(messageId);
|
|
3604
|
+
return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${msgId}/retry`, "POST", undefined, (value) => queueMessage(value, { queueName: this.name, messageId: msgId }));
|
|
1089
3605
|
}
|
|
1090
3606
|
}
|
|
1091
3607
|
|
|
@@ -1100,174 +3616,6 @@ class SupaCloudQueuesClient extends SupaCloudManagementClient {
|
|
|
1100
3616
|
await this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${encodeURIComponent(queueName)}`, "DELETE", undefined, decodeVoid);
|
|
1101
3617
|
}
|
|
1102
3618
|
}
|
|
1103
|
-
|
|
1104
|
-
class SupaCloudOAuthServerClient extends SupaCloudManagementClient {
|
|
1105
|
-
async getStatus() {
|
|
1106
|
-
return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-server`, "GET", undefined, decodeOAuthServerStatus);
|
|
1107
|
-
}
|
|
1108
|
-
async migrateToOidc(options = {}) {
|
|
1109
|
-
return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-server/migrate`, "POST", {
|
|
1110
|
-
allow_dynamic_registration: options.allowDynamicRegistration === true,
|
|
1111
|
-
...options.authorizationPath === undefined ? {} : { authorization_path: options.authorizationPath }
|
|
1112
|
-
}, decodeOAuthServerStatus);
|
|
1113
|
-
}
|
|
1114
|
-
async getDiscovery() {
|
|
1115
|
-
const status = await this.getStatus();
|
|
1116
|
-
const response = await fetch(status.discovery_url);
|
|
1117
|
-
if (!response.ok)
|
|
1118
|
-
throw new Error(`SupaCloud OIDC discovery failed (${response.status})`);
|
|
1119
|
-
const payload = await response.json();
|
|
1120
|
-
return valueRecord2(payload);
|
|
1121
|
-
}
|
|
1122
|
-
async getJwks() {
|
|
1123
|
-
const status = await this.getStatus();
|
|
1124
|
-
const response = await fetch(status.jwks_url);
|
|
1125
|
-
if (!response.ok)
|
|
1126
|
-
throw new Error(`SupaCloud JWKS fetch failed (${response.status})`);
|
|
1127
|
-
const payload = await response.json();
|
|
1128
|
-
return valueRecord2(payload);
|
|
1129
|
-
}
|
|
1130
|
-
async buildAuthorizeUrl(options) {
|
|
1131
|
-
const status = await this.getStatus();
|
|
1132
|
-
const url = new URL(status.authorization_endpoint);
|
|
1133
|
-
url.searchParams.set("client_id", options.clientId);
|
|
1134
|
-
url.searchParams.set("redirect_uri", options.redirectUri);
|
|
1135
|
-
url.searchParams.set("response_type", options.responseType ?? "code");
|
|
1136
|
-
const scope = Array.isArray(options.scope) ? options.scope.join(" ") : options.scope;
|
|
1137
|
-
if (scope)
|
|
1138
|
-
url.searchParams.set("scope", scope);
|
|
1139
|
-
if (options.state)
|
|
1140
|
-
url.searchParams.set("state", options.state);
|
|
1141
|
-
if (options.codeChallenge)
|
|
1142
|
-
url.searchParams.set("code_challenge", options.codeChallenge);
|
|
1143
|
-
if (options.codeChallengeMethod)
|
|
1144
|
-
url.searchParams.set("code_challenge_method", options.codeChallengeMethod);
|
|
1145
|
-
if (options.nonce)
|
|
1146
|
-
url.searchParams.set("nonce", options.nonce);
|
|
1147
|
-
if (options.resource)
|
|
1148
|
-
url.searchParams.set("resource", options.resource);
|
|
1149
|
-
return url.toString();
|
|
1150
|
-
}
|
|
1151
|
-
}
|
|
1152
|
-
|
|
1153
|
-
class SupaCloudOAuthClientsClient extends SupaCloudManagementClient {
|
|
1154
|
-
async list() {
|
|
1155
|
-
return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-clients`, "GET", undefined, decodeOAuthClientList);
|
|
1156
|
-
}
|
|
1157
|
-
async create(input) {
|
|
1158
|
-
return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-clients`, "POST", input, decodeOAuthClient);
|
|
1159
|
-
}
|
|
1160
|
-
async get(clientId) {
|
|
1161
|
-
return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-clients/${encodeURIComponent(clientId)}`, "GET", undefined, decodeOAuthClient);
|
|
1162
|
-
}
|
|
1163
|
-
async update(clientId, patch) {
|
|
1164
|
-
return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-clients/${encodeURIComponent(clientId)}`, "PUT", patch, decodeOAuthClient);
|
|
1165
|
-
}
|
|
1166
|
-
async delete(clientId) {
|
|
1167
|
-
await this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-clients/${encodeURIComponent(clientId)}`, "DELETE", undefined, decodeVoid);
|
|
1168
|
-
}
|
|
1169
|
-
async regenerateSecret(clientId) {
|
|
1170
|
-
return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-clients/${encodeURIComponent(clientId)}/regenerate-secret`, "POST", undefined, decodeOAuthClient);
|
|
1171
|
-
}
|
|
1172
|
-
}
|
|
1173
|
-
|
|
1174
|
-
class SupaCloudSupAuthClient extends SupaCloudManagementClient {
|
|
1175
|
-
get basePath() {
|
|
1176
|
-
return `/v1/projects/${this.options.projectRef}/supauth`;
|
|
1177
|
-
}
|
|
1178
|
-
async provision(options = {}) {
|
|
1179
|
-
return this.request(`${this.basePath}/provision`, "POST", options, decodeSupAuthProvisionResult);
|
|
1180
|
-
}
|
|
1181
|
-
async reconcile(options = {}) {
|
|
1182
|
-
return this.request(`${this.basePath}/reconcile`, "POST", options, decodeSupAuthReconcileResult);
|
|
1183
|
-
}
|
|
1184
|
-
async rollback() {
|
|
1185
|
-
return this.request(`${this.basePath}/rollback`, "POST", undefined, decodeSupAuthRollbackResult);
|
|
1186
|
-
}
|
|
1187
|
-
async getClientConfig() {
|
|
1188
|
-
return this.request(`${this.basePath}/client-config`, "GET", undefined, decodeSupAuthClientConfig);
|
|
1189
|
-
}
|
|
1190
|
-
async verify() {
|
|
1191
|
-
return this.request(`${this.basePath}/verify`, "GET", undefined, decodeSupAuthVerification);
|
|
1192
|
-
}
|
|
1193
|
-
}
|
|
1194
|
-
|
|
1195
|
-
class SupaCloudCapabilitiesClient extends SupaCloudManagementClient {
|
|
1196
|
-
async get() {
|
|
1197
|
-
return this.request(`/v1/projects/${this.options.projectRef}/capabilities`, "GET", undefined, decodeProjectCapabilities);
|
|
1198
|
-
}
|
|
1199
|
-
async isAvailable(capabilityKey) {
|
|
1200
|
-
const res = await this.get();
|
|
1201
|
-
return res.capabilities?.[capabilityKey]?.available === true;
|
|
1202
|
-
}
|
|
1203
|
-
async getVersion() {
|
|
1204
|
-
const res = await this.get();
|
|
1205
|
-
return res.platform_version ?? "unknown";
|
|
1206
|
-
}
|
|
1207
|
-
async getEnvironment() {
|
|
1208
|
-
const res = await this.get();
|
|
1209
|
-
return {
|
|
1210
|
-
projectRef: res.project_ref,
|
|
1211
|
-
platformVersion: res.platform_version ?? "unknown",
|
|
1212
|
-
environment: res.environment ?? "production",
|
|
1213
|
-
schemaVersion: res.schema_version,
|
|
1214
|
-
authRuntime: res.auth_runtime,
|
|
1215
|
-
storageBackend: res.storage_backend,
|
|
1216
|
-
capabilities: res.capabilities
|
|
1217
|
-
};
|
|
1218
|
-
}
|
|
1219
|
-
}
|
|
1220
|
-
|
|
1221
|
-
class SupaCloudStorageClient extends SupaCloudManagementClient {
|
|
1222
|
-
async getPlatformConstraints() {
|
|
1223
|
-
return this.request(`/storage/v1/constraints`, "GET", undefined, decodeStoragePlatformConstraints);
|
|
1224
|
-
}
|
|
1225
|
-
async getUploadConstraints(bucketId) {
|
|
1226
|
-
try {
|
|
1227
|
-
const { data, error } = await this.options.supabase.storage.getBucket(bucketId);
|
|
1228
|
-
if (!error && data) {
|
|
1229
|
-
return {
|
|
1230
|
-
bucketId,
|
|
1231
|
-
fileSizeLimit: typeof data.file_size_limit === "number" ? data.file_size_limit : data.file_size_limit ? Number(data.file_size_limit) : null,
|
|
1232
|
-
allowedMimeTypes: Array.isArray(data.allowed_mime_types) ? data.allowed_mime_types : null
|
|
1233
|
-
};
|
|
1234
|
-
}
|
|
1235
|
-
} catch {}
|
|
1236
|
-
try {
|
|
1237
|
-
const bucket = await this.request(`/v1/projects/${this.options.projectRef}/storage/buckets/${encodeURIComponent(bucketId)}`, "GET", undefined, (val) => responseRecord(val, "storage bucket"));
|
|
1238
|
-
const rawLimit = bucket.file_size_limit;
|
|
1239
|
-
const fileSizeLimit = typeof rawLimit === "number" ? rawLimit : rawLimit ? Number(rawLimit) : null;
|
|
1240
|
-
const allowedMimeTypes = Array.isArray(bucket.allowed_mime_types) ? bucket.allowed_mime_types : null;
|
|
1241
|
-
return {
|
|
1242
|
-
bucketId,
|
|
1243
|
-
fileSizeLimit,
|
|
1244
|
-
allowedMimeTypes
|
|
1245
|
-
};
|
|
1246
|
-
} catch {
|
|
1247
|
-
return {
|
|
1248
|
-
bucketId,
|
|
1249
|
-
fileSizeLimit: null,
|
|
1250
|
-
allowedMimeTypes: null
|
|
1251
|
-
};
|
|
1252
|
-
}
|
|
1253
|
-
}
|
|
1254
|
-
async validateUpload(bucketId, file) {
|
|
1255
|
-
const constraints = await this.getUploadConstraints(bucketId);
|
|
1256
|
-
if (constraints.fileSizeLimit !== null && file.size > constraints.fileSizeLimit) {
|
|
1257
|
-
return {
|
|
1258
|
-
valid: false,
|
|
1259
|
-
error: `File size ${file.size} bytes exceeds bucket limit of ${constraints.fileSizeLimit} bytes`
|
|
1260
|
-
};
|
|
1261
|
-
}
|
|
1262
|
-
if (constraints.allowedMimeTypes && constraints.allowedMimeTypes.length > 0 && file.type && !constraints.allowedMimeTypes.includes(file.type)) {
|
|
1263
|
-
return {
|
|
1264
|
-
valid: false,
|
|
1265
|
-
error: `MIME type "${file.type}" is not in the allowed list: ${constraints.allowedMimeTypes.join(", ")}`
|
|
1266
|
-
};
|
|
1267
|
-
}
|
|
1268
|
-
return { valid: true };
|
|
1269
|
-
}
|
|
1270
|
-
}
|
|
1271
3619
|
function createSupaCloudClient(options) {
|
|
1272
3620
|
const normalized = {
|
|
1273
3621
|
...options,
|
|
@@ -1278,10 +3626,7 @@ function createSupaCloudClient(options) {
|
|
|
1278
3626
|
const tasks = new SupaCloudTasksClient(normalized);
|
|
1279
3627
|
const oauthServer = new SupaCloudOAuthServerClient(normalized);
|
|
1280
3628
|
const oauthClients = new SupaCloudOAuthClientsClient(normalized);
|
|
1281
|
-
const supauth = new SupaCloudSupAuthClient(normalized);
|
|
1282
3629
|
const queues = new SupaCloudQueuesClient(normalized);
|
|
1283
|
-
const capabilities = new SupaCloudCapabilitiesClient(normalized);
|
|
1284
|
-
const storage = new SupaCloudStorageClient(normalized);
|
|
1285
3630
|
const workflows2 = new SupaCloudWorkflowsClient(options.supabase);
|
|
1286
3631
|
const commands2 = new SupaCloudCommandsClient(options.supabase);
|
|
1287
3632
|
const artifacts2 = new SupaCloudArtifactsClient(options.supabase);
|
|
@@ -1297,12 +3642,7 @@ function createSupaCloudClient(options) {
|
|
|
1297
3642
|
workflows: workflows2,
|
|
1298
3643
|
commands: commands2,
|
|
1299
3644
|
artifacts: artifacts2,
|
|
1300
|
-
supauth,
|
|
1301
3645
|
queues,
|
|
1302
|
-
capabilities,
|
|
1303
|
-
storage,
|
|
1304
|
-
getEnvironment: () => capabilities.getEnvironment(),
|
|
1305
|
-
getVersion: () => capabilities.getVersion(),
|
|
1306
3646
|
queue: (name) => new SupaCloudQueueClient(normalized, name),
|
|
1307
3647
|
functions: {
|
|
1308
3648
|
invokeBackground: (functionName, submitOptions) => tasks.submit(functionName, submitOptions)
|
|
@@ -1310,16 +3650,39 @@ function createSupaCloudClient(options) {
|
|
|
1310
3650
|
};
|
|
1311
3651
|
}
|
|
1312
3652
|
export {
|
|
1313
|
-
SUPACLOUD_JS_VERSION,
|
|
1314
3653
|
SupaCloudApiError,
|
|
3654
|
+
SupaCloudArtifactLinkError,
|
|
3655
|
+
SupaCloudArtifactReadError,
|
|
3656
|
+
SupaCloudArtifactRegisterError,
|
|
1315
3657
|
SupaCloudArtifactsClient,
|
|
1316
|
-
|
|
3658
|
+
SupaCloudCommandReadError,
|
|
3659
|
+
SupaCloudCommandSubmitError,
|
|
1317
3660
|
SupaCloudCommandsClient,
|
|
1318
|
-
|
|
3661
|
+
SupaCloudOAuthClientError,
|
|
3662
|
+
SupaCloudOAuthClientsClient,
|
|
3663
|
+
SupaCloudOAuthServerClient,
|
|
3664
|
+
SupaCloudOAuthServerError,
|
|
3665
|
+
SupaCloudQueueError,
|
|
3666
|
+
SupaCloudTaskAuthenticationError,
|
|
1319
3667
|
SupaCloudTaskDecoderError as SupaCloudTaskDecodeError,
|
|
1320
3668
|
SupaCloudTaskDecoderError,
|
|
3669
|
+
SupaCloudTaskResponseError,
|
|
1321
3670
|
SupaCloudTaskSubmitError,
|
|
3671
|
+
SupaCloudWorkflowAdvanceError,
|
|
3672
|
+
SupaCloudWorkflowCancelError,
|
|
3673
|
+
SupaCloudWorkflowClaimError,
|
|
3674
|
+
SupaCloudWorkflowClaimInputError,
|
|
3675
|
+
SupaCloudWorkflowCompleteError,
|
|
3676
|
+
SupaCloudWorkflowEventsError,
|
|
3677
|
+
SupaCloudWorkflowFailError,
|
|
3678
|
+
SupaCloudWorkflowReadError,
|
|
3679
|
+
SupaCloudWorkflowRetryError,
|
|
3680
|
+
SupaCloudWorkflowStartError,
|
|
1322
3681
|
SupaCloudWorkflowsClient,
|
|
3682
|
+
createSupaCloudArtifactFetch,
|
|
1323
3683
|
createSupaCloudClient,
|
|
1324
|
-
|
|
3684
|
+
createSupaCloudCommandFetch,
|
|
3685
|
+
createSupaCloudOAuthFetch,
|
|
3686
|
+
createSupaCloudTaskFetch,
|
|
3687
|
+
createSupaCloudWorkflowFetch
|
|
1325
3688
|
};
|