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