@sylphx/sdk 0.7.0 → 0.8.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -27
- package/dist/health/index.mjs +475 -0
- package/dist/health/index.mjs.map +1 -0
- package/dist/index.d.ts +51 -17
- package/dist/index.mjs +11 -6
- package/dist/index.mjs.map +1 -1
- package/dist/nextjs/index.mjs.map +1 -1
- package/dist/react/index.d.ts +2 -2
- package/dist/react/index.mjs +10 -10
- package/dist/react/index.mjs.map +1 -1
- package/dist/server/index.d.ts +11 -7
- package/dist/server/index.mjs +5 -5
- package/dist/server/index.mjs.map +1 -1
- package/dist/web-analytics.mjs.map +1 -1
- package/package.json +18 -14
- package/dist/index.d.cts +0 -9385
- package/dist/index.js +0 -11229
- package/dist/index.js.map +0 -1
- package/dist/nextjs/index.d.cts +0 -567
- package/dist/nextjs/index.js +0 -2081
- package/dist/nextjs/index.js.map +0 -1
- package/dist/react/index.d.cts +0 -14250
- package/dist/react/index.js +0 -81688
- package/dist/react/index.js.map +0 -1
- package/dist/server/index.d.cts +0 -1842
- package/dist/server/index.js +0 -3430
- package/dist/server/index.js.map +0 -1
- package/dist/web-analytics.js +0 -248
- package/dist/web-analytics.js.map +0 -1
package/dist/server/index.js
DELETED
|
@@ -1,3430 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __export = (target, all) => {
|
|
7
|
-
for (var name in all)
|
|
8
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
-
};
|
|
10
|
-
var __copyProps = (to, from, except, desc) => {
|
|
11
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
-
for (let key of __getOwnPropNames(from))
|
|
13
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
-
}
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
-
|
|
20
|
-
// src/server/index.ts
|
|
21
|
-
var server_exports = {};
|
|
22
|
-
__export(server_exports, {
|
|
23
|
-
FunctionsClient: () => FunctionsClient,
|
|
24
|
-
InvalidConnectionUrlError: () => InvalidConnectionUrlError,
|
|
25
|
-
createAI: () => createAI,
|
|
26
|
-
createAuthenticatedServerClient: () => createAuthenticatedServerClient,
|
|
27
|
-
createClient: () => createClient,
|
|
28
|
-
createKv: () => createKv,
|
|
29
|
-
createServerClient: () => createServerClient,
|
|
30
|
-
createServerRestClient: () => createServerRestClient,
|
|
31
|
-
createStreams: () => createStreams,
|
|
32
|
-
createWebhookHandler: () => createWebhookHandler,
|
|
33
|
-
decodeUserId: () => decodeUserId,
|
|
34
|
-
detectEnvironment: () => detectEnvironment,
|
|
35
|
-
detectKeyType: () => detectKeyType,
|
|
36
|
-
encodeUserId: () => encodeUserId,
|
|
37
|
-
getAI: () => getAI,
|
|
38
|
-
getAppConfig: () => getAppConfig,
|
|
39
|
-
getAppMetadata: () => getAppMetadata,
|
|
40
|
-
getConsentTypes: () => getConsentTypes,
|
|
41
|
-
getCookieNamespace: () => getCookieNamespace,
|
|
42
|
-
getDatabaseConnection: () => getDatabaseConnection,
|
|
43
|
-
getDatabaseStatus: () => getDatabaseStatus,
|
|
44
|
-
getEngagementLeaderboard: () => getEngagementLeaderboard,
|
|
45
|
-
getFeatureFlags: () => getFeatureFlags,
|
|
46
|
-
getJwks: () => getJwks,
|
|
47
|
-
getKv: () => getKv,
|
|
48
|
-
getOAuthProviders: () => getOAuthProviders,
|
|
49
|
-
getOAuthProvidersWithInfo: () => getOAuthProvidersWithInfo,
|
|
50
|
-
getPlans: () => getPlans,
|
|
51
|
-
getReferralLeaderboard: () => getReferralLeaderboard,
|
|
52
|
-
getStreams: () => getStreams,
|
|
53
|
-
isAppId: () => isAppId,
|
|
54
|
-
isDevelopmentKey: () => isDevelopmentKey,
|
|
55
|
-
isDevelopmentRuntime: () => isDevelopmentRuntime,
|
|
56
|
-
isProductionKey: () => isProductionKey,
|
|
57
|
-
isSecretKey: () => isSecretKey,
|
|
58
|
-
resetJwksCache: () => resetJwksCache,
|
|
59
|
-
validateAndSanitizeAppId: () => validateAndSanitizeAppId,
|
|
60
|
-
validateAndSanitizeKey: () => validateAndSanitizeKey,
|
|
61
|
-
validateAndSanitizeSecretKey: () => validateAndSanitizeSecretKey,
|
|
62
|
-
validateAppId: () => validateAppId,
|
|
63
|
-
validateKey: () => validateKey,
|
|
64
|
-
validateSecretKey: () => validateSecretKey,
|
|
65
|
-
verifyAccessToken: () => verifyAccessToken,
|
|
66
|
-
verifyWebhook: () => verifyWebhook
|
|
67
|
-
});
|
|
68
|
-
module.exports = __toCommonJS(server_exports);
|
|
69
|
-
|
|
70
|
-
// ../../node_modules/jose/dist/webapi/lib/buffer_utils.js
|
|
71
|
-
var encoder = new TextEncoder();
|
|
72
|
-
var decoder = new TextDecoder();
|
|
73
|
-
var MAX_INT32 = 2 ** 32;
|
|
74
|
-
function concat(...buffers) {
|
|
75
|
-
const size = buffers.reduce((acc, { length }) => acc + length, 0);
|
|
76
|
-
const buf = new Uint8Array(size);
|
|
77
|
-
let i = 0;
|
|
78
|
-
for (const buffer of buffers) {
|
|
79
|
-
buf.set(buffer, i);
|
|
80
|
-
i += buffer.length;
|
|
81
|
-
}
|
|
82
|
-
return buf;
|
|
83
|
-
}
|
|
84
|
-
function encode(string) {
|
|
85
|
-
const bytes = new Uint8Array(string.length);
|
|
86
|
-
for (let i = 0; i < string.length; i++) {
|
|
87
|
-
const code = string.charCodeAt(i);
|
|
88
|
-
if (code > 127) {
|
|
89
|
-
throw new TypeError("non-ASCII string encountered in encode()");
|
|
90
|
-
}
|
|
91
|
-
bytes[i] = code;
|
|
92
|
-
}
|
|
93
|
-
return bytes;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
// ../../node_modules/jose/dist/webapi/lib/base64.js
|
|
97
|
-
function decodeBase64(encoded) {
|
|
98
|
-
if (Uint8Array.fromBase64) {
|
|
99
|
-
return Uint8Array.fromBase64(encoded);
|
|
100
|
-
}
|
|
101
|
-
const binary = atob(encoded);
|
|
102
|
-
const bytes = new Uint8Array(binary.length);
|
|
103
|
-
for (let i = 0; i < binary.length; i++) {
|
|
104
|
-
bytes[i] = binary.charCodeAt(i);
|
|
105
|
-
}
|
|
106
|
-
return bytes;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// ../../node_modules/jose/dist/webapi/util/base64url.js
|
|
110
|
-
function decode(input) {
|
|
111
|
-
if (Uint8Array.fromBase64) {
|
|
112
|
-
return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
|
|
113
|
-
alphabet: "base64url"
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
let encoded = input;
|
|
117
|
-
if (encoded instanceof Uint8Array) {
|
|
118
|
-
encoded = decoder.decode(encoded);
|
|
119
|
-
}
|
|
120
|
-
encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
|
|
121
|
-
try {
|
|
122
|
-
return decodeBase64(encoded);
|
|
123
|
-
} catch {
|
|
124
|
-
throw new TypeError("The input to be decoded is not correctly encoded.");
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
// ../../node_modules/jose/dist/webapi/util/errors.js
|
|
129
|
-
var JOSEError = class extends Error {
|
|
130
|
-
static code = "ERR_JOSE_GENERIC";
|
|
131
|
-
code = "ERR_JOSE_GENERIC";
|
|
132
|
-
constructor(message2, options) {
|
|
133
|
-
super(message2, options);
|
|
134
|
-
this.name = this.constructor.name;
|
|
135
|
-
Error.captureStackTrace?.(this, this.constructor);
|
|
136
|
-
}
|
|
137
|
-
};
|
|
138
|
-
var JWTClaimValidationFailed = class extends JOSEError {
|
|
139
|
-
static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
|
|
140
|
-
code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
|
|
141
|
-
claim;
|
|
142
|
-
reason;
|
|
143
|
-
payload;
|
|
144
|
-
constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
|
|
145
|
-
super(message2, { cause: { claim, reason, payload } });
|
|
146
|
-
this.claim = claim;
|
|
147
|
-
this.reason = reason;
|
|
148
|
-
this.payload = payload;
|
|
149
|
-
}
|
|
150
|
-
};
|
|
151
|
-
var JWTExpired = class extends JOSEError {
|
|
152
|
-
static code = "ERR_JWT_EXPIRED";
|
|
153
|
-
code = "ERR_JWT_EXPIRED";
|
|
154
|
-
claim;
|
|
155
|
-
reason;
|
|
156
|
-
payload;
|
|
157
|
-
constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
|
|
158
|
-
super(message2, { cause: { claim, reason, payload } });
|
|
159
|
-
this.claim = claim;
|
|
160
|
-
this.reason = reason;
|
|
161
|
-
this.payload = payload;
|
|
162
|
-
}
|
|
163
|
-
};
|
|
164
|
-
var JOSEAlgNotAllowed = class extends JOSEError {
|
|
165
|
-
static code = "ERR_JOSE_ALG_NOT_ALLOWED";
|
|
166
|
-
code = "ERR_JOSE_ALG_NOT_ALLOWED";
|
|
167
|
-
};
|
|
168
|
-
var JOSENotSupported = class extends JOSEError {
|
|
169
|
-
static code = "ERR_JOSE_NOT_SUPPORTED";
|
|
170
|
-
code = "ERR_JOSE_NOT_SUPPORTED";
|
|
171
|
-
};
|
|
172
|
-
var JWSInvalid = class extends JOSEError {
|
|
173
|
-
static code = "ERR_JWS_INVALID";
|
|
174
|
-
code = "ERR_JWS_INVALID";
|
|
175
|
-
};
|
|
176
|
-
var JWTInvalid = class extends JOSEError {
|
|
177
|
-
static code = "ERR_JWT_INVALID";
|
|
178
|
-
code = "ERR_JWT_INVALID";
|
|
179
|
-
};
|
|
180
|
-
var JWSSignatureVerificationFailed = class extends JOSEError {
|
|
181
|
-
static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
|
|
182
|
-
code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
|
|
183
|
-
constructor(message2 = "signature verification failed", options) {
|
|
184
|
-
super(message2, options);
|
|
185
|
-
}
|
|
186
|
-
};
|
|
187
|
-
|
|
188
|
-
// ../../node_modules/jose/dist/webapi/lib/crypto_key.js
|
|
189
|
-
var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
|
|
190
|
-
var isAlgorithm = (algorithm, name) => algorithm.name === name;
|
|
191
|
-
function getHashLength(hash) {
|
|
192
|
-
return parseInt(hash.name.slice(4), 10);
|
|
193
|
-
}
|
|
194
|
-
function getNamedCurve(alg) {
|
|
195
|
-
switch (alg) {
|
|
196
|
-
case "ES256":
|
|
197
|
-
return "P-256";
|
|
198
|
-
case "ES384":
|
|
199
|
-
return "P-384";
|
|
200
|
-
case "ES512":
|
|
201
|
-
return "P-521";
|
|
202
|
-
default:
|
|
203
|
-
throw new Error("unreachable");
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
function checkUsage(key, usage) {
|
|
207
|
-
if (usage && !key.usages.includes(usage)) {
|
|
208
|
-
throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
function checkSigCryptoKey(key, alg, usage) {
|
|
212
|
-
switch (alg) {
|
|
213
|
-
case "HS256":
|
|
214
|
-
case "HS384":
|
|
215
|
-
case "HS512": {
|
|
216
|
-
if (!isAlgorithm(key.algorithm, "HMAC"))
|
|
217
|
-
throw unusable("HMAC");
|
|
218
|
-
const expected = parseInt(alg.slice(2), 10);
|
|
219
|
-
const actual = getHashLength(key.algorithm.hash);
|
|
220
|
-
if (actual !== expected)
|
|
221
|
-
throw unusable(`SHA-${expected}`, "algorithm.hash");
|
|
222
|
-
break;
|
|
223
|
-
}
|
|
224
|
-
case "RS256":
|
|
225
|
-
case "RS384":
|
|
226
|
-
case "RS512": {
|
|
227
|
-
if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
|
|
228
|
-
throw unusable("RSASSA-PKCS1-v1_5");
|
|
229
|
-
const expected = parseInt(alg.slice(2), 10);
|
|
230
|
-
const actual = getHashLength(key.algorithm.hash);
|
|
231
|
-
if (actual !== expected)
|
|
232
|
-
throw unusable(`SHA-${expected}`, "algorithm.hash");
|
|
233
|
-
break;
|
|
234
|
-
}
|
|
235
|
-
case "PS256":
|
|
236
|
-
case "PS384":
|
|
237
|
-
case "PS512": {
|
|
238
|
-
if (!isAlgorithm(key.algorithm, "RSA-PSS"))
|
|
239
|
-
throw unusable("RSA-PSS");
|
|
240
|
-
const expected = parseInt(alg.slice(2), 10);
|
|
241
|
-
const actual = getHashLength(key.algorithm.hash);
|
|
242
|
-
if (actual !== expected)
|
|
243
|
-
throw unusable(`SHA-${expected}`, "algorithm.hash");
|
|
244
|
-
break;
|
|
245
|
-
}
|
|
246
|
-
case "Ed25519":
|
|
247
|
-
case "EdDSA": {
|
|
248
|
-
if (!isAlgorithm(key.algorithm, "Ed25519"))
|
|
249
|
-
throw unusable("Ed25519");
|
|
250
|
-
break;
|
|
251
|
-
}
|
|
252
|
-
case "ML-DSA-44":
|
|
253
|
-
case "ML-DSA-65":
|
|
254
|
-
case "ML-DSA-87": {
|
|
255
|
-
if (!isAlgorithm(key.algorithm, alg))
|
|
256
|
-
throw unusable(alg);
|
|
257
|
-
break;
|
|
258
|
-
}
|
|
259
|
-
case "ES256":
|
|
260
|
-
case "ES384":
|
|
261
|
-
case "ES512": {
|
|
262
|
-
if (!isAlgorithm(key.algorithm, "ECDSA"))
|
|
263
|
-
throw unusable("ECDSA");
|
|
264
|
-
const expected = getNamedCurve(alg);
|
|
265
|
-
const actual = key.algorithm.namedCurve;
|
|
266
|
-
if (actual !== expected)
|
|
267
|
-
throw unusable(expected, "algorithm.namedCurve");
|
|
268
|
-
break;
|
|
269
|
-
}
|
|
270
|
-
default:
|
|
271
|
-
throw new TypeError("CryptoKey does not support this operation");
|
|
272
|
-
}
|
|
273
|
-
checkUsage(key, usage);
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
// ../../node_modules/jose/dist/webapi/lib/invalid_key_input.js
|
|
277
|
-
function message(msg, actual, ...types) {
|
|
278
|
-
types = types.filter(Boolean);
|
|
279
|
-
if (types.length > 2) {
|
|
280
|
-
const last = types.pop();
|
|
281
|
-
msg += `one of type ${types.join(", ")}, or ${last}.`;
|
|
282
|
-
} else if (types.length === 2) {
|
|
283
|
-
msg += `one of type ${types[0]} or ${types[1]}.`;
|
|
284
|
-
} else {
|
|
285
|
-
msg += `of type ${types[0]}.`;
|
|
286
|
-
}
|
|
287
|
-
if (actual == null) {
|
|
288
|
-
msg += ` Received ${actual}`;
|
|
289
|
-
} else if (typeof actual === "function" && actual.name) {
|
|
290
|
-
msg += ` Received function ${actual.name}`;
|
|
291
|
-
} else if (typeof actual === "object" && actual != null) {
|
|
292
|
-
if (actual.constructor?.name) {
|
|
293
|
-
msg += ` Received an instance of ${actual.constructor.name}`;
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
return msg;
|
|
297
|
-
}
|
|
298
|
-
var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
|
|
299
|
-
var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
|
|
300
|
-
|
|
301
|
-
// ../../node_modules/jose/dist/webapi/lib/is_key_like.js
|
|
302
|
-
var isCryptoKey = (key) => {
|
|
303
|
-
if (key?.[Symbol.toStringTag] === "CryptoKey")
|
|
304
|
-
return true;
|
|
305
|
-
try {
|
|
306
|
-
return key instanceof CryptoKey;
|
|
307
|
-
} catch {
|
|
308
|
-
return false;
|
|
309
|
-
}
|
|
310
|
-
};
|
|
311
|
-
var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
|
|
312
|
-
var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
|
|
313
|
-
|
|
314
|
-
// ../../node_modules/jose/dist/webapi/lib/is_disjoint.js
|
|
315
|
-
function isDisjoint(...headers) {
|
|
316
|
-
const sources = headers.filter(Boolean);
|
|
317
|
-
if (sources.length === 0 || sources.length === 1) {
|
|
318
|
-
return true;
|
|
319
|
-
}
|
|
320
|
-
let acc;
|
|
321
|
-
for (const header of sources) {
|
|
322
|
-
const parameters = Object.keys(header);
|
|
323
|
-
if (!acc || acc.size === 0) {
|
|
324
|
-
acc = new Set(parameters);
|
|
325
|
-
continue;
|
|
326
|
-
}
|
|
327
|
-
for (const parameter of parameters) {
|
|
328
|
-
if (acc.has(parameter)) {
|
|
329
|
-
return false;
|
|
330
|
-
}
|
|
331
|
-
acc.add(parameter);
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
return true;
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
// ../../node_modules/jose/dist/webapi/lib/is_object.js
|
|
338
|
-
var isObjectLike = (value) => typeof value === "object" && value !== null;
|
|
339
|
-
function isObject(input) {
|
|
340
|
-
if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
|
|
341
|
-
return false;
|
|
342
|
-
}
|
|
343
|
-
if (Object.getPrototypeOf(input) === null) {
|
|
344
|
-
return true;
|
|
345
|
-
}
|
|
346
|
-
let proto = input;
|
|
347
|
-
while (Object.getPrototypeOf(proto) !== null) {
|
|
348
|
-
proto = Object.getPrototypeOf(proto);
|
|
349
|
-
}
|
|
350
|
-
return Object.getPrototypeOf(input) === proto;
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
// ../../node_modules/jose/dist/webapi/lib/check_key_length.js
|
|
354
|
-
function checkKeyLength(alg, key) {
|
|
355
|
-
if (alg.startsWith("RS") || alg.startsWith("PS")) {
|
|
356
|
-
const { modulusLength } = key.algorithm;
|
|
357
|
-
if (typeof modulusLength !== "number" || modulusLength < 2048) {
|
|
358
|
-
throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
// ../../node_modules/jose/dist/webapi/lib/jwk_to_key.js
|
|
364
|
-
function subtleMapping(jwk) {
|
|
365
|
-
let algorithm;
|
|
366
|
-
let keyUsages;
|
|
367
|
-
switch (jwk.kty) {
|
|
368
|
-
case "AKP": {
|
|
369
|
-
switch (jwk.alg) {
|
|
370
|
-
case "ML-DSA-44":
|
|
371
|
-
case "ML-DSA-65":
|
|
372
|
-
case "ML-DSA-87":
|
|
373
|
-
algorithm = { name: jwk.alg };
|
|
374
|
-
keyUsages = jwk.priv ? ["sign"] : ["verify"];
|
|
375
|
-
break;
|
|
376
|
-
default:
|
|
377
|
-
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
|
378
|
-
}
|
|
379
|
-
break;
|
|
380
|
-
}
|
|
381
|
-
case "RSA": {
|
|
382
|
-
switch (jwk.alg) {
|
|
383
|
-
case "PS256":
|
|
384
|
-
case "PS384":
|
|
385
|
-
case "PS512":
|
|
386
|
-
algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
|
|
387
|
-
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
388
|
-
break;
|
|
389
|
-
case "RS256":
|
|
390
|
-
case "RS384":
|
|
391
|
-
case "RS512":
|
|
392
|
-
algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` };
|
|
393
|
-
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
394
|
-
break;
|
|
395
|
-
case "RSA-OAEP":
|
|
396
|
-
case "RSA-OAEP-256":
|
|
397
|
-
case "RSA-OAEP-384":
|
|
398
|
-
case "RSA-OAEP-512":
|
|
399
|
-
algorithm = {
|
|
400
|
-
name: "RSA-OAEP",
|
|
401
|
-
hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
|
|
402
|
-
};
|
|
403
|
-
keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
|
|
404
|
-
break;
|
|
405
|
-
default:
|
|
406
|
-
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
|
407
|
-
}
|
|
408
|
-
break;
|
|
409
|
-
}
|
|
410
|
-
case "EC": {
|
|
411
|
-
switch (jwk.alg) {
|
|
412
|
-
case "ES256":
|
|
413
|
-
algorithm = { name: "ECDSA", namedCurve: "P-256" };
|
|
414
|
-
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
415
|
-
break;
|
|
416
|
-
case "ES384":
|
|
417
|
-
algorithm = { name: "ECDSA", namedCurve: "P-384" };
|
|
418
|
-
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
419
|
-
break;
|
|
420
|
-
case "ES512":
|
|
421
|
-
algorithm = { name: "ECDSA", namedCurve: "P-521" };
|
|
422
|
-
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
423
|
-
break;
|
|
424
|
-
case "ECDH-ES":
|
|
425
|
-
case "ECDH-ES+A128KW":
|
|
426
|
-
case "ECDH-ES+A192KW":
|
|
427
|
-
case "ECDH-ES+A256KW":
|
|
428
|
-
algorithm = { name: "ECDH", namedCurve: jwk.crv };
|
|
429
|
-
keyUsages = jwk.d ? ["deriveBits"] : [];
|
|
430
|
-
break;
|
|
431
|
-
default:
|
|
432
|
-
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
|
433
|
-
}
|
|
434
|
-
break;
|
|
435
|
-
}
|
|
436
|
-
case "OKP": {
|
|
437
|
-
switch (jwk.alg) {
|
|
438
|
-
case "Ed25519":
|
|
439
|
-
case "EdDSA":
|
|
440
|
-
algorithm = { name: "Ed25519" };
|
|
441
|
-
keyUsages = jwk.d ? ["sign"] : ["verify"];
|
|
442
|
-
break;
|
|
443
|
-
case "ECDH-ES":
|
|
444
|
-
case "ECDH-ES+A128KW":
|
|
445
|
-
case "ECDH-ES+A192KW":
|
|
446
|
-
case "ECDH-ES+A256KW":
|
|
447
|
-
algorithm = { name: jwk.crv };
|
|
448
|
-
keyUsages = jwk.d ? ["deriveBits"] : [];
|
|
449
|
-
break;
|
|
450
|
-
default:
|
|
451
|
-
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
|
452
|
-
}
|
|
453
|
-
break;
|
|
454
|
-
}
|
|
455
|
-
default:
|
|
456
|
-
throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
|
|
457
|
-
}
|
|
458
|
-
return { algorithm, keyUsages };
|
|
459
|
-
}
|
|
460
|
-
async function jwkToKey(jwk) {
|
|
461
|
-
if (!jwk.alg) {
|
|
462
|
-
throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
|
|
463
|
-
}
|
|
464
|
-
const { algorithm, keyUsages } = subtleMapping(jwk);
|
|
465
|
-
const keyData = { ...jwk };
|
|
466
|
-
if (keyData.kty !== "AKP") {
|
|
467
|
-
delete keyData.alg;
|
|
468
|
-
}
|
|
469
|
-
delete keyData.use;
|
|
470
|
-
return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
// ../../node_modules/jose/dist/webapi/key/import.js
|
|
474
|
-
async function importJWK(jwk, alg, options) {
|
|
475
|
-
if (!isObject(jwk)) {
|
|
476
|
-
throw new TypeError("JWK must be an object");
|
|
477
|
-
}
|
|
478
|
-
let ext;
|
|
479
|
-
alg ??= jwk.alg;
|
|
480
|
-
ext ??= options?.extractable ?? jwk.ext;
|
|
481
|
-
switch (jwk.kty) {
|
|
482
|
-
case "oct":
|
|
483
|
-
if (typeof jwk.k !== "string" || !jwk.k) {
|
|
484
|
-
throw new TypeError('missing "k" (Key Value) Parameter value');
|
|
485
|
-
}
|
|
486
|
-
return decode(jwk.k);
|
|
487
|
-
case "RSA":
|
|
488
|
-
if ("oth" in jwk && jwk.oth !== void 0) {
|
|
489
|
-
throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
|
|
490
|
-
}
|
|
491
|
-
return jwkToKey({ ...jwk, alg, ext });
|
|
492
|
-
case "AKP": {
|
|
493
|
-
if (typeof jwk.alg !== "string" || !jwk.alg) {
|
|
494
|
-
throw new TypeError('missing "alg" (Algorithm) Parameter value');
|
|
495
|
-
}
|
|
496
|
-
if (alg !== void 0 && alg !== jwk.alg) {
|
|
497
|
-
throw new TypeError("JWK alg and alg option value mismatch");
|
|
498
|
-
}
|
|
499
|
-
return jwkToKey({ ...jwk, ext });
|
|
500
|
-
}
|
|
501
|
-
case "EC":
|
|
502
|
-
case "OKP":
|
|
503
|
-
return jwkToKey({ ...jwk, alg, ext });
|
|
504
|
-
default:
|
|
505
|
-
throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
// ../../node_modules/jose/dist/webapi/lib/validate_crit.js
|
|
510
|
-
function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
|
|
511
|
-
if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) {
|
|
512
|
-
throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
|
|
513
|
-
}
|
|
514
|
-
if (!protectedHeader || protectedHeader.crit === void 0) {
|
|
515
|
-
return /* @__PURE__ */ new Set();
|
|
516
|
-
}
|
|
517
|
-
if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
|
|
518
|
-
throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
|
|
519
|
-
}
|
|
520
|
-
let recognized;
|
|
521
|
-
if (recognizedOption !== void 0) {
|
|
522
|
-
recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
|
|
523
|
-
} else {
|
|
524
|
-
recognized = recognizedDefault;
|
|
525
|
-
}
|
|
526
|
-
for (const parameter of protectedHeader.crit) {
|
|
527
|
-
if (!recognized.has(parameter)) {
|
|
528
|
-
throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
|
|
529
|
-
}
|
|
530
|
-
if (joseHeader[parameter] === void 0) {
|
|
531
|
-
throw new Err(`Extension Header Parameter "${parameter}" is missing`);
|
|
532
|
-
}
|
|
533
|
-
if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
|
|
534
|
-
throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
return new Set(protectedHeader.crit);
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
// ../../node_modules/jose/dist/webapi/lib/validate_algorithms.js
|
|
541
|
-
function validateAlgorithms(option, algorithms) {
|
|
542
|
-
if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
|
|
543
|
-
throw new TypeError(`"${option}" option must be an array of strings`);
|
|
544
|
-
}
|
|
545
|
-
if (!algorithms) {
|
|
546
|
-
return void 0;
|
|
547
|
-
}
|
|
548
|
-
return new Set(algorithms);
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
// ../../node_modules/jose/dist/webapi/lib/is_jwk.js
|
|
552
|
-
var isJWK = (key) => isObject(key) && typeof key.kty === "string";
|
|
553
|
-
var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
|
|
554
|
-
var isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
|
|
555
|
-
var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
|
|
556
|
-
|
|
557
|
-
// ../../node_modules/jose/dist/webapi/lib/normalize_key.js
|
|
558
|
-
var cache;
|
|
559
|
-
var handleJWK = async (key, jwk, alg, freeze = false) => {
|
|
560
|
-
cache ||= /* @__PURE__ */ new WeakMap();
|
|
561
|
-
let cached = cache.get(key);
|
|
562
|
-
if (cached?.[alg]) {
|
|
563
|
-
return cached[alg];
|
|
564
|
-
}
|
|
565
|
-
const cryptoKey = await jwkToKey({ ...jwk, alg });
|
|
566
|
-
if (freeze)
|
|
567
|
-
Object.freeze(key);
|
|
568
|
-
if (!cached) {
|
|
569
|
-
cache.set(key, { [alg]: cryptoKey });
|
|
570
|
-
} else {
|
|
571
|
-
cached[alg] = cryptoKey;
|
|
572
|
-
}
|
|
573
|
-
return cryptoKey;
|
|
574
|
-
};
|
|
575
|
-
var handleKeyObject = (keyObject, alg) => {
|
|
576
|
-
cache ||= /* @__PURE__ */ new WeakMap();
|
|
577
|
-
let cached = cache.get(keyObject);
|
|
578
|
-
if (cached?.[alg]) {
|
|
579
|
-
return cached[alg];
|
|
580
|
-
}
|
|
581
|
-
const isPublic = keyObject.type === "public";
|
|
582
|
-
const extractable = isPublic ? true : false;
|
|
583
|
-
let cryptoKey;
|
|
584
|
-
if (keyObject.asymmetricKeyType === "x25519") {
|
|
585
|
-
switch (alg) {
|
|
586
|
-
case "ECDH-ES":
|
|
587
|
-
case "ECDH-ES+A128KW":
|
|
588
|
-
case "ECDH-ES+A192KW":
|
|
589
|
-
case "ECDH-ES+A256KW":
|
|
590
|
-
break;
|
|
591
|
-
default:
|
|
592
|
-
throw new TypeError("given KeyObject instance cannot be used for this algorithm");
|
|
593
|
-
}
|
|
594
|
-
cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
|
|
595
|
-
}
|
|
596
|
-
if (keyObject.asymmetricKeyType === "ed25519") {
|
|
597
|
-
if (alg !== "EdDSA" && alg !== "Ed25519") {
|
|
598
|
-
throw new TypeError("given KeyObject instance cannot be used for this algorithm");
|
|
599
|
-
}
|
|
600
|
-
cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
|
|
601
|
-
isPublic ? "verify" : "sign"
|
|
602
|
-
]);
|
|
603
|
-
}
|
|
604
|
-
switch (keyObject.asymmetricKeyType) {
|
|
605
|
-
case "ml-dsa-44":
|
|
606
|
-
case "ml-dsa-65":
|
|
607
|
-
case "ml-dsa-87": {
|
|
608
|
-
if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {
|
|
609
|
-
throw new TypeError("given KeyObject instance cannot be used for this algorithm");
|
|
610
|
-
}
|
|
611
|
-
cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
|
|
612
|
-
isPublic ? "verify" : "sign"
|
|
613
|
-
]);
|
|
614
|
-
}
|
|
615
|
-
}
|
|
616
|
-
if (keyObject.asymmetricKeyType === "rsa") {
|
|
617
|
-
let hash;
|
|
618
|
-
switch (alg) {
|
|
619
|
-
case "RSA-OAEP":
|
|
620
|
-
hash = "SHA-1";
|
|
621
|
-
break;
|
|
622
|
-
case "RS256":
|
|
623
|
-
case "PS256":
|
|
624
|
-
case "RSA-OAEP-256":
|
|
625
|
-
hash = "SHA-256";
|
|
626
|
-
break;
|
|
627
|
-
case "RS384":
|
|
628
|
-
case "PS384":
|
|
629
|
-
case "RSA-OAEP-384":
|
|
630
|
-
hash = "SHA-384";
|
|
631
|
-
break;
|
|
632
|
-
case "RS512":
|
|
633
|
-
case "PS512":
|
|
634
|
-
case "RSA-OAEP-512":
|
|
635
|
-
hash = "SHA-512";
|
|
636
|
-
break;
|
|
637
|
-
default:
|
|
638
|
-
throw new TypeError("given KeyObject instance cannot be used for this algorithm");
|
|
639
|
-
}
|
|
640
|
-
if (alg.startsWith("RSA-OAEP")) {
|
|
641
|
-
return keyObject.toCryptoKey({
|
|
642
|
-
name: "RSA-OAEP",
|
|
643
|
-
hash
|
|
644
|
-
}, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
|
|
645
|
-
}
|
|
646
|
-
cryptoKey = keyObject.toCryptoKey({
|
|
647
|
-
name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
|
|
648
|
-
hash
|
|
649
|
-
}, extractable, [isPublic ? "verify" : "sign"]);
|
|
650
|
-
}
|
|
651
|
-
if (keyObject.asymmetricKeyType === "ec") {
|
|
652
|
-
const nist = /* @__PURE__ */ new Map([
|
|
653
|
-
["prime256v1", "P-256"],
|
|
654
|
-
["secp384r1", "P-384"],
|
|
655
|
-
["secp521r1", "P-521"]
|
|
656
|
-
]);
|
|
657
|
-
const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
|
|
658
|
-
if (!namedCurve) {
|
|
659
|
-
throw new TypeError("given KeyObject instance cannot be used for this algorithm");
|
|
660
|
-
}
|
|
661
|
-
if (alg === "ES256" && namedCurve === "P-256") {
|
|
662
|
-
cryptoKey = keyObject.toCryptoKey({
|
|
663
|
-
name: "ECDSA",
|
|
664
|
-
namedCurve
|
|
665
|
-
}, extractable, [isPublic ? "verify" : "sign"]);
|
|
666
|
-
}
|
|
667
|
-
if (alg === "ES384" && namedCurve === "P-384") {
|
|
668
|
-
cryptoKey = keyObject.toCryptoKey({
|
|
669
|
-
name: "ECDSA",
|
|
670
|
-
namedCurve
|
|
671
|
-
}, extractable, [isPublic ? "verify" : "sign"]);
|
|
672
|
-
}
|
|
673
|
-
if (alg === "ES512" && namedCurve === "P-521") {
|
|
674
|
-
cryptoKey = keyObject.toCryptoKey({
|
|
675
|
-
name: "ECDSA",
|
|
676
|
-
namedCurve
|
|
677
|
-
}, extractable, [isPublic ? "verify" : "sign"]);
|
|
678
|
-
}
|
|
679
|
-
if (alg.startsWith("ECDH-ES")) {
|
|
680
|
-
cryptoKey = keyObject.toCryptoKey({
|
|
681
|
-
name: "ECDH",
|
|
682
|
-
namedCurve
|
|
683
|
-
}, extractable, isPublic ? [] : ["deriveBits"]);
|
|
684
|
-
}
|
|
685
|
-
}
|
|
686
|
-
if (!cryptoKey) {
|
|
687
|
-
throw new TypeError("given KeyObject instance cannot be used for this algorithm");
|
|
688
|
-
}
|
|
689
|
-
if (!cached) {
|
|
690
|
-
cache.set(keyObject, { [alg]: cryptoKey });
|
|
691
|
-
} else {
|
|
692
|
-
cached[alg] = cryptoKey;
|
|
693
|
-
}
|
|
694
|
-
return cryptoKey;
|
|
695
|
-
};
|
|
696
|
-
async function normalizeKey(key, alg) {
|
|
697
|
-
if (key instanceof Uint8Array) {
|
|
698
|
-
return key;
|
|
699
|
-
}
|
|
700
|
-
if (isCryptoKey(key)) {
|
|
701
|
-
return key;
|
|
702
|
-
}
|
|
703
|
-
if (isKeyObject(key)) {
|
|
704
|
-
if (key.type === "secret") {
|
|
705
|
-
return key.export();
|
|
706
|
-
}
|
|
707
|
-
if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
|
|
708
|
-
try {
|
|
709
|
-
return handleKeyObject(key, alg);
|
|
710
|
-
} catch (err) {
|
|
711
|
-
if (err instanceof TypeError) {
|
|
712
|
-
throw err;
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
let jwk = key.export({ format: "jwk" });
|
|
717
|
-
return handleJWK(key, jwk, alg);
|
|
718
|
-
}
|
|
719
|
-
if (isJWK(key)) {
|
|
720
|
-
if (key.k) {
|
|
721
|
-
return decode(key.k);
|
|
722
|
-
}
|
|
723
|
-
return handleJWK(key, key, alg, true);
|
|
724
|
-
}
|
|
725
|
-
throw new Error("unreachable");
|
|
726
|
-
}
|
|
727
|
-
|
|
728
|
-
// ../../node_modules/jose/dist/webapi/lib/check_key_type.js
|
|
729
|
-
var tag = (key) => key?.[Symbol.toStringTag];
|
|
730
|
-
var jwkMatchesOp = (alg, key, usage) => {
|
|
731
|
-
if (key.use !== void 0) {
|
|
732
|
-
let expected;
|
|
733
|
-
switch (usage) {
|
|
734
|
-
case "sign":
|
|
735
|
-
case "verify":
|
|
736
|
-
expected = "sig";
|
|
737
|
-
break;
|
|
738
|
-
case "encrypt":
|
|
739
|
-
case "decrypt":
|
|
740
|
-
expected = "enc";
|
|
741
|
-
break;
|
|
742
|
-
}
|
|
743
|
-
if (key.use !== expected) {
|
|
744
|
-
throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
|
|
745
|
-
}
|
|
746
|
-
}
|
|
747
|
-
if (key.alg !== void 0 && key.alg !== alg) {
|
|
748
|
-
throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
|
|
749
|
-
}
|
|
750
|
-
if (Array.isArray(key.key_ops)) {
|
|
751
|
-
let expectedKeyOp;
|
|
752
|
-
switch (true) {
|
|
753
|
-
case (usage === "sign" || usage === "verify"):
|
|
754
|
-
case alg === "dir":
|
|
755
|
-
case alg.includes("CBC-HS"):
|
|
756
|
-
expectedKeyOp = usage;
|
|
757
|
-
break;
|
|
758
|
-
case alg.startsWith("PBES2"):
|
|
759
|
-
expectedKeyOp = "deriveBits";
|
|
760
|
-
break;
|
|
761
|
-
case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
|
|
762
|
-
if (!alg.includes("GCM") && alg.endsWith("KW")) {
|
|
763
|
-
expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
|
|
764
|
-
} else {
|
|
765
|
-
expectedKeyOp = usage;
|
|
766
|
-
}
|
|
767
|
-
break;
|
|
768
|
-
case (usage === "encrypt" && alg.startsWith("RSA")):
|
|
769
|
-
expectedKeyOp = "wrapKey";
|
|
770
|
-
break;
|
|
771
|
-
case usage === "decrypt":
|
|
772
|
-
expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
|
|
773
|
-
break;
|
|
774
|
-
}
|
|
775
|
-
if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {
|
|
776
|
-
throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
|
|
777
|
-
}
|
|
778
|
-
}
|
|
779
|
-
return true;
|
|
780
|
-
};
|
|
781
|
-
var symmetricTypeCheck = (alg, key, usage) => {
|
|
782
|
-
if (key instanceof Uint8Array)
|
|
783
|
-
return;
|
|
784
|
-
if (isJWK(key)) {
|
|
785
|
-
if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
|
|
786
|
-
return;
|
|
787
|
-
throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
|
|
788
|
-
}
|
|
789
|
-
if (!isKeyLike(key)) {
|
|
790
|
-
throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
|
|
791
|
-
}
|
|
792
|
-
if (key.type !== "secret") {
|
|
793
|
-
throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
|
|
794
|
-
}
|
|
795
|
-
};
|
|
796
|
-
var asymmetricTypeCheck = (alg, key, usage) => {
|
|
797
|
-
if (isJWK(key)) {
|
|
798
|
-
switch (usage) {
|
|
799
|
-
case "decrypt":
|
|
800
|
-
case "sign":
|
|
801
|
-
if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
|
|
802
|
-
return;
|
|
803
|
-
throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
|
|
804
|
-
case "encrypt":
|
|
805
|
-
case "verify":
|
|
806
|
-
if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
|
|
807
|
-
return;
|
|
808
|
-
throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
|
|
809
|
-
}
|
|
810
|
-
}
|
|
811
|
-
if (!isKeyLike(key)) {
|
|
812
|
-
throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
|
|
813
|
-
}
|
|
814
|
-
if (key.type === "secret") {
|
|
815
|
-
throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
|
|
816
|
-
}
|
|
817
|
-
if (key.type === "public") {
|
|
818
|
-
switch (usage) {
|
|
819
|
-
case "sign":
|
|
820
|
-
throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
|
|
821
|
-
case "decrypt":
|
|
822
|
-
throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
if (key.type === "private") {
|
|
826
|
-
switch (usage) {
|
|
827
|
-
case "verify":
|
|
828
|
-
throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
|
|
829
|
-
case "encrypt":
|
|
830
|
-
throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
|
|
831
|
-
}
|
|
832
|
-
}
|
|
833
|
-
};
|
|
834
|
-
function checkKeyType(alg, key, usage) {
|
|
835
|
-
switch (alg.substring(0, 2)) {
|
|
836
|
-
case "A1":
|
|
837
|
-
case "A2":
|
|
838
|
-
case "di":
|
|
839
|
-
case "HS":
|
|
840
|
-
case "PB":
|
|
841
|
-
symmetricTypeCheck(alg, key, usage);
|
|
842
|
-
break;
|
|
843
|
-
default:
|
|
844
|
-
asymmetricTypeCheck(alg, key, usage);
|
|
845
|
-
}
|
|
846
|
-
}
|
|
847
|
-
|
|
848
|
-
// ../../node_modules/jose/dist/webapi/lib/subtle_dsa.js
|
|
849
|
-
function subtleAlgorithm(alg, algorithm) {
|
|
850
|
-
const hash = `SHA-${alg.slice(-3)}`;
|
|
851
|
-
switch (alg) {
|
|
852
|
-
case "HS256":
|
|
853
|
-
case "HS384":
|
|
854
|
-
case "HS512":
|
|
855
|
-
return { hash, name: "HMAC" };
|
|
856
|
-
case "PS256":
|
|
857
|
-
case "PS384":
|
|
858
|
-
case "PS512":
|
|
859
|
-
return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
|
|
860
|
-
case "RS256":
|
|
861
|
-
case "RS384":
|
|
862
|
-
case "RS512":
|
|
863
|
-
return { hash, name: "RSASSA-PKCS1-v1_5" };
|
|
864
|
-
case "ES256":
|
|
865
|
-
case "ES384":
|
|
866
|
-
case "ES512":
|
|
867
|
-
return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
|
|
868
|
-
case "Ed25519":
|
|
869
|
-
case "EdDSA":
|
|
870
|
-
return { name: "Ed25519" };
|
|
871
|
-
case "ML-DSA-44":
|
|
872
|
-
case "ML-DSA-65":
|
|
873
|
-
case "ML-DSA-87":
|
|
874
|
-
return { name: alg };
|
|
875
|
-
default:
|
|
876
|
-
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
|
|
877
|
-
}
|
|
878
|
-
}
|
|
879
|
-
|
|
880
|
-
// ../../node_modules/jose/dist/webapi/lib/get_sign_verify_key.js
|
|
881
|
-
async function getSigKey(alg, key, usage) {
|
|
882
|
-
if (key instanceof Uint8Array) {
|
|
883
|
-
if (!alg.startsWith("HS")) {
|
|
884
|
-
throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
|
|
885
|
-
}
|
|
886
|
-
return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]);
|
|
887
|
-
}
|
|
888
|
-
checkSigCryptoKey(key, alg, usage);
|
|
889
|
-
return key;
|
|
890
|
-
}
|
|
891
|
-
|
|
892
|
-
// ../../node_modules/jose/dist/webapi/lib/verify.js
|
|
893
|
-
async function verify(alg, key, signature, data) {
|
|
894
|
-
const cryptoKey = await getSigKey(alg, key, "verify");
|
|
895
|
-
checkKeyLength(alg, cryptoKey);
|
|
896
|
-
const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
|
|
897
|
-
try {
|
|
898
|
-
return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
|
|
899
|
-
} catch {
|
|
900
|
-
return false;
|
|
901
|
-
}
|
|
902
|
-
}
|
|
903
|
-
|
|
904
|
-
// ../../node_modules/jose/dist/webapi/jws/flattened/verify.js
|
|
905
|
-
async function flattenedVerify(jws, key, options) {
|
|
906
|
-
if (!isObject(jws)) {
|
|
907
|
-
throw new JWSInvalid("Flattened JWS must be an object");
|
|
908
|
-
}
|
|
909
|
-
if (jws.protected === void 0 && jws.header === void 0) {
|
|
910
|
-
throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
|
|
911
|
-
}
|
|
912
|
-
if (jws.protected !== void 0 && typeof jws.protected !== "string") {
|
|
913
|
-
throw new JWSInvalid("JWS Protected Header incorrect type");
|
|
914
|
-
}
|
|
915
|
-
if (jws.payload === void 0) {
|
|
916
|
-
throw new JWSInvalid("JWS Payload missing");
|
|
917
|
-
}
|
|
918
|
-
if (typeof jws.signature !== "string") {
|
|
919
|
-
throw new JWSInvalid("JWS Signature missing or incorrect type");
|
|
920
|
-
}
|
|
921
|
-
if (jws.header !== void 0 && !isObject(jws.header)) {
|
|
922
|
-
throw new JWSInvalid("JWS Unprotected Header incorrect type");
|
|
923
|
-
}
|
|
924
|
-
let parsedProt = {};
|
|
925
|
-
if (jws.protected) {
|
|
926
|
-
try {
|
|
927
|
-
const protectedHeader = decode(jws.protected);
|
|
928
|
-
parsedProt = JSON.parse(decoder.decode(protectedHeader));
|
|
929
|
-
} catch {
|
|
930
|
-
throw new JWSInvalid("JWS Protected Header is invalid");
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
if (!isDisjoint(parsedProt, jws.header)) {
|
|
934
|
-
throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
|
|
935
|
-
}
|
|
936
|
-
const joseHeader = {
|
|
937
|
-
...parsedProt,
|
|
938
|
-
...jws.header
|
|
939
|
-
};
|
|
940
|
-
const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
|
|
941
|
-
let b64 = true;
|
|
942
|
-
if (extensions.has("b64")) {
|
|
943
|
-
b64 = parsedProt.b64;
|
|
944
|
-
if (typeof b64 !== "boolean") {
|
|
945
|
-
throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
|
|
946
|
-
}
|
|
947
|
-
}
|
|
948
|
-
const { alg } = joseHeader;
|
|
949
|
-
if (typeof alg !== "string" || !alg) {
|
|
950
|
-
throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
|
|
951
|
-
}
|
|
952
|
-
const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
|
|
953
|
-
if (algorithms && !algorithms.has(alg)) {
|
|
954
|
-
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
|
|
955
|
-
}
|
|
956
|
-
if (b64) {
|
|
957
|
-
if (typeof jws.payload !== "string") {
|
|
958
|
-
throw new JWSInvalid("JWS Payload must be a string");
|
|
959
|
-
}
|
|
960
|
-
} else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) {
|
|
961
|
-
throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
|
|
962
|
-
}
|
|
963
|
-
let resolvedKey = false;
|
|
964
|
-
if (typeof key === "function") {
|
|
965
|
-
key = await key(parsedProt, jws);
|
|
966
|
-
resolvedKey = true;
|
|
967
|
-
}
|
|
968
|
-
checkKeyType(alg, key, "verify");
|
|
969
|
-
const data = concat(jws.protected !== void 0 ? encode(jws.protected) : new Uint8Array(), encode("."), typeof jws.payload === "string" ? b64 ? encode(jws.payload) : encoder.encode(jws.payload) : jws.payload);
|
|
970
|
-
let signature;
|
|
971
|
-
try {
|
|
972
|
-
signature = decode(jws.signature);
|
|
973
|
-
} catch {
|
|
974
|
-
throw new JWSInvalid("Failed to base64url decode the signature");
|
|
975
|
-
}
|
|
976
|
-
const k = await normalizeKey(key, alg);
|
|
977
|
-
const verified = await verify(alg, k, signature, data);
|
|
978
|
-
if (!verified) {
|
|
979
|
-
throw new JWSSignatureVerificationFailed();
|
|
980
|
-
}
|
|
981
|
-
let payload;
|
|
982
|
-
if (b64) {
|
|
983
|
-
try {
|
|
984
|
-
payload = decode(jws.payload);
|
|
985
|
-
} catch {
|
|
986
|
-
throw new JWSInvalid("Failed to base64url decode the payload");
|
|
987
|
-
}
|
|
988
|
-
} else if (typeof jws.payload === "string") {
|
|
989
|
-
payload = encoder.encode(jws.payload);
|
|
990
|
-
} else {
|
|
991
|
-
payload = jws.payload;
|
|
992
|
-
}
|
|
993
|
-
const result = { payload };
|
|
994
|
-
if (jws.protected !== void 0) {
|
|
995
|
-
result.protectedHeader = parsedProt;
|
|
996
|
-
}
|
|
997
|
-
if (jws.header !== void 0) {
|
|
998
|
-
result.unprotectedHeader = jws.header;
|
|
999
|
-
}
|
|
1000
|
-
if (resolvedKey) {
|
|
1001
|
-
return { ...result, key: k };
|
|
1002
|
-
}
|
|
1003
|
-
return result;
|
|
1004
|
-
}
|
|
1005
|
-
|
|
1006
|
-
// ../../node_modules/jose/dist/webapi/jws/compact/verify.js
|
|
1007
|
-
async function compactVerify(jws, key, options) {
|
|
1008
|
-
if (jws instanceof Uint8Array) {
|
|
1009
|
-
jws = decoder.decode(jws);
|
|
1010
|
-
}
|
|
1011
|
-
if (typeof jws !== "string") {
|
|
1012
|
-
throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
|
|
1013
|
-
}
|
|
1014
|
-
const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
|
|
1015
|
-
if (length !== 3) {
|
|
1016
|
-
throw new JWSInvalid("Invalid Compact JWS");
|
|
1017
|
-
}
|
|
1018
|
-
const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
|
|
1019
|
-
const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
|
|
1020
|
-
if (typeof key === "function") {
|
|
1021
|
-
return { ...result, key: verified.key };
|
|
1022
|
-
}
|
|
1023
|
-
return result;
|
|
1024
|
-
}
|
|
1025
|
-
|
|
1026
|
-
// ../../node_modules/jose/dist/webapi/lib/jwt_claims_set.js
|
|
1027
|
-
var epoch = (date) => Math.floor(date.getTime() / 1e3);
|
|
1028
|
-
var minute = 60;
|
|
1029
|
-
var hour = minute * 60;
|
|
1030
|
-
var day = hour * 24;
|
|
1031
|
-
var week = day * 7;
|
|
1032
|
-
var year = day * 365.25;
|
|
1033
|
-
var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
|
|
1034
|
-
function secs(str) {
|
|
1035
|
-
const matched = REGEX.exec(str);
|
|
1036
|
-
if (!matched || matched[4] && matched[1]) {
|
|
1037
|
-
throw new TypeError("Invalid time period format");
|
|
1038
|
-
}
|
|
1039
|
-
const value = parseFloat(matched[2]);
|
|
1040
|
-
const unit = matched[3].toLowerCase();
|
|
1041
|
-
let numericDate;
|
|
1042
|
-
switch (unit) {
|
|
1043
|
-
case "sec":
|
|
1044
|
-
case "secs":
|
|
1045
|
-
case "second":
|
|
1046
|
-
case "seconds":
|
|
1047
|
-
case "s":
|
|
1048
|
-
numericDate = Math.round(value);
|
|
1049
|
-
break;
|
|
1050
|
-
case "minute":
|
|
1051
|
-
case "minutes":
|
|
1052
|
-
case "min":
|
|
1053
|
-
case "mins":
|
|
1054
|
-
case "m":
|
|
1055
|
-
numericDate = Math.round(value * minute);
|
|
1056
|
-
break;
|
|
1057
|
-
case "hour":
|
|
1058
|
-
case "hours":
|
|
1059
|
-
case "hr":
|
|
1060
|
-
case "hrs":
|
|
1061
|
-
case "h":
|
|
1062
|
-
numericDate = Math.round(value * hour);
|
|
1063
|
-
break;
|
|
1064
|
-
case "day":
|
|
1065
|
-
case "days":
|
|
1066
|
-
case "d":
|
|
1067
|
-
numericDate = Math.round(value * day);
|
|
1068
|
-
break;
|
|
1069
|
-
case "week":
|
|
1070
|
-
case "weeks":
|
|
1071
|
-
case "w":
|
|
1072
|
-
numericDate = Math.round(value * week);
|
|
1073
|
-
break;
|
|
1074
|
-
default:
|
|
1075
|
-
numericDate = Math.round(value * year);
|
|
1076
|
-
break;
|
|
1077
|
-
}
|
|
1078
|
-
if (matched[1] === "-" || matched[4] === "ago") {
|
|
1079
|
-
return -numericDate;
|
|
1080
|
-
}
|
|
1081
|
-
return numericDate;
|
|
1082
|
-
}
|
|
1083
|
-
var normalizeTyp = (value) => {
|
|
1084
|
-
if (value.includes("/")) {
|
|
1085
|
-
return value.toLowerCase();
|
|
1086
|
-
}
|
|
1087
|
-
return `application/${value.toLowerCase()}`;
|
|
1088
|
-
};
|
|
1089
|
-
var checkAudiencePresence = (audPayload, audOption) => {
|
|
1090
|
-
if (typeof audPayload === "string") {
|
|
1091
|
-
return audOption.includes(audPayload);
|
|
1092
|
-
}
|
|
1093
|
-
if (Array.isArray(audPayload)) {
|
|
1094
|
-
return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
|
|
1095
|
-
}
|
|
1096
|
-
return false;
|
|
1097
|
-
};
|
|
1098
|
-
function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
|
|
1099
|
-
let payload;
|
|
1100
|
-
try {
|
|
1101
|
-
payload = JSON.parse(decoder.decode(encodedPayload));
|
|
1102
|
-
} catch {
|
|
1103
|
-
}
|
|
1104
|
-
if (!isObject(payload)) {
|
|
1105
|
-
throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
|
|
1106
|
-
}
|
|
1107
|
-
const { typ } = options;
|
|
1108
|
-
if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
|
|
1109
|
-
throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed");
|
|
1110
|
-
}
|
|
1111
|
-
const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
|
|
1112
|
-
const presenceCheck = [...requiredClaims];
|
|
1113
|
-
if (maxTokenAge !== void 0)
|
|
1114
|
-
presenceCheck.push("iat");
|
|
1115
|
-
if (audience !== void 0)
|
|
1116
|
-
presenceCheck.push("aud");
|
|
1117
|
-
if (subject !== void 0)
|
|
1118
|
-
presenceCheck.push("sub");
|
|
1119
|
-
if (issuer !== void 0)
|
|
1120
|
-
presenceCheck.push("iss");
|
|
1121
|
-
for (const claim of new Set(presenceCheck.reverse())) {
|
|
1122
|
-
if (!(claim in payload)) {
|
|
1123
|
-
throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
|
|
1124
|
-
}
|
|
1125
|
-
}
|
|
1126
|
-
if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
|
|
1127
|
-
throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed");
|
|
1128
|
-
}
|
|
1129
|
-
if (subject && payload.sub !== subject) {
|
|
1130
|
-
throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed");
|
|
1131
|
-
}
|
|
1132
|
-
if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) {
|
|
1133
|
-
throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed");
|
|
1134
|
-
}
|
|
1135
|
-
let tolerance;
|
|
1136
|
-
switch (typeof options.clockTolerance) {
|
|
1137
|
-
case "string":
|
|
1138
|
-
tolerance = secs(options.clockTolerance);
|
|
1139
|
-
break;
|
|
1140
|
-
case "number":
|
|
1141
|
-
tolerance = options.clockTolerance;
|
|
1142
|
-
break;
|
|
1143
|
-
case "undefined":
|
|
1144
|
-
tolerance = 0;
|
|
1145
|
-
break;
|
|
1146
|
-
default:
|
|
1147
|
-
throw new TypeError("Invalid clockTolerance option type");
|
|
1148
|
-
}
|
|
1149
|
-
const { currentDate } = options;
|
|
1150
|
-
const now = epoch(currentDate || /* @__PURE__ */ new Date());
|
|
1151
|
-
if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") {
|
|
1152
|
-
throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid");
|
|
1153
|
-
}
|
|
1154
|
-
if (payload.nbf !== void 0) {
|
|
1155
|
-
if (typeof payload.nbf !== "number") {
|
|
1156
|
-
throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid");
|
|
1157
|
-
}
|
|
1158
|
-
if (payload.nbf > now + tolerance) {
|
|
1159
|
-
throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed");
|
|
1160
|
-
}
|
|
1161
|
-
}
|
|
1162
|
-
if (payload.exp !== void 0) {
|
|
1163
|
-
if (typeof payload.exp !== "number") {
|
|
1164
|
-
throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid");
|
|
1165
|
-
}
|
|
1166
|
-
if (payload.exp <= now - tolerance) {
|
|
1167
|
-
throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed");
|
|
1168
|
-
}
|
|
1169
|
-
}
|
|
1170
|
-
if (maxTokenAge) {
|
|
1171
|
-
const age = now - payload.iat;
|
|
1172
|
-
const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
|
|
1173
|
-
if (age - tolerance > max) {
|
|
1174
|
-
throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed");
|
|
1175
|
-
}
|
|
1176
|
-
if (age < 0 - tolerance) {
|
|
1177
|
-
throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed");
|
|
1178
|
-
}
|
|
1179
|
-
}
|
|
1180
|
-
return payload;
|
|
1181
|
-
}
|
|
1182
|
-
|
|
1183
|
-
// ../../node_modules/jose/dist/webapi/jwt/verify.js
|
|
1184
|
-
async function jwtVerify(jwt, key, options) {
|
|
1185
|
-
const verified = await compactVerify(jwt, key, options);
|
|
1186
|
-
if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) {
|
|
1187
|
-
throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
|
|
1188
|
-
}
|
|
1189
|
-
const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
|
|
1190
|
-
const result = { payload, protectedHeader: verified.protectedHeader };
|
|
1191
|
-
if (typeof key === "function") {
|
|
1192
|
-
return { ...result, key: verified.key };
|
|
1193
|
-
}
|
|
1194
|
-
return result;
|
|
1195
|
-
}
|
|
1196
|
-
|
|
1197
|
-
// src/constants.ts
|
|
1198
|
-
var ENV_SECRET_URL = "SYLPHX_SECRET_URL";
|
|
1199
|
-
function resolveSecretUrl(explicit) {
|
|
1200
|
-
return explicit || process.env[ENV_SECRET_URL];
|
|
1201
|
-
}
|
|
1202
|
-
var SDK_API_PATH = `/v1`;
|
|
1203
|
-
var DEFAULT_SDK_API_HOST = "api.sylphx.com";
|
|
1204
|
-
var SDK_VERSION = "0.5.0";
|
|
1205
|
-
var SDK_PLATFORM = typeof window !== "undefined" ? "browser" : typeof process !== "undefined" && process.versions?.node ? "node" : "unknown";
|
|
1206
|
-
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
1207
|
-
var SESSION_TOKEN_LIFETIME_SECONDS = 5 * 60;
|
|
1208
|
-
var SESSION_TOKEN_LIFETIME_MS = SESSION_TOKEN_LIFETIME_SECONDS * 1e3;
|
|
1209
|
-
var REFRESH_TOKEN_LIFETIME_SECONDS = 30 * 24 * 60 * 60;
|
|
1210
|
-
var FLAGS_CACHE_TTL_MS = 5 * 60 * 1e3;
|
|
1211
|
-
var FLAGS_STALE_WHILE_REVALIDATE_MS = 60 * 1e3;
|
|
1212
|
-
var MAX_RETRY_DELAY_MS = 3e4;
|
|
1213
|
-
var BASE_RETRY_DELAY_MS = 1e3;
|
|
1214
|
-
var MAX_RETRIES = 3;
|
|
1215
|
-
var ANALYTICS_SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
|
|
1216
|
-
var WEBHOOK_MAX_AGE_MS = 5 * 60 * 1e3;
|
|
1217
|
-
var WEBHOOK_CLOCK_SKEW_MS = 30 * 1e3;
|
|
1218
|
-
var PKCE_CODE_TTL_MS = 10 * 60 * 1e3;
|
|
1219
|
-
var JOBS_DLQ_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
1220
|
-
var SESSION_REPLAY_MAX_DURATION_MS = 60 * 60 * 1e3;
|
|
1221
|
-
var FLAGS_EXPOSURE_DEDUPE_WINDOW_MS = 60 * 60 * 1e3;
|
|
1222
|
-
var CLICK_ID_EXPIRY_MS = 90 * 24 * 60 * 60 * 1e3;
|
|
1223
|
-
var STALE_TIME_FREQUENT_MS = 60 * 1e3;
|
|
1224
|
-
var STALE_TIME_MODERATE_MS = 2 * 60 * 1e3;
|
|
1225
|
-
var STALE_TIME_STABLE_MS = 5 * 60 * 1e3;
|
|
1226
|
-
var STALE_TIME_STATS_MS = 30 * 1e3;
|
|
1227
|
-
var NEW_USER_THRESHOLD_MS = 60 * 1e3;
|
|
1228
|
-
var STORAGE_MULTIPART_THRESHOLD_BYTES = 5 * 1024 * 1024;
|
|
1229
|
-
var STORAGE_DEFAULT_MAX_SIZE_BYTES = 5 * 1024 * 1024;
|
|
1230
|
-
var STORAGE_AVATAR_MAX_SIZE_BYTES = 2 * 1024 * 1024;
|
|
1231
|
-
var STORAGE_LARGE_MAX_SIZE_BYTES = 10 * 1024 * 1024;
|
|
1232
|
-
var JWK_CACHE_TTL_MS = 60 * 60 * 1e3;
|
|
1233
|
-
var CIRCUIT_BREAKER_FAILURE_THRESHOLD = 5;
|
|
1234
|
-
var CIRCUIT_BREAKER_WINDOW_MS = 1e4;
|
|
1235
|
-
var CIRCUIT_BREAKER_OPEN_DURATION_MS = 3e4;
|
|
1236
|
-
var ETAG_CACHE_MAX_ENTRIES = 100;
|
|
1237
|
-
var ETAG_CACHE_TTL_MS = 5 * 60 * 1e3;
|
|
1238
|
-
|
|
1239
|
-
// src/errors.ts
|
|
1240
|
-
var ERROR_CODE_STATUS = {
|
|
1241
|
-
BAD_REQUEST: 400,
|
|
1242
|
-
UNAUTHORIZED: 401,
|
|
1243
|
-
FORBIDDEN: 403,
|
|
1244
|
-
NOT_FOUND: 404,
|
|
1245
|
-
CONFLICT: 409,
|
|
1246
|
-
PAYLOAD_TOO_LARGE: 413,
|
|
1247
|
-
UNPROCESSABLE_ENTITY: 422,
|
|
1248
|
-
TOO_MANY_REQUESTS: 429,
|
|
1249
|
-
QUOTA_EXCEEDED: 402,
|
|
1250
|
-
INTERNAL_SERVER_ERROR: 500,
|
|
1251
|
-
NOT_IMPLEMENTED: 501,
|
|
1252
|
-
BAD_GATEWAY: 502,
|
|
1253
|
-
SERVICE_UNAVAILABLE: 503,
|
|
1254
|
-
GATEWAY_TIMEOUT: 504,
|
|
1255
|
-
NETWORK_ERROR: 0,
|
|
1256
|
-
TIMEOUT: 0,
|
|
1257
|
-
ABORTED: 0,
|
|
1258
|
-
PARSE_ERROR: 0,
|
|
1259
|
-
UNKNOWN: 0
|
|
1260
|
-
};
|
|
1261
|
-
var RETRYABLE_CODES = /* @__PURE__ */ new Set([
|
|
1262
|
-
"NETWORK_ERROR",
|
|
1263
|
-
"TIMEOUT",
|
|
1264
|
-
"BAD_GATEWAY",
|
|
1265
|
-
"SERVICE_UNAVAILABLE",
|
|
1266
|
-
"GATEWAY_TIMEOUT",
|
|
1267
|
-
"TOO_MANY_REQUESTS",
|
|
1268
|
-
// With backoff
|
|
1269
|
-
"INTERNAL_SERVER_ERROR"
|
|
1270
|
-
// Sometimes transient
|
|
1271
|
-
]);
|
|
1272
|
-
var SylphxError = class _SylphxError extends Error {
|
|
1273
|
-
/** Error code for programmatic handling */
|
|
1274
|
-
code;
|
|
1275
|
-
/** HTTP status code */
|
|
1276
|
-
status;
|
|
1277
|
-
/** Additional context data */
|
|
1278
|
-
data;
|
|
1279
|
-
/** Whether this error is safe to retry */
|
|
1280
|
-
isRetryable;
|
|
1281
|
-
/** Retry-After value in seconds (for rate limiting) */
|
|
1282
|
-
retryAfter;
|
|
1283
|
-
/** Timestamp when error occurred */
|
|
1284
|
-
timestamp;
|
|
1285
|
-
constructor(message2, options = {}) {
|
|
1286
|
-
super(message2, { cause: options.cause });
|
|
1287
|
-
this.name = "SylphxError";
|
|
1288
|
-
this.code = options.code ?? "UNKNOWN";
|
|
1289
|
-
this.status = options.status ?? ERROR_CODE_STATUS[this.code];
|
|
1290
|
-
this.data = options.data;
|
|
1291
|
-
this.isRetryable = RETRYABLE_CODES.has(this.code);
|
|
1292
|
-
this.retryAfter = options.retryAfter;
|
|
1293
|
-
this.timestamp = /* @__PURE__ */ new Date();
|
|
1294
|
-
if (Error.captureStackTrace) {
|
|
1295
|
-
Error.captureStackTrace(this, _SylphxError);
|
|
1296
|
-
}
|
|
1297
|
-
}
|
|
1298
|
-
// ============================================================================
|
|
1299
|
-
// Static Type Guards (DX helpers)
|
|
1300
|
-
// ============================================================================
|
|
1301
|
-
/**
|
|
1302
|
-
* Check if error is a rate-limit error (429 Too Many Requests)
|
|
1303
|
-
*/
|
|
1304
|
-
static isRateLimited(err) {
|
|
1305
|
-
return err instanceof _SylphxError && err.code === "TOO_MANY_REQUESTS";
|
|
1306
|
-
}
|
|
1307
|
-
/**
|
|
1308
|
-
* Check if error is an account lockout error (too many failed login attempts).
|
|
1309
|
-
* When true, `error.data?.lockoutUntil` contains the ISO 8601 timestamp when the lockout expires.
|
|
1310
|
-
*/
|
|
1311
|
-
static isAccountLocked(err) {
|
|
1312
|
-
return err instanceof _SylphxError && err.code === "TOO_MANY_REQUESTS" && err.data?.code === "ACCOUNT_LOCKED";
|
|
1313
|
-
}
|
|
1314
|
-
/**
|
|
1315
|
-
* Check if error is a quota exceeded error (plan limit reached)
|
|
1316
|
-
*/
|
|
1317
|
-
static isQuotaExceeded(err) {
|
|
1318
|
-
return err instanceof _SylphxError && err.code === "QUOTA_EXCEEDED";
|
|
1319
|
-
}
|
|
1320
|
-
/**
|
|
1321
|
-
* Check if error is an authentication error (401 Unauthorized)
|
|
1322
|
-
*/
|
|
1323
|
-
static isUnauthorized(err) {
|
|
1324
|
-
return err instanceof _SylphxError && err.code === "UNAUTHORIZED";
|
|
1325
|
-
}
|
|
1326
|
-
/**
|
|
1327
|
-
* Check if error is a not-found error (404 Not Found)
|
|
1328
|
-
*/
|
|
1329
|
-
static isNotFound(err) {
|
|
1330
|
-
return err instanceof _SylphxError && err.code === "NOT_FOUND";
|
|
1331
|
-
}
|
|
1332
|
-
/**
|
|
1333
|
-
* Check if error is an authorization error (403 Forbidden)
|
|
1334
|
-
*/
|
|
1335
|
-
static isForbidden(err) {
|
|
1336
|
-
return err instanceof _SylphxError && err.code === "FORBIDDEN";
|
|
1337
|
-
}
|
|
1338
|
-
/**
|
|
1339
|
-
* Check if error is a validation error (422 Unprocessable Entity)
|
|
1340
|
-
*/
|
|
1341
|
-
static isValidationError(err) {
|
|
1342
|
-
return err instanceof _SylphxError && err.code === "UNPROCESSABLE_ENTITY";
|
|
1343
|
-
}
|
|
1344
|
-
/**
|
|
1345
|
-
* Check if error is a network error (no response received)
|
|
1346
|
-
*/
|
|
1347
|
-
static isNetworkError(err) {
|
|
1348
|
-
return err instanceof _SylphxError && err.code === "NETWORK_ERROR";
|
|
1349
|
-
}
|
|
1350
|
-
/**
|
|
1351
|
-
* Check if error is an upstream/gateway error (502/504)
|
|
1352
|
-
*/
|
|
1353
|
-
static isUpstreamError(err) {
|
|
1354
|
-
return err instanceof _SylphxError && (err.code === "BAD_GATEWAY" || err.code === "GATEWAY_TIMEOUT" || err.code === "SERVICE_UNAVAILABLE");
|
|
1355
|
-
}
|
|
1356
|
-
/**
|
|
1357
|
-
* Convert to JSON-serializable object
|
|
1358
|
-
*/
|
|
1359
|
-
toJSON() {
|
|
1360
|
-
return {
|
|
1361
|
-
name: this.name,
|
|
1362
|
-
message: this.message,
|
|
1363
|
-
code: this.code,
|
|
1364
|
-
status: this.status,
|
|
1365
|
-
data: this.data,
|
|
1366
|
-
isRetryable: this.isRetryable,
|
|
1367
|
-
retryAfter: this.retryAfter,
|
|
1368
|
-
timestamp: this.timestamp.toISOString()
|
|
1369
|
-
};
|
|
1370
|
-
}
|
|
1371
|
-
};
|
|
1372
|
-
var NetworkError = class extends SylphxError {
|
|
1373
|
-
constructor(message2 = "Network request failed", options) {
|
|
1374
|
-
super(message2, { ...options, code: "NETWORK_ERROR" });
|
|
1375
|
-
this.name = "NetworkError";
|
|
1376
|
-
}
|
|
1377
|
-
};
|
|
1378
|
-
var TimeoutError = class extends SylphxError {
|
|
1379
|
-
/** Timeout duration in milliseconds */
|
|
1380
|
-
timeout;
|
|
1381
|
-
constructor(timeout, options) {
|
|
1382
|
-
super(`Request timed out after ${timeout}ms`, {
|
|
1383
|
-
...options,
|
|
1384
|
-
code: "TIMEOUT"
|
|
1385
|
-
});
|
|
1386
|
-
this.name = "TimeoutError";
|
|
1387
|
-
this.timeout = timeout;
|
|
1388
|
-
}
|
|
1389
|
-
};
|
|
1390
|
-
var RateLimitError = class extends SylphxError {
|
|
1391
|
-
/** Maximum requests allowed in window */
|
|
1392
|
-
limit;
|
|
1393
|
-
/** Remaining requests in current window */
|
|
1394
|
-
remaining;
|
|
1395
|
-
/** Unix timestamp (seconds) when limit resets */
|
|
1396
|
-
resetAt;
|
|
1397
|
-
constructor(message2 = "Too many requests", options) {
|
|
1398
|
-
super(message2, { ...options, code: "TOO_MANY_REQUESTS" });
|
|
1399
|
-
this.name = "RateLimitError";
|
|
1400
|
-
this.limit = options?.limit;
|
|
1401
|
-
this.remaining = options?.remaining;
|
|
1402
|
-
this.resetAt = options?.resetAt;
|
|
1403
|
-
}
|
|
1404
|
-
/**
|
|
1405
|
-
* Get Date when rate limit resets
|
|
1406
|
-
*/
|
|
1407
|
-
getResetDate() {
|
|
1408
|
-
return this.resetAt ? new Date(this.resetAt * 1e3) : void 0;
|
|
1409
|
-
}
|
|
1410
|
-
/**
|
|
1411
|
-
* Get human-readable retry message
|
|
1412
|
-
*/
|
|
1413
|
-
getRetryMessage() {
|
|
1414
|
-
if (this.retryAfter) {
|
|
1415
|
-
return `Please retry after ${this.retryAfter} seconds`;
|
|
1416
|
-
}
|
|
1417
|
-
if (this.resetAt) {
|
|
1418
|
-
const seconds = Math.max(0, this.resetAt - Math.floor(Date.now() / 1e3));
|
|
1419
|
-
return `Rate limit resets in ${seconds} seconds`;
|
|
1420
|
-
}
|
|
1421
|
-
return "Please wait before retrying";
|
|
1422
|
-
}
|
|
1423
|
-
};
|
|
1424
|
-
function exponentialBackoff(attempt, baseDelay = BASE_RETRY_DELAY_MS, maxDelay = MAX_RETRY_DELAY_MS) {
|
|
1425
|
-
const exponentialDelay = baseDelay * 2 ** attempt;
|
|
1426
|
-
const cappedDelay = Math.min(exponentialDelay, maxDelay);
|
|
1427
|
-
const jitter = cappedDelay * 0.25 * (Math.random() * 2 - 1);
|
|
1428
|
-
return Math.round(cappedDelay + jitter);
|
|
1429
|
-
}
|
|
1430
|
-
|
|
1431
|
-
// src/key-validation.ts
|
|
1432
|
-
var PUBLIC_KEY_PATTERN = /^pk_(dev|stg|prod)_[a-z0-9]{12}_[a-f0-9]{32}$/;
|
|
1433
|
-
var APP_ID_PATTERN = /^(app|pk)_(dev|stg|prod|prev)_[a-z0-9_-]+$/;
|
|
1434
|
-
var SECRET_KEY_PATTERN = /^sk_(dev|stg|prod)_[a-z0-9_-]+$/;
|
|
1435
|
-
var ENV_PREFIX_MAP = {
|
|
1436
|
-
dev: "development",
|
|
1437
|
-
stg: "staging",
|
|
1438
|
-
prod: "production"
|
|
1439
|
-
};
|
|
1440
|
-
function detectKeyIssues(key) {
|
|
1441
|
-
const issues = [];
|
|
1442
|
-
if (key !== key.trim()) issues.push("whitespace");
|
|
1443
|
-
if (key.includes("\n")) issues.push("newline");
|
|
1444
|
-
if (key.includes("\r")) issues.push("carriage-return");
|
|
1445
|
-
if (key.includes(" ")) issues.push("space");
|
|
1446
|
-
if (key !== key.toLowerCase()) issues.push("uppercase-chars");
|
|
1447
|
-
return issues;
|
|
1448
|
-
}
|
|
1449
|
-
function createSanitizationWarning(keyType, issues, envVarName) {
|
|
1450
|
-
const keyTypeName = keyType === "appId" ? "App ID" : "Secret Key";
|
|
1451
|
-
return `[Sylphx] ${keyTypeName} contains ${issues.join(", ")}. This is commonly caused by Vercel CLI's 'env pull' command.
|
|
1452
|
-
|
|
1453
|
-
To fix permanently:
|
|
1454
|
-
1. Go to Vercel Dashboard \u2192 Your Project \u2192 Settings \u2192 Environment Variables
|
|
1455
|
-
2. Edit ${envVarName}
|
|
1456
|
-
3. Remove any trailing whitespace or newline characters
|
|
1457
|
-
4. Redeploy your application
|
|
1458
|
-
|
|
1459
|
-
The SDK will automatically sanitize the key, but fixing the source is recommended.`;
|
|
1460
|
-
}
|
|
1461
|
-
function createInvalidKeyError(keyType, key, envVarName) {
|
|
1462
|
-
const maskedKey = key.length > 20 ? `${key.slice(0, 20)}...` : key;
|
|
1463
|
-
const formatHint = keyType === "appId" ? "pk_(dev|stg|prod)_{ref}_{hex} or app_(dev|stg|prod)_[id]" : "sk_(dev|stg|prod)_{ref}_{hex}";
|
|
1464
|
-
const keyTypeName = keyType === "appId" ? "App ID" : "Secret Key";
|
|
1465
|
-
return `[Sylphx] Invalid ${keyTypeName} format.
|
|
1466
|
-
|
|
1467
|
-
Expected format: ${formatHint}
|
|
1468
|
-
Received: "${maskedKey}"
|
|
1469
|
-
|
|
1470
|
-
Please check your ${envVarName} environment variable.
|
|
1471
|
-
You can find your keys in the Sylphx Console \u2192 API Keys.
|
|
1472
|
-
|
|
1473
|
-
Common issues:
|
|
1474
|
-
\u2022 Key has uppercase characters (must be lowercase)
|
|
1475
|
-
\u2022 Key has wrong prefix (App ID: pk_ or app_, Secret Key: sk_)
|
|
1476
|
-
\u2022 Key has invalid environment (must be dev, stg, or prod)
|
|
1477
|
-
\u2022 Key was copied with extra whitespace`;
|
|
1478
|
-
}
|
|
1479
|
-
function extractEnvironment(key) {
|
|
1480
|
-
const match = key.match(/^(?:app|pk|sk)_(dev|stg|prod|prev)_/);
|
|
1481
|
-
if (!match) return void 0;
|
|
1482
|
-
return ENV_PREFIX_MAP[match[1]];
|
|
1483
|
-
}
|
|
1484
|
-
function validateKeyForType(key, keyType, pattern, envVarName) {
|
|
1485
|
-
const keyTypeName = keyType === "appId" ? "App ID" : "Secret Key";
|
|
1486
|
-
if (!key) {
|
|
1487
|
-
return {
|
|
1488
|
-
valid: false,
|
|
1489
|
-
sanitizedKey: "",
|
|
1490
|
-
error: `[Sylphx] ${keyTypeName} is required. Set ${envVarName} in your environment variables.`,
|
|
1491
|
-
issues: ["missing"]
|
|
1492
|
-
};
|
|
1493
|
-
}
|
|
1494
|
-
const issues = detectKeyIssues(key);
|
|
1495
|
-
if (pattern.test(key)) {
|
|
1496
|
-
return {
|
|
1497
|
-
valid: true,
|
|
1498
|
-
sanitizedKey: key,
|
|
1499
|
-
keyType,
|
|
1500
|
-
environment: extractEnvironment(key),
|
|
1501
|
-
issues: []
|
|
1502
|
-
};
|
|
1503
|
-
}
|
|
1504
|
-
const sanitized = key.trim().toLowerCase();
|
|
1505
|
-
if (pattern.test(sanitized)) {
|
|
1506
|
-
return {
|
|
1507
|
-
valid: true,
|
|
1508
|
-
sanitizedKey: sanitized,
|
|
1509
|
-
keyType,
|
|
1510
|
-
environment: extractEnvironment(sanitized),
|
|
1511
|
-
warning: createSanitizationWarning(keyType, issues, envVarName),
|
|
1512
|
-
issues
|
|
1513
|
-
};
|
|
1514
|
-
}
|
|
1515
|
-
return {
|
|
1516
|
-
valid: false,
|
|
1517
|
-
sanitizedKey: "",
|
|
1518
|
-
error: createInvalidKeyError(keyType, key, envVarName),
|
|
1519
|
-
issues: [...issues, "invalid-format"]
|
|
1520
|
-
};
|
|
1521
|
-
}
|
|
1522
|
-
function validatePublicKey(key) {
|
|
1523
|
-
return validateKeyForType(key, "publicKey", PUBLIC_KEY_PATTERN, "NEXT_PUBLIC_SYLPHX_KEY");
|
|
1524
|
-
}
|
|
1525
|
-
function validateAppId(key) {
|
|
1526
|
-
return validateKeyForType(key, "appId", APP_ID_PATTERN, "NEXT_PUBLIC_SYLPHX_APP_ID");
|
|
1527
|
-
}
|
|
1528
|
-
function validateAndSanitizeAppId(key) {
|
|
1529
|
-
const result = validateAppId(key);
|
|
1530
|
-
if (!result.valid) {
|
|
1531
|
-
throw new Error(result.error);
|
|
1532
|
-
}
|
|
1533
|
-
if (result.warning) {
|
|
1534
|
-
console.warn(result.warning);
|
|
1535
|
-
}
|
|
1536
|
-
return result.sanitizedKey;
|
|
1537
|
-
}
|
|
1538
|
-
function validateSecretKey(key) {
|
|
1539
|
-
return validateKeyForType(key, "secret", SECRET_KEY_PATTERN, "SYLPHX_SECRET_KEY");
|
|
1540
|
-
}
|
|
1541
|
-
function validateAndSanitizeSecretKey(key) {
|
|
1542
|
-
const result = validateSecretKey(key);
|
|
1543
|
-
if (!result.valid) {
|
|
1544
|
-
throw new Error(result.error);
|
|
1545
|
-
}
|
|
1546
|
-
if (result.warning) {
|
|
1547
|
-
console.warn(result.warning);
|
|
1548
|
-
}
|
|
1549
|
-
return result.sanitizedKey;
|
|
1550
|
-
}
|
|
1551
|
-
function detectEnvironment(key) {
|
|
1552
|
-
const sanitized = key.trim().toLowerCase();
|
|
1553
|
-
if (sanitized.startsWith("pk_")) {
|
|
1554
|
-
const result = validatePublicKey(sanitized);
|
|
1555
|
-
if (!result.valid) throw new Error(result.error);
|
|
1556
|
-
return result.environment;
|
|
1557
|
-
}
|
|
1558
|
-
if (sanitized.startsWith("sk_")) {
|
|
1559
|
-
const result = validateSecretKey(sanitized);
|
|
1560
|
-
if (!result.valid) throw new Error(result.error);
|
|
1561
|
-
return result.environment;
|
|
1562
|
-
}
|
|
1563
|
-
if (sanitized.startsWith("app_")) {
|
|
1564
|
-
const result = validateAppId(sanitized);
|
|
1565
|
-
if (!result.valid) throw new Error(result.error);
|
|
1566
|
-
return result.environment;
|
|
1567
|
-
}
|
|
1568
|
-
throw new Error(
|
|
1569
|
-
`[Sylphx] Invalid key format. Key must start with 'pk_' (publishable), 'sk_' (secret), or 'app_' (legacy App ID).`
|
|
1570
|
-
);
|
|
1571
|
-
}
|
|
1572
|
-
function isDevelopmentKey(key) {
|
|
1573
|
-
return detectEnvironment(key) === "development";
|
|
1574
|
-
}
|
|
1575
|
-
function isProductionKey(key) {
|
|
1576
|
-
return detectEnvironment(key) === "production";
|
|
1577
|
-
}
|
|
1578
|
-
function getCookieNamespace(secretKey) {
|
|
1579
|
-
const env = detectEnvironment(secretKey);
|
|
1580
|
-
const shortEnv = env === "development" ? "dev" : env === "staging" ? "stg" : "prod";
|
|
1581
|
-
return `sylphx_${shortEnv}`;
|
|
1582
|
-
}
|
|
1583
|
-
function detectKeyType(key) {
|
|
1584
|
-
const sanitized = key.trim().toLowerCase();
|
|
1585
|
-
if (sanitized.startsWith("pk_")) return "publicKey";
|
|
1586
|
-
if (sanitized.startsWith("app_")) return "appId";
|
|
1587
|
-
if (sanitized.startsWith("sk_")) return "secret";
|
|
1588
|
-
return null;
|
|
1589
|
-
}
|
|
1590
|
-
function isAppId(key) {
|
|
1591
|
-
return detectKeyType(key) === "appId";
|
|
1592
|
-
}
|
|
1593
|
-
function isSecretKey(key) {
|
|
1594
|
-
return detectKeyType(key) === "secret";
|
|
1595
|
-
}
|
|
1596
|
-
function validateKey(key) {
|
|
1597
|
-
const keyType = key ? detectKeyType(key) : null;
|
|
1598
|
-
if (keyType === "publicKey") {
|
|
1599
|
-
return validatePublicKey(key);
|
|
1600
|
-
}
|
|
1601
|
-
if (keyType === "appId") {
|
|
1602
|
-
return validateAppId(key);
|
|
1603
|
-
}
|
|
1604
|
-
if (keyType === "secret") {
|
|
1605
|
-
return validateSecretKey(key);
|
|
1606
|
-
}
|
|
1607
|
-
return {
|
|
1608
|
-
valid: false,
|
|
1609
|
-
sanitizedKey: "",
|
|
1610
|
-
error: key ? `Invalid key format. Keys must start with 'pk_' (publishable), 'app_' (legacy), or 'sk_' (secret), followed by environment (dev/stg/prod). Got: ${key.slice(0, 20)}...` : "API key is required but was not provided.",
|
|
1611
|
-
issues: key ? ["invalid_format"] : ["missing"]
|
|
1612
|
-
};
|
|
1613
|
-
}
|
|
1614
|
-
function validateAndSanitizeKey(key) {
|
|
1615
|
-
const result = validateKey(key);
|
|
1616
|
-
if (!result.valid) {
|
|
1617
|
-
throw new Error(result.error);
|
|
1618
|
-
}
|
|
1619
|
-
if (result.warning) {
|
|
1620
|
-
console.warn(`[Sylphx] ${result.warning}`);
|
|
1621
|
-
}
|
|
1622
|
-
return result.sanitizedKey;
|
|
1623
|
-
}
|
|
1624
|
-
function isDevelopmentRuntime() {
|
|
1625
|
-
if (typeof process !== "undefined" && process.env) {
|
|
1626
|
-
return process.env.NODE_ENV === "development";
|
|
1627
|
-
}
|
|
1628
|
-
if (typeof window !== "undefined") {
|
|
1629
|
-
return window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1";
|
|
1630
|
-
}
|
|
1631
|
-
return false;
|
|
1632
|
-
}
|
|
1633
|
-
|
|
1634
|
-
// src/rest-client.ts
|
|
1635
|
-
async function runPipeline(middlewares, initial) {
|
|
1636
|
-
let request = initial;
|
|
1637
|
-
for (const mw of middlewares) {
|
|
1638
|
-
if (mw.onRequest) {
|
|
1639
|
-
const next = await mw.onRequest({ request });
|
|
1640
|
-
if (next) request = next;
|
|
1641
|
-
}
|
|
1642
|
-
}
|
|
1643
|
-
let response = await fetch(request);
|
|
1644
|
-
for (const mw of middlewares) {
|
|
1645
|
-
if (mw.onResponse) {
|
|
1646
|
-
const next = await mw.onResponse({ request, response });
|
|
1647
|
-
if (next) response = next;
|
|
1648
|
-
}
|
|
1649
|
-
}
|
|
1650
|
-
return response;
|
|
1651
|
-
}
|
|
1652
|
-
function buildUrl(baseUrl, path, params) {
|
|
1653
|
-
const url = `${baseUrl}${path}`;
|
|
1654
|
-
if (!params) return url;
|
|
1655
|
-
const entries = Object.entries(params).filter(([, v]) => v !== void 0);
|
|
1656
|
-
if (entries.length === 0) return url;
|
|
1657
|
-
const search = new URLSearchParams(
|
|
1658
|
-
entries.map(([k, v]) => [k, String(v)])
|
|
1659
|
-
).toString();
|
|
1660
|
-
return `${url}?${search}`;
|
|
1661
|
-
}
|
|
1662
|
-
function interpolatePath(path, pathParams) {
|
|
1663
|
-
if (!pathParams) return path;
|
|
1664
|
-
return path.replace(/\{(\w+)\}/g, (_match, key) => {
|
|
1665
|
-
const value = pathParams[key];
|
|
1666
|
-
if (value === void 0) return `{${key}}`;
|
|
1667
|
-
return encodeURIComponent(value);
|
|
1668
|
-
});
|
|
1669
|
-
}
|
|
1670
|
-
async function executeRequest(method, baseUrl, path, options, baseHeaders, middlewares) {
|
|
1671
|
-
const finalPath = interpolatePath(path, options?.params?.path);
|
|
1672
|
-
const url = buildUrl(baseUrl, finalPath, options?.params?.query);
|
|
1673
|
-
const headers = { ...baseHeaders, ...options?.headers };
|
|
1674
|
-
const init = { method, headers };
|
|
1675
|
-
if (options?.body !== void 0) {
|
|
1676
|
-
init.body = typeof options.body === "string" ? options.body : JSON.stringify(options.body);
|
|
1677
|
-
if (!headers["Content-Type"] && !headers["content-type"]) {
|
|
1678
|
-
headers["Content-Type"] = "application/json";
|
|
1679
|
-
}
|
|
1680
|
-
}
|
|
1681
|
-
const request = new Request(url, init);
|
|
1682
|
-
const response = await runPipeline(middlewares, request);
|
|
1683
|
-
const contentType = response.headers.get("content-type") ?? "";
|
|
1684
|
-
let parsed;
|
|
1685
|
-
if (contentType.includes("json")) {
|
|
1686
|
-
try {
|
|
1687
|
-
parsed = await response.clone().json();
|
|
1688
|
-
} catch {
|
|
1689
|
-
parsed = void 0;
|
|
1690
|
-
}
|
|
1691
|
-
} else if (response.status !== 204 && response.status !== 205) {
|
|
1692
|
-
try {
|
|
1693
|
-
const text = await response.clone().text();
|
|
1694
|
-
parsed = text === "" ? void 0 : text;
|
|
1695
|
-
} catch {
|
|
1696
|
-
parsed = void 0;
|
|
1697
|
-
}
|
|
1698
|
-
}
|
|
1699
|
-
if (response.ok) {
|
|
1700
|
-
return { data: parsed, response };
|
|
1701
|
-
}
|
|
1702
|
-
return { error: parsed, response };
|
|
1703
|
-
}
|
|
1704
|
-
function buildClient(baseUrl, baseHeaders) {
|
|
1705
|
-
const middlewares = [];
|
|
1706
|
-
const dispatch = (method) => (path, options) => executeRequest(method, baseUrl, path, options, baseHeaders, middlewares);
|
|
1707
|
-
const client = {
|
|
1708
|
-
GET: dispatch("GET"),
|
|
1709
|
-
POST: dispatch("POST"),
|
|
1710
|
-
PUT: dispatch("PUT"),
|
|
1711
|
-
PATCH: dispatch("PATCH"),
|
|
1712
|
-
DELETE: dispatch("DELETE"),
|
|
1713
|
-
HEAD: dispatch("HEAD"),
|
|
1714
|
-
OPTIONS: dispatch("OPTIONS"),
|
|
1715
|
-
use(...mws) {
|
|
1716
|
-
middlewares.push(...mws);
|
|
1717
|
-
}
|
|
1718
|
-
};
|
|
1719
|
-
return { client, middlewares };
|
|
1720
|
-
}
|
|
1721
|
-
function createAuthMiddleware(config) {
|
|
1722
|
-
return {
|
|
1723
|
-
async onRequest({ request }) {
|
|
1724
|
-
request.headers.set("X-SDK-Version", SDK_VERSION);
|
|
1725
|
-
request.headers.set("X-SDK-Platform", SDK_PLATFORM);
|
|
1726
|
-
if (config.secretKey) {
|
|
1727
|
-
request.headers.set("x-app-secret", config.secretKey);
|
|
1728
|
-
}
|
|
1729
|
-
const token = config.getAccessToken?.();
|
|
1730
|
-
if (token) {
|
|
1731
|
-
request.headers.set("Authorization", `Bearer ${token}`);
|
|
1732
|
-
}
|
|
1733
|
-
return request;
|
|
1734
|
-
}
|
|
1735
|
-
};
|
|
1736
|
-
}
|
|
1737
|
-
function isRetryableStatus(status) {
|
|
1738
|
-
return status >= 500 || status === 429;
|
|
1739
|
-
}
|
|
1740
|
-
var inFlightRequests = /* @__PURE__ */ new Map();
|
|
1741
|
-
async function getRequestKey(request) {
|
|
1742
|
-
const body = request.body ? await request.clone().text() : "";
|
|
1743
|
-
return `${request.method}:${request.url}:${body}`;
|
|
1744
|
-
}
|
|
1745
|
-
function createDeduplicationMiddleware(config = {}) {
|
|
1746
|
-
const { enabled = true, methods = ["GET"] } = config;
|
|
1747
|
-
if (!enabled) {
|
|
1748
|
-
return {
|
|
1749
|
-
async onRequest({ request }) {
|
|
1750
|
-
return request;
|
|
1751
|
-
}
|
|
1752
|
-
};
|
|
1753
|
-
}
|
|
1754
|
-
return {
|
|
1755
|
-
async onRequest({ request }) {
|
|
1756
|
-
if (!methods.includes(request.method)) {
|
|
1757
|
-
return request;
|
|
1758
|
-
}
|
|
1759
|
-
const key = await getRequestKey(request);
|
|
1760
|
-
const existing = inFlightRequests.get(key);
|
|
1761
|
-
if (existing) {
|
|
1762
|
-
const deduped = request.clone();
|
|
1763
|
-
deduped._dedupKey = key;
|
|
1764
|
-
return deduped;
|
|
1765
|
-
}
|
|
1766
|
-
;
|
|
1767
|
-
request._dedupKey = key;
|
|
1768
|
-
return request;
|
|
1769
|
-
},
|
|
1770
|
-
async onResponse({ request, response }) {
|
|
1771
|
-
const key = request._dedupKey;
|
|
1772
|
-
if (!key) return response;
|
|
1773
|
-
const existing = inFlightRequests.get(key);
|
|
1774
|
-
if (existing && inFlightRequests.get(key) !== void 0) {
|
|
1775
|
-
const cachedResponse = await existing;
|
|
1776
|
-
return cachedResponse.clone();
|
|
1777
|
-
}
|
|
1778
|
-
const responsePromise = Promise.resolve(response.clone());
|
|
1779
|
-
inFlightRequests.set(key, responsePromise);
|
|
1780
|
-
responsePromise.finally(() => {
|
|
1781
|
-
setTimeout(() => inFlightRequests.delete(key), 100);
|
|
1782
|
-
});
|
|
1783
|
-
return response;
|
|
1784
|
-
}
|
|
1785
|
-
};
|
|
1786
|
-
}
|
|
1787
|
-
var CircuitBreakerOpenError = class extends Error {
|
|
1788
|
-
remainingMs;
|
|
1789
|
-
constructor(remainingMs) {
|
|
1790
|
-
super(`Circuit breaker is open. Retry after ${Math.ceil(remainingMs / 1e3)}s`);
|
|
1791
|
-
this.name = "CircuitBreakerOpenError";
|
|
1792
|
-
this.remainingMs = remainingMs;
|
|
1793
|
-
}
|
|
1794
|
-
};
|
|
1795
|
-
function createCircuitBreakerInstance(config = {}) {
|
|
1796
|
-
return {
|
|
1797
|
-
state: "CLOSED",
|
|
1798
|
-
failures: [],
|
|
1799
|
-
openedAt: null,
|
|
1800
|
-
config: {
|
|
1801
|
-
enabled: config.enabled ?? true,
|
|
1802
|
-
failureThreshold: config.failureThreshold ?? CIRCUIT_BREAKER_FAILURE_THRESHOLD,
|
|
1803
|
-
windowMs: config.windowMs ?? CIRCUIT_BREAKER_WINDOW_MS,
|
|
1804
|
-
openDurationMs: config.openDurationMs ?? CIRCUIT_BREAKER_OPEN_DURATION_MS,
|
|
1805
|
-
isFailure: config.isFailure ?? ((status) => status >= 500 || status === 429)
|
|
1806
|
-
}
|
|
1807
|
-
};
|
|
1808
|
-
}
|
|
1809
|
-
function recordFailure(cb) {
|
|
1810
|
-
const now = Date.now();
|
|
1811
|
-
cb.failures = cb.failures.filter((t) => now - t < cb.config.windowMs);
|
|
1812
|
-
cb.failures.push(now);
|
|
1813
|
-
if (cb.failures.length >= cb.config.failureThreshold) {
|
|
1814
|
-
cb.state = "OPEN";
|
|
1815
|
-
cb.openedAt = now;
|
|
1816
|
-
}
|
|
1817
|
-
}
|
|
1818
|
-
function recordSuccess(cb) {
|
|
1819
|
-
if (cb.state === "HALF_OPEN") {
|
|
1820
|
-
cb.state = "CLOSED";
|
|
1821
|
-
cb.failures = [];
|
|
1822
|
-
cb.openedAt = null;
|
|
1823
|
-
}
|
|
1824
|
-
}
|
|
1825
|
-
function shouldAllowRequest(cb) {
|
|
1826
|
-
const now = Date.now();
|
|
1827
|
-
switch (cb.state) {
|
|
1828
|
-
case "CLOSED":
|
|
1829
|
-
return { allowed: true };
|
|
1830
|
-
case "OPEN": {
|
|
1831
|
-
const elapsed = now - (cb.openedAt ?? now);
|
|
1832
|
-
if (elapsed >= cb.config.openDurationMs) {
|
|
1833
|
-
cb.state = "HALF_OPEN";
|
|
1834
|
-
return { allowed: true };
|
|
1835
|
-
}
|
|
1836
|
-
return {
|
|
1837
|
-
allowed: false,
|
|
1838
|
-
remainingMs: cb.config.openDurationMs - elapsed
|
|
1839
|
-
};
|
|
1840
|
-
}
|
|
1841
|
-
case "HALF_OPEN":
|
|
1842
|
-
return { allowed: true };
|
|
1843
|
-
default:
|
|
1844
|
-
return { allowed: true };
|
|
1845
|
-
}
|
|
1846
|
-
}
|
|
1847
|
-
function createCircuitBreakerMiddleware(config) {
|
|
1848
|
-
if (config === false) {
|
|
1849
|
-
return {
|
|
1850
|
-
async onRequest({ request }) {
|
|
1851
|
-
return request;
|
|
1852
|
-
}
|
|
1853
|
-
};
|
|
1854
|
-
}
|
|
1855
|
-
const cb = createCircuitBreakerInstance(config ?? {});
|
|
1856
|
-
_lastCircuitBreaker = cb;
|
|
1857
|
-
return {
|
|
1858
|
-
async onRequest({ request }) {
|
|
1859
|
-
if (!cb.config.enabled) {
|
|
1860
|
-
return request;
|
|
1861
|
-
}
|
|
1862
|
-
const check = shouldAllowRequest(cb);
|
|
1863
|
-
if (!check.allowed) {
|
|
1864
|
-
throw new CircuitBreakerOpenError(check.remainingMs);
|
|
1865
|
-
}
|
|
1866
|
-
return request;
|
|
1867
|
-
},
|
|
1868
|
-
async onResponse({ response }) {
|
|
1869
|
-
if (!cb.config.enabled) {
|
|
1870
|
-
return response;
|
|
1871
|
-
}
|
|
1872
|
-
if (cb.config.isFailure(response.status)) {
|
|
1873
|
-
recordFailure(cb);
|
|
1874
|
-
} else {
|
|
1875
|
-
recordSuccess(cb);
|
|
1876
|
-
}
|
|
1877
|
-
return response;
|
|
1878
|
-
}
|
|
1879
|
-
};
|
|
1880
|
-
}
|
|
1881
|
-
var _lastCircuitBreaker = null;
|
|
1882
|
-
var etagCache = /* @__PURE__ */ new Map();
|
|
1883
|
-
function getETagCacheKey(request) {
|
|
1884
|
-
return `${request.method}:${request.url}`;
|
|
1885
|
-
}
|
|
1886
|
-
function evictOldEntries(maxEntries, ttlMs) {
|
|
1887
|
-
const now = Date.now();
|
|
1888
|
-
for (const [key, entry] of etagCache) {
|
|
1889
|
-
if (now - entry.timestamp > ttlMs) {
|
|
1890
|
-
etagCache.delete(key);
|
|
1891
|
-
}
|
|
1892
|
-
}
|
|
1893
|
-
if (etagCache.size > maxEntries) {
|
|
1894
|
-
const entries = Array.from(etagCache.entries());
|
|
1895
|
-
entries.sort((a, b) => a[1].timestamp - b[1].timestamp);
|
|
1896
|
-
const toRemove = entries.slice(0, entries.length - maxEntries);
|
|
1897
|
-
for (const [key] of toRemove) {
|
|
1898
|
-
etagCache.delete(key);
|
|
1899
|
-
}
|
|
1900
|
-
}
|
|
1901
|
-
}
|
|
1902
|
-
function createETagMiddleware(config) {
|
|
1903
|
-
if (config === false) {
|
|
1904
|
-
return {
|
|
1905
|
-
async onRequest({ request }) {
|
|
1906
|
-
return request;
|
|
1907
|
-
}
|
|
1908
|
-
};
|
|
1909
|
-
}
|
|
1910
|
-
const {
|
|
1911
|
-
enabled = true,
|
|
1912
|
-
maxEntries = ETAG_CACHE_MAX_ENTRIES,
|
|
1913
|
-
ttlMs = ETAG_CACHE_TTL_MS
|
|
1914
|
-
} = config ?? {};
|
|
1915
|
-
if (!enabled) {
|
|
1916
|
-
return {
|
|
1917
|
-
async onRequest({ request }) {
|
|
1918
|
-
return request;
|
|
1919
|
-
}
|
|
1920
|
-
};
|
|
1921
|
-
}
|
|
1922
|
-
return {
|
|
1923
|
-
async onRequest({ request }) {
|
|
1924
|
-
if (request.method !== "GET") {
|
|
1925
|
-
return request;
|
|
1926
|
-
}
|
|
1927
|
-
const cacheKey = getETagCacheKey(request);
|
|
1928
|
-
const cached = etagCache.get(cacheKey);
|
|
1929
|
-
if (cached) {
|
|
1930
|
-
if (Date.now() - cached.timestamp > ttlMs) {
|
|
1931
|
-
etagCache.delete(cacheKey);
|
|
1932
|
-
} else {
|
|
1933
|
-
request.headers.set("If-None-Match", cached.etag);
|
|
1934
|
-
}
|
|
1935
|
-
}
|
|
1936
|
-
return request;
|
|
1937
|
-
},
|
|
1938
|
-
async onResponse({ request, response }) {
|
|
1939
|
-
if (request.method !== "GET") {
|
|
1940
|
-
return response;
|
|
1941
|
-
}
|
|
1942
|
-
const cacheKey = getETagCacheKey(request);
|
|
1943
|
-
if (response.status === 304) {
|
|
1944
|
-
const cached = etagCache.get(cacheKey);
|
|
1945
|
-
if (cached) {
|
|
1946
|
-
cached.timestamp = Date.now();
|
|
1947
|
-
return new Response(cached.body, {
|
|
1948
|
-
status: 200,
|
|
1949
|
-
headers: response.headers
|
|
1950
|
-
});
|
|
1951
|
-
}
|
|
1952
|
-
return response;
|
|
1953
|
-
}
|
|
1954
|
-
if (response.ok) {
|
|
1955
|
-
const etag = response.headers.get("ETag");
|
|
1956
|
-
if (etag) {
|
|
1957
|
-
const cloned = response.clone();
|
|
1958
|
-
const body = await cloned.text();
|
|
1959
|
-
evictOldEntries(maxEntries, ttlMs);
|
|
1960
|
-
etagCache.set(cacheKey, {
|
|
1961
|
-
etag,
|
|
1962
|
-
body,
|
|
1963
|
-
timestamp: Date.now()
|
|
1964
|
-
});
|
|
1965
|
-
}
|
|
1966
|
-
}
|
|
1967
|
-
return response;
|
|
1968
|
-
}
|
|
1969
|
-
};
|
|
1970
|
-
}
|
|
1971
|
-
var retryBodyMap = /* @__PURE__ */ new WeakMap();
|
|
1972
|
-
function createRetryMiddleware(retryConfig) {
|
|
1973
|
-
if (retryConfig === false) {
|
|
1974
|
-
return {
|
|
1975
|
-
async onResponse({ response }) {
|
|
1976
|
-
return response;
|
|
1977
|
-
}
|
|
1978
|
-
};
|
|
1979
|
-
}
|
|
1980
|
-
const {
|
|
1981
|
-
maxRetries = 3,
|
|
1982
|
-
baseDelay = BASE_RETRY_DELAY_MS,
|
|
1983
|
-
maxDelay = MAX_RETRY_DELAY_MS,
|
|
1984
|
-
shouldRetry = isRetryableStatus,
|
|
1985
|
-
timeout = DEFAULT_TIMEOUT_MS
|
|
1986
|
-
} = retryConfig ?? {};
|
|
1987
|
-
return {
|
|
1988
|
-
async onRequest({ request }) {
|
|
1989
|
-
const body = request.body ? await request.clone().text() : null;
|
|
1990
|
-
const controller = new AbortController();
|
|
1991
|
-
setTimeout(() => controller.abort(), timeout);
|
|
1992
|
-
const newRequest = new Request(request.url, {
|
|
1993
|
-
method: request.method,
|
|
1994
|
-
headers: request.headers,
|
|
1995
|
-
body,
|
|
1996
|
-
signal: controller.signal
|
|
1997
|
-
});
|
|
1998
|
-
retryBodyMap.set(newRequest, body);
|
|
1999
|
-
return newRequest;
|
|
2000
|
-
},
|
|
2001
|
-
async onResponse({ response, request }) {
|
|
2002
|
-
const originalBody = retryBodyMap.get(request) ?? null;
|
|
2003
|
-
let attempt = 0;
|
|
2004
|
-
let currentResponse = response;
|
|
2005
|
-
while (attempt < maxRetries && shouldRetry(currentResponse.status, attempt)) {
|
|
2006
|
-
const retryAfter = currentResponse.headers.get("Retry-After");
|
|
2007
|
-
const delay = retryAfter ? Number.parseInt(retryAfter, 10) * 1e3 : exponentialBackoff(attempt, baseDelay, maxDelay);
|
|
2008
|
-
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
2009
|
-
attempt++;
|
|
2010
|
-
const controller = new AbortController();
|
|
2011
|
-
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
2012
|
-
try {
|
|
2013
|
-
const retryRequest = new Request(request.url, {
|
|
2014
|
-
method: request.method,
|
|
2015
|
-
headers: request.headers,
|
|
2016
|
-
body: originalBody,
|
|
2017
|
-
signal: controller.signal
|
|
2018
|
-
});
|
|
2019
|
-
const newResponse = await fetch(retryRequest);
|
|
2020
|
-
clearTimeout(timeoutId);
|
|
2021
|
-
if (newResponse.ok || !shouldRetry(newResponse.status, attempt)) {
|
|
2022
|
-
retryBodyMap.delete(request);
|
|
2023
|
-
return newResponse;
|
|
2024
|
-
}
|
|
2025
|
-
currentResponse = newResponse;
|
|
2026
|
-
} catch (error) {
|
|
2027
|
-
clearTimeout(timeoutId);
|
|
2028
|
-
if (attempt >= maxRetries) {
|
|
2029
|
-
retryBodyMap.delete(request);
|
|
2030
|
-
throw error;
|
|
2031
|
-
}
|
|
2032
|
-
}
|
|
2033
|
-
}
|
|
2034
|
-
retryBodyMap.delete(request);
|
|
2035
|
-
return currentResponse;
|
|
2036
|
-
}
|
|
2037
|
-
};
|
|
2038
|
-
}
|
|
2039
|
-
function validateClientConfig(config) {
|
|
2040
|
-
return {
|
|
2041
|
-
secretKey: validateAndSanitizeSecretKey(config.secretKey),
|
|
2042
|
-
baseUrl: (config.platformUrl || `https://${DEFAULT_SDK_API_HOST}`).trim()
|
|
2043
|
-
};
|
|
2044
|
-
}
|
|
2045
|
-
function createRestClient(config) {
|
|
2046
|
-
const { secretKey, baseUrl } = validateClientConfig(config);
|
|
2047
|
-
const { client, middlewares } = buildClient(`${baseUrl}${SDK_API_PATH}`, {
|
|
2048
|
-
"Content-Type": "application/json",
|
|
2049
|
-
"x-app-secret": secretKey
|
|
2050
|
-
});
|
|
2051
|
-
if (config.deduplication !== false) {
|
|
2052
|
-
middlewares.push(createDeduplicationMiddleware(config.deduplication));
|
|
2053
|
-
}
|
|
2054
|
-
if (config.circuitBreaker !== false) {
|
|
2055
|
-
middlewares.push(createCircuitBreakerMiddleware(config.circuitBreaker));
|
|
2056
|
-
}
|
|
2057
|
-
if (config.etag !== false) {
|
|
2058
|
-
middlewares.push(createETagMiddleware(config.etag));
|
|
2059
|
-
}
|
|
2060
|
-
middlewares.push(createRetryMiddleware(config.retry));
|
|
2061
|
-
return client;
|
|
2062
|
-
}
|
|
2063
|
-
function createDynamicRestClient(config) {
|
|
2064
|
-
const { secretKey, baseUrl } = validateClientConfig(config);
|
|
2065
|
-
const validatedConfig = {
|
|
2066
|
-
...config,
|
|
2067
|
-
secretKey,
|
|
2068
|
-
platformUrl: baseUrl
|
|
2069
|
-
};
|
|
2070
|
-
const { client, middlewares } = buildClient(`${baseUrl}${SDK_API_PATH}`, {
|
|
2071
|
-
"Content-Type": "application/json"
|
|
2072
|
-
});
|
|
2073
|
-
if (config.deduplication !== false) {
|
|
2074
|
-
middlewares.push(createDeduplicationMiddleware(config.deduplication));
|
|
2075
|
-
}
|
|
2076
|
-
middlewares.push(createAuthMiddleware(validatedConfig));
|
|
2077
|
-
if (config.circuitBreaker !== false) {
|
|
2078
|
-
middlewares.push(createCircuitBreakerMiddleware(config.circuitBreaker));
|
|
2079
|
-
}
|
|
2080
|
-
if (config.etag !== false) {
|
|
2081
|
-
middlewares.push(createETagMiddleware(config.etag));
|
|
2082
|
-
}
|
|
2083
|
-
middlewares.push(createRetryMiddleware(config.retry));
|
|
2084
|
-
return client;
|
|
2085
|
-
}
|
|
2086
|
-
|
|
2087
|
-
// src/connection-url.ts
|
|
2088
|
-
var SYLPHX_PROTOCOL = "sylphx:";
|
|
2089
|
-
var DEFAULT_VERSION = "v1";
|
|
2090
|
-
var CREDENTIAL_REGEX = /^(pk|sk)_(dev|stg|prod|prev)_[a-f0-9]{32,64}$/;
|
|
2091
|
-
var VERSION_REGEX = /^v[0-9]+$/;
|
|
2092
|
-
var SLUG_REGEX = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
|
|
2093
|
-
var InvalidConnectionUrlError = class _InvalidConnectionUrlError extends Error {
|
|
2094
|
-
code = "INVALID_CONNECTION_URL";
|
|
2095
|
-
constructor(message2) {
|
|
2096
|
-
super(message2);
|
|
2097
|
-
this.name = "InvalidConnectionUrlError";
|
|
2098
|
-
Object.setPrototypeOf(this, _InvalidConnectionUrlError.prototype);
|
|
2099
|
-
}
|
|
2100
|
-
};
|
|
2101
|
-
function fail(reason) {
|
|
2102
|
-
throw new InvalidConnectionUrlError(`Invalid Sylphx connection URL: ${reason}`);
|
|
2103
|
-
}
|
|
2104
|
-
function parseCredential(raw) {
|
|
2105
|
-
const match = CREDENTIAL_REGEX.exec(raw);
|
|
2106
|
-
if (!match) {
|
|
2107
|
-
fail(`credential must match (pk|sk)_(dev|stg|prod|prev)_[a-f0-9]{32,64}, got "${raw}"`);
|
|
2108
|
-
}
|
|
2109
|
-
return {
|
|
2110
|
-
credentialType: match[1],
|
|
2111
|
-
env: match[2]
|
|
2112
|
-
};
|
|
2113
|
-
}
|
|
2114
|
-
function validateSlug(candidate) {
|
|
2115
|
-
if (!candidate || candidate.length > 63 || !SLUG_REGEX.test(candidate)) {
|
|
2116
|
-
fail(`slug "${candidate}" is not a valid DNS label (lowercase alnum + hyphens, 1-63 chars)`);
|
|
2117
|
-
}
|
|
2118
|
-
return candidate;
|
|
2119
|
-
}
|
|
2120
|
-
function parseConnectionUrl(url) {
|
|
2121
|
-
if (typeof url !== "string" || url.length === 0) {
|
|
2122
|
-
fail("url must be a non-empty string");
|
|
2123
|
-
}
|
|
2124
|
-
let parsed;
|
|
2125
|
-
try {
|
|
2126
|
-
parsed = new URL(url);
|
|
2127
|
-
} catch {
|
|
2128
|
-
fail(`not a valid URL: "${url}"`);
|
|
2129
|
-
}
|
|
2130
|
-
if (parsed.protocol !== SYLPHX_PROTOCOL) {
|
|
2131
|
-
fail(`protocol must be "sylphx:", got "${parsed.protocol}"`);
|
|
2132
|
-
}
|
|
2133
|
-
const credential = decodeURIComponent(parsed.username);
|
|
2134
|
-
if (!credential) {
|
|
2135
|
-
fail("missing credential (expected `sylphx://<credential>@<host>`)");
|
|
2136
|
-
}
|
|
2137
|
-
if (parsed.password) {
|
|
2138
|
-
fail("connection URL must not contain a password component");
|
|
2139
|
-
}
|
|
2140
|
-
const { credentialType, env } = parseCredential(credential);
|
|
2141
|
-
const host = parsed.host;
|
|
2142
|
-
if (!host) {
|
|
2143
|
-
fail("missing host");
|
|
2144
|
-
}
|
|
2145
|
-
const hostname = parsed.hostname;
|
|
2146
|
-
const firstDot = hostname.indexOf(".");
|
|
2147
|
-
if (firstDot <= 0) {
|
|
2148
|
-
fail(`host "${hostname}" must contain at least one dot (slug.domain)`);
|
|
2149
|
-
}
|
|
2150
|
-
const slugCandidate = hostname.slice(0, firstDot);
|
|
2151
|
-
const domainSuffix = hostname.slice(firstDot + 1);
|
|
2152
|
-
if (!domainSuffix) {
|
|
2153
|
-
fail(`host "${hostname}" has empty domain suffix`);
|
|
2154
|
-
}
|
|
2155
|
-
const slug = validateSlug(slugCandidate);
|
|
2156
|
-
const rawPath = parsed.pathname.replace(/^\/+/, "").replace(/\/+$/, "");
|
|
2157
|
-
let version = DEFAULT_VERSION;
|
|
2158
|
-
if (rawPath !== "") {
|
|
2159
|
-
if (!VERSION_REGEX.test(rawPath)) {
|
|
2160
|
-
fail(`path "${parsed.pathname}" must be empty or match /v{N}`);
|
|
2161
|
-
}
|
|
2162
|
-
version = rawPath;
|
|
2163
|
-
}
|
|
2164
|
-
if (parsed.search) {
|
|
2165
|
-
fail("connection URL must not contain a query string");
|
|
2166
|
-
}
|
|
2167
|
-
if (parsed.hash) {
|
|
2168
|
-
fail("connection URL must not contain a fragment");
|
|
2169
|
-
}
|
|
2170
|
-
const apiBaseUrl = `https://${host}/${version}`;
|
|
2171
|
-
return {
|
|
2172
|
-
credential,
|
|
2173
|
-
credentialType,
|
|
2174
|
-
env,
|
|
2175
|
-
slug,
|
|
2176
|
-
host,
|
|
2177
|
-
apiBaseUrl
|
|
2178
|
-
};
|
|
2179
|
-
}
|
|
2180
|
-
|
|
2181
|
-
// src/config.ts
|
|
2182
|
-
var LEGACY_EMBEDDED_REF_PATTERN = /^(pk|sk)_(dev|stg|prod|prev)_[a-z0-9]{12}_[a-f0-9]+$/;
|
|
2183
|
-
var LEGACY_APP_KEY_PATTERN = /^app_(dev|stg|prod|prev)_/;
|
|
2184
|
-
var MIGRATION_MESSAGE = "API key format has changed. Use a sylphx:// connection URL instead.\n\nNew format: sylphx://pk_prod_{hex}@your-slug.sylphx.com\n\nGenerate new credentials from the Sylphx Console \u2192 Your App \u2192 Environments.\nSee https://docs.sylphx.com/migration for details.";
|
|
2185
|
-
function rejectLegacyKeyFormat(input) {
|
|
2186
|
-
const trimmed = input.trim().toLowerCase();
|
|
2187
|
-
if (LEGACY_APP_KEY_PATTERN.test(trimmed)) {
|
|
2188
|
-
throw new SylphxError(`[Sylphx] ${MIGRATION_MESSAGE}`, { code: "BAD_REQUEST" });
|
|
2189
|
-
}
|
|
2190
|
-
if (LEGACY_EMBEDDED_REF_PATTERN.test(trimmed)) {
|
|
2191
|
-
throw new SylphxError(`[Sylphx] ${MIGRATION_MESSAGE}`, { code: "BAD_REQUEST" });
|
|
2192
|
-
}
|
|
2193
|
-
}
|
|
2194
|
-
function freezeConfig(opts) {
|
|
2195
|
-
return Object.freeze({
|
|
2196
|
-
credential: opts.credential,
|
|
2197
|
-
credentialType: opts.credentialType,
|
|
2198
|
-
env: opts.env,
|
|
2199
|
-
slug: opts.slug,
|
|
2200
|
-
baseUrl: opts.baseUrl,
|
|
2201
|
-
accessToken: opts.accessToken,
|
|
2202
|
-
// Backward-compat aliases
|
|
2203
|
-
secretKey: opts.credentialType === "sk" ? opts.credential : void 0,
|
|
2204
|
-
publicKey: opts.credentialType === "pk" ? opts.credential : void 0,
|
|
2205
|
-
ref: opts.slug
|
|
2206
|
-
});
|
|
2207
|
-
}
|
|
2208
|
-
function createClient(input) {
|
|
2209
|
-
if (typeof input === "string") {
|
|
2210
|
-
return createConfigFromUrl(input);
|
|
2211
|
-
}
|
|
2212
|
-
return createConfigFromComponents(input);
|
|
2213
|
-
}
|
|
2214
|
-
function createServerClient(input) {
|
|
2215
|
-
const config = createClient(input);
|
|
2216
|
-
if (config.credentialType !== "sk") {
|
|
2217
|
-
throw new SylphxError(
|
|
2218
|
-
"[Sylphx] createServerClient() requires a secret key (sk_*). Use a SYLPHX_SECRET_URL with an sk_ credential, or pass { secretKey } in the components object.",
|
|
2219
|
-
{ code: "BAD_REQUEST" }
|
|
2220
|
-
);
|
|
2221
|
-
}
|
|
2222
|
-
return config;
|
|
2223
|
-
}
|
|
2224
|
-
function createConfigFromUrl(url) {
|
|
2225
|
-
if (!url || typeof url !== "string") {
|
|
2226
|
-
throw new SylphxError(
|
|
2227
|
-
"[Sylphx] Connection URL is required. Set SYLPHX_URL or NEXT_PUBLIC_SYLPHX_URL environment variable.\n\nFormat: sylphx://pk_prod_{hex}@your-slug.sylphx.com",
|
|
2228
|
-
{ code: "BAD_REQUEST" }
|
|
2229
|
-
);
|
|
2230
|
-
}
|
|
2231
|
-
const trimmed = url.trim();
|
|
2232
|
-
rejectLegacyKeyFormat(trimmed);
|
|
2233
|
-
if (!trimmed.startsWith("sylphx://")) {
|
|
2234
|
-
if (CREDENTIAL_REGEX.test(trimmed)) {
|
|
2235
|
-
throw new SylphxError(
|
|
2236
|
-
"[Sylphx] Received a bare credential instead of a connection URL.\n\nWrap it in a connection URL: sylphx://<credential>@<slug>.sylphx.com\nOr use createClient({ slug, publicKey }) for explicit components.",
|
|
2237
|
-
{ code: "BAD_REQUEST" }
|
|
2238
|
-
);
|
|
2239
|
-
}
|
|
2240
|
-
throw new SylphxError(
|
|
2241
|
-
`[Sylphx] Invalid connection URL \u2014 must start with "sylphx://". Got: "${trimmed.slice(0, 30)}..."`,
|
|
2242
|
-
{ code: "BAD_REQUEST" }
|
|
2243
|
-
);
|
|
2244
|
-
}
|
|
2245
|
-
let parsed;
|
|
2246
|
-
try {
|
|
2247
|
-
parsed = parseConnectionUrl(trimmed);
|
|
2248
|
-
} catch (err) {
|
|
2249
|
-
if (err instanceof InvalidConnectionUrlError) {
|
|
2250
|
-
throw new SylphxError(err.message, { code: "BAD_REQUEST", cause: err });
|
|
2251
|
-
}
|
|
2252
|
-
throw err;
|
|
2253
|
-
}
|
|
2254
|
-
return freezeConfig({
|
|
2255
|
-
credential: parsed.credential,
|
|
2256
|
-
credentialType: parsed.credentialType,
|
|
2257
|
-
env: parsed.env,
|
|
2258
|
-
slug: parsed.slug,
|
|
2259
|
-
baseUrl: parsed.apiBaseUrl
|
|
2260
|
-
});
|
|
2261
|
-
}
|
|
2262
|
-
function createConfigFromComponents(input) {
|
|
2263
|
-
const credential = input.secretKey || input.publicKey;
|
|
2264
|
-
if (!credential) {
|
|
2265
|
-
throw new SylphxError("[Sylphx] Either publicKey or secretKey must be provided.", {
|
|
2266
|
-
code: "BAD_REQUEST"
|
|
2267
|
-
});
|
|
2268
|
-
}
|
|
2269
|
-
const resolvedSlug = input.slug || input.ref;
|
|
2270
|
-
if (!resolvedSlug) {
|
|
2271
|
-
throw new SylphxError("[Sylphx] slug is required when using explicit components.", {
|
|
2272
|
-
code: "BAD_REQUEST"
|
|
2273
|
-
});
|
|
2274
|
-
}
|
|
2275
|
-
const trimmedCred = credential.trim().toLowerCase();
|
|
2276
|
-
if (CREDENTIAL_REGEX.test(trimmedCred)) {
|
|
2277
|
-
const match = CREDENTIAL_REGEX.exec(trimmedCred);
|
|
2278
|
-
const credentialType = match[1];
|
|
2279
|
-
const env = match[2];
|
|
2280
|
-
const slug = resolvedSlug.trim().toLowerCase();
|
|
2281
|
-
const domain = input.domain?.trim() || "api.sylphx.com";
|
|
2282
|
-
const baseUrl = `https://${slug}.${domain}/v1`;
|
|
2283
|
-
return freezeConfig({
|
|
2284
|
-
credential: trimmedCred,
|
|
2285
|
-
credentialType,
|
|
2286
|
-
env,
|
|
2287
|
-
slug,
|
|
2288
|
-
baseUrl,
|
|
2289
|
-
accessToken: input.accessToken
|
|
2290
|
-
});
|
|
2291
|
-
}
|
|
2292
|
-
const parts = trimmedCred.split("_");
|
|
2293
|
-
const prefix = parts[0];
|
|
2294
|
-
if ((prefix === "pk" || prefix === "sk") && parts.length >= 3) {
|
|
2295
|
-
const envSegment = parts[1];
|
|
2296
|
-
const validEnvs = ["dev", "stg", "prod", "prev"];
|
|
2297
|
-
const env = validEnvs.includes(envSegment) ? envSegment : "prod";
|
|
2298
|
-
const slug = resolvedSlug.trim().toLowerCase();
|
|
2299
|
-
let baseUrl;
|
|
2300
|
-
if (input.platformUrl) {
|
|
2301
|
-
const platform = input.platformUrl.trim().replace(/\/$/, "");
|
|
2302
|
-
baseUrl = platform.includes("/v1") ? platform : `${platform}/v1`;
|
|
2303
|
-
} else {
|
|
2304
|
-
const domain = input.domain?.trim() || "api.sylphx.com";
|
|
2305
|
-
baseUrl = `https://${slug}.${domain}/v1`;
|
|
2306
|
-
}
|
|
2307
|
-
return freezeConfig({
|
|
2308
|
-
credential: trimmedCred,
|
|
2309
|
-
credentialType: prefix,
|
|
2310
|
-
env,
|
|
2311
|
-
slug,
|
|
2312
|
-
baseUrl,
|
|
2313
|
-
accessToken: input.accessToken
|
|
2314
|
-
});
|
|
2315
|
-
}
|
|
2316
|
-
throw new SylphxError(
|
|
2317
|
-
`[Sylphx] Invalid credential format. Expected (pk|sk)_(dev|stg|prod|prev)_[a-f0-9]{32,64}. Got: "${trimmedCred.slice(0, 30)}..."`,
|
|
2318
|
-
{ code: "BAD_REQUEST" }
|
|
2319
|
-
);
|
|
2320
|
-
}
|
|
2321
|
-
function httpStatusToErrorCode(status) {
|
|
2322
|
-
switch (status) {
|
|
2323
|
-
case 400:
|
|
2324
|
-
return "BAD_REQUEST";
|
|
2325
|
-
case 401:
|
|
2326
|
-
return "UNAUTHORIZED";
|
|
2327
|
-
case 403:
|
|
2328
|
-
return "FORBIDDEN";
|
|
2329
|
-
case 404:
|
|
2330
|
-
return "NOT_FOUND";
|
|
2331
|
-
case 409:
|
|
2332
|
-
return "CONFLICT";
|
|
2333
|
-
case 413:
|
|
2334
|
-
return "PAYLOAD_TOO_LARGE";
|
|
2335
|
-
case 422:
|
|
2336
|
-
return "UNPROCESSABLE_ENTITY";
|
|
2337
|
-
case 429:
|
|
2338
|
-
return "TOO_MANY_REQUESTS";
|
|
2339
|
-
case 500:
|
|
2340
|
-
return "INTERNAL_SERVER_ERROR";
|
|
2341
|
-
case 501:
|
|
2342
|
-
return "NOT_IMPLEMENTED";
|
|
2343
|
-
case 502:
|
|
2344
|
-
return "BAD_GATEWAY";
|
|
2345
|
-
case 503:
|
|
2346
|
-
return "SERVICE_UNAVAILABLE";
|
|
2347
|
-
case 504:
|
|
2348
|
-
return "GATEWAY_TIMEOUT";
|
|
2349
|
-
default:
|
|
2350
|
-
return status >= 500 ? "INTERNAL_SERVER_ERROR" : "BAD_REQUEST";
|
|
2351
|
-
}
|
|
2352
|
-
}
|
|
2353
|
-
function buildHeaders(config) {
|
|
2354
|
-
const headers = {
|
|
2355
|
-
"Content-Type": "application/json"
|
|
2356
|
-
};
|
|
2357
|
-
if (config.credential) {
|
|
2358
|
-
headers["x-app-secret"] = config.credential;
|
|
2359
|
-
}
|
|
2360
|
-
if (config.accessToken) {
|
|
2361
|
-
headers.Authorization = `Bearer ${config.accessToken}`;
|
|
2362
|
-
}
|
|
2363
|
-
return headers;
|
|
2364
|
-
}
|
|
2365
|
-
function buildApiUrl(config, path) {
|
|
2366
|
-
const base = config.baseUrl.replace(/\/$/, "");
|
|
2367
|
-
const cleanPath = path.startsWith("/") ? path : `/${path}`;
|
|
2368
|
-
return `${base}${cleanPath}`;
|
|
2369
|
-
}
|
|
2370
|
-
async function callApi(config, path, options = {}) {
|
|
2371
|
-
const {
|
|
2372
|
-
method = "GET",
|
|
2373
|
-
body,
|
|
2374
|
-
query,
|
|
2375
|
-
timeout = DEFAULT_TIMEOUT_MS,
|
|
2376
|
-
signal,
|
|
2377
|
-
idempotencyKey,
|
|
2378
|
-
headers: extraHeaders
|
|
2379
|
-
} = options;
|
|
2380
|
-
let url = buildApiUrl(config, path);
|
|
2381
|
-
if (query) {
|
|
2382
|
-
const params = new URLSearchParams();
|
|
2383
|
-
for (const [key, value] of Object.entries(query)) {
|
|
2384
|
-
if (value !== void 0) {
|
|
2385
|
-
params.set(key, String(value));
|
|
2386
|
-
}
|
|
2387
|
-
}
|
|
2388
|
-
const queryString = params.toString();
|
|
2389
|
-
if (queryString) {
|
|
2390
|
-
url += `?${queryString}`;
|
|
2391
|
-
}
|
|
2392
|
-
}
|
|
2393
|
-
const controller = new AbortController();
|
|
2394
|
-
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
2395
|
-
const combinedSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
|
|
2396
|
-
const headers = buildHeaders(config);
|
|
2397
|
-
if (idempotencyKey) {
|
|
2398
|
-
headers["Idempotency-Key"] = idempotencyKey;
|
|
2399
|
-
}
|
|
2400
|
-
if (extraHeaders) {
|
|
2401
|
-
for (const [k, v] of Object.entries(extraHeaders)) {
|
|
2402
|
-
headers[k] = v;
|
|
2403
|
-
}
|
|
2404
|
-
}
|
|
2405
|
-
const fetchOptions = {
|
|
2406
|
-
method,
|
|
2407
|
-
headers,
|
|
2408
|
-
signal: combinedSignal
|
|
2409
|
-
};
|
|
2410
|
-
if (body) {
|
|
2411
|
-
fetchOptions.body = JSON.stringify(body);
|
|
2412
|
-
}
|
|
2413
|
-
let response;
|
|
2414
|
-
try {
|
|
2415
|
-
response = await fetch(url, fetchOptions);
|
|
2416
|
-
} catch (error) {
|
|
2417
|
-
clearTimeout(timeoutId);
|
|
2418
|
-
if (error instanceof Error) {
|
|
2419
|
-
if (error.name === "AbortError") {
|
|
2420
|
-
if (controller.signal.aborted && !signal?.aborted) {
|
|
2421
|
-
throw new TimeoutError(timeout);
|
|
2422
|
-
}
|
|
2423
|
-
throw new SylphxError("Request aborted", {
|
|
2424
|
-
code: "ABORTED",
|
|
2425
|
-
cause: error
|
|
2426
|
-
});
|
|
2427
|
-
}
|
|
2428
|
-
throw new NetworkError(error.message, { cause: error });
|
|
2429
|
-
}
|
|
2430
|
-
throw new NetworkError("Network request failed");
|
|
2431
|
-
} finally {
|
|
2432
|
-
clearTimeout(timeoutId);
|
|
2433
|
-
}
|
|
2434
|
-
if (!response.ok) {
|
|
2435
|
-
const errorBody = await response.text().catch(() => "");
|
|
2436
|
-
let errorMessage = "Request failed";
|
|
2437
|
-
let errorData;
|
|
2438
|
-
if (errorBody) {
|
|
2439
|
-
try {
|
|
2440
|
-
const parsed = JSON.parse(errorBody);
|
|
2441
|
-
errorMessage = parsed.error?.message ?? parsed.message ?? errorMessage;
|
|
2442
|
-
errorData = parsed.error;
|
|
2443
|
-
} catch {
|
|
2444
|
-
errorMessage = response.statusText || errorMessage;
|
|
2445
|
-
}
|
|
2446
|
-
}
|
|
2447
|
-
const errorCode = httpStatusToErrorCode(response.status);
|
|
2448
|
-
const retryAfterHeader = response.headers.get("Retry-After");
|
|
2449
|
-
const rateLimitLimit = response.headers.get("X-RateLimit-Limit");
|
|
2450
|
-
const rateLimitRemaining = response.headers.get("X-RateLimit-Remaining");
|
|
2451
|
-
const rateLimitReset = response.headers.get("X-RateLimit-Reset");
|
|
2452
|
-
const retryAfter = retryAfterHeader ? Number.parseInt(retryAfterHeader, 10) : void 0;
|
|
2453
|
-
if (response.status === 429) {
|
|
2454
|
-
throw new RateLimitError(errorMessage || "Too many requests", {
|
|
2455
|
-
status: response.status,
|
|
2456
|
-
data: errorData,
|
|
2457
|
-
retryAfter,
|
|
2458
|
-
limit: rateLimitLimit ? Number.parseInt(rateLimitLimit, 10) : void 0,
|
|
2459
|
-
remaining: rateLimitRemaining ? Number.parseInt(rateLimitRemaining, 10) : void 0,
|
|
2460
|
-
resetAt: rateLimitReset ? Number.parseInt(rateLimitReset, 10) : void 0
|
|
2461
|
-
});
|
|
2462
|
-
}
|
|
2463
|
-
throw new SylphxError(errorMessage, {
|
|
2464
|
-
code: errorCode,
|
|
2465
|
-
status: response.status,
|
|
2466
|
-
data: errorData,
|
|
2467
|
-
retryAfter
|
|
2468
|
-
});
|
|
2469
|
-
}
|
|
2470
|
-
const text = await response.text();
|
|
2471
|
-
if (!text) {
|
|
2472
|
-
return {};
|
|
2473
|
-
}
|
|
2474
|
-
try {
|
|
2475
|
-
return JSON.parse(text);
|
|
2476
|
-
} catch (error) {
|
|
2477
|
-
throw new SylphxError("Failed to parse response", {
|
|
2478
|
-
code: "PARSE_ERROR",
|
|
2479
|
-
cause: error instanceof Error ? error : void 0,
|
|
2480
|
-
data: { body: text.slice(0, 200) }
|
|
2481
|
-
});
|
|
2482
|
-
}
|
|
2483
|
-
}
|
|
2484
|
-
|
|
2485
|
-
// src/lib/functions/index.ts
|
|
2486
|
-
var FunctionsClient = {
|
|
2487
|
-
/**
|
|
2488
|
-
* Deploy (create or update) a function.
|
|
2489
|
-
*
|
|
2490
|
-
* If a function with the same name already exists, it is updated
|
|
2491
|
-
* (version number incremented, code replaced atomically).
|
|
2492
|
-
*
|
|
2493
|
-
* @example
|
|
2494
|
-
* ```typescript
|
|
2495
|
-
* const fn = await FunctionsClient.deploy(config, {
|
|
2496
|
-
* name: 'send-webhook',
|
|
2497
|
-
* code: `
|
|
2498
|
-
* export default async (req: Request) => {
|
|
2499
|
-
* const body = await req.json()
|
|
2500
|
-
* await fetch(body.url, { method: 'POST', body: JSON.stringify(body.payload) })
|
|
2501
|
-
* return Response.json({ ok: true })
|
|
2502
|
-
* }
|
|
2503
|
-
* `,
|
|
2504
|
-
* timeoutSeconds: 10,
|
|
2505
|
-
* })
|
|
2506
|
-
* console.log('Deployed:', fn.url)
|
|
2507
|
-
* ```
|
|
2508
|
-
*/
|
|
2509
|
-
async deploy(config, options) {
|
|
2510
|
-
return callApi(config, "/functions", {
|
|
2511
|
-
method: "POST",
|
|
2512
|
-
body: options
|
|
2513
|
-
});
|
|
2514
|
-
},
|
|
2515
|
-
/**
|
|
2516
|
-
* Get a function by name.
|
|
2517
|
-
*/
|
|
2518
|
-
async get(config, name) {
|
|
2519
|
-
return callApi(config, `/functions/${encodeURIComponent(name)}`, { method: "GET" });
|
|
2520
|
-
},
|
|
2521
|
-
/**
|
|
2522
|
-
* List all functions for this project.
|
|
2523
|
-
*/
|
|
2524
|
-
async list(config, options = {}) {
|
|
2525
|
-
const params = new URLSearchParams();
|
|
2526
|
-
if (options.status) params.set("status", options.status);
|
|
2527
|
-
if (options.environment) params.set("environment", options.environment);
|
|
2528
|
-
if (options.limit) params.set("limit", String(options.limit));
|
|
2529
|
-
const qs = params.toString();
|
|
2530
|
-
return callApi(config, `/functions${qs ? `?${qs}` : ""}`, { method: "GET" });
|
|
2531
|
-
},
|
|
2532
|
-
/**
|
|
2533
|
-
* Delete a function permanently.
|
|
2534
|
-
*/
|
|
2535
|
-
async delete(config, name) {
|
|
2536
|
-
return callApi(config, `/functions/${encodeURIComponent(name)}`, { method: "DELETE" });
|
|
2537
|
-
},
|
|
2538
|
-
/**
|
|
2539
|
-
* Invoke a function from server-side code.
|
|
2540
|
-
*
|
|
2541
|
-
* For client-side invocations, call the function URL directly via fetch().
|
|
2542
|
-
*
|
|
2543
|
-
* @example
|
|
2544
|
-
* ```typescript
|
|
2545
|
-
* const result = await FunctionsClient.invoke(config, 'process-order', {
|
|
2546
|
-
* body: { orderId: '123', userId: 'user_abc' },
|
|
2547
|
-
* })
|
|
2548
|
-
* ```
|
|
2549
|
-
*/
|
|
2550
|
-
async invoke(config, name, body, options = {}) {
|
|
2551
|
-
return callApi(config, `/functions/${encodeURIComponent(name)}/invoke`, {
|
|
2552
|
-
method: options.method ?? "POST",
|
|
2553
|
-
body: body ?? null,
|
|
2554
|
-
headers: options.headers
|
|
2555
|
-
});
|
|
2556
|
-
},
|
|
2557
|
-
/**
|
|
2558
|
-
* Retrieve recent invocation logs for a function.
|
|
2559
|
-
*
|
|
2560
|
-
* @example
|
|
2561
|
-
* ```typescript
|
|
2562
|
-
* const logs = await FunctionsClient.logs(config, 'send-webhook', { errorsOnly: true })
|
|
2563
|
-
* for (const entry of logs) {
|
|
2564
|
-
* console.log(`${entry.status} ${entry.durationMs}ms`, entry.errorMessage)
|
|
2565
|
-
* }
|
|
2566
|
-
* ```
|
|
2567
|
-
*/
|
|
2568
|
-
async logs(config, name, options = {}) {
|
|
2569
|
-
const params = new URLSearchParams();
|
|
2570
|
-
if (options.limit) params.set("limit", String(options.limit));
|
|
2571
|
-
if (options.errorsOnly) params.set("errors_only", "1");
|
|
2572
|
-
if (options.since) params.set("since", options.since);
|
|
2573
|
-
const qs = params.toString();
|
|
2574
|
-
return callApi(config, `/functions/${encodeURIComponent(name)}/logs${qs ? `?${qs}` : ""}`, {
|
|
2575
|
-
method: "GET"
|
|
2576
|
-
});
|
|
2577
|
-
}
|
|
2578
|
-
};
|
|
2579
|
-
|
|
2580
|
-
// src/lib/ids.ts
|
|
2581
|
-
var CB32 = "0123456789abcdefghjkmnpqrstvwxyz";
|
|
2582
|
-
var CB32_MAP = Object.fromEntries([...CB32].map((c, i) => [c, i]));
|
|
2583
|
-
var B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
2584
|
-
var B58_MAP = Object.fromEntries([...B58].map((c, i) => [c, i]));
|
|
2585
|
-
function cb32Encode(hex) {
|
|
2586
|
-
const num = BigInt(`0x${hex}`);
|
|
2587
|
-
const chars = [];
|
|
2588
|
-
let n = num;
|
|
2589
|
-
for (let i = 0; i < 26; i++) {
|
|
2590
|
-
chars.unshift(CB32[Number(n & 0x1fn)]);
|
|
2591
|
-
n >>= 5n;
|
|
2592
|
-
}
|
|
2593
|
-
return chars.join("");
|
|
2594
|
-
}
|
|
2595
|
-
function cb32Decode(str) {
|
|
2596
|
-
if (str.length !== 26) return null;
|
|
2597
|
-
let n = 0n;
|
|
2598
|
-
for (const c of str.toLowerCase()) {
|
|
2599
|
-
const idx = CB32_MAP[c];
|
|
2600
|
-
if (idx === void 0) return null;
|
|
2601
|
-
n = n << 5n | BigInt(idx);
|
|
2602
|
-
}
|
|
2603
|
-
return n.toString(16).padStart(32, "0");
|
|
2604
|
-
}
|
|
2605
|
-
function b58Decode(str) {
|
|
2606
|
-
let n = 0n;
|
|
2607
|
-
for (const c of str) {
|
|
2608
|
-
const i = B58_MAP[c] ?? -1;
|
|
2609
|
-
if (i === -1) return null;
|
|
2610
|
-
n = n * 58n + BigInt(i);
|
|
2611
|
-
}
|
|
2612
|
-
const hex = n.toString(16).padStart(32, "0");
|
|
2613
|
-
return hex.length === 32 ? hex : null;
|
|
2614
|
-
}
|
|
2615
|
-
function hexToUuid(hex) {
|
|
2616
|
-
return [
|
|
2617
|
-
hex.slice(0, 8),
|
|
2618
|
-
hex.slice(8, 12),
|
|
2619
|
-
hex.slice(12, 16),
|
|
2620
|
-
hex.slice(16, 20),
|
|
2621
|
-
hex.slice(20)
|
|
2622
|
-
].join("-");
|
|
2623
|
-
}
|
|
2624
|
-
function encodeUserId(uuid) {
|
|
2625
|
-
const hex = uuid.replace(/-/g, "");
|
|
2626
|
-
if (hex.length !== 32)
|
|
2627
|
-
throw new Error("Invalid UUID: expected 32 hex chars after stripping dashes");
|
|
2628
|
-
return `user_${cb32Encode(hex)}`;
|
|
2629
|
-
}
|
|
2630
|
-
function decodeUserId(prefixedId) {
|
|
2631
|
-
if (!prefixedId.startsWith("user_")) return null;
|
|
2632
|
-
const enc = prefixedId.slice(5);
|
|
2633
|
-
if (!enc) return null;
|
|
2634
|
-
if (enc.length === 26) {
|
|
2635
|
-
const hex2 = cb32Decode(enc);
|
|
2636
|
-
if (hex2) return hexToUuid(hex2);
|
|
2637
|
-
}
|
|
2638
|
-
const hex = b58Decode(enc);
|
|
2639
|
-
if (hex) return hexToUuid(hex);
|
|
2640
|
-
return null;
|
|
2641
|
-
}
|
|
2642
|
-
|
|
2643
|
-
// src/server/ai.ts
|
|
2644
|
-
function createAI(options = {}) {
|
|
2645
|
-
const baseURL = (options.platformUrl || `https://${DEFAULT_SDK_API_HOST}`).trim();
|
|
2646
|
-
const rawApiKey = options.secretKey || process.env.SYLPHX_SECRET_KEY;
|
|
2647
|
-
const apiKey = validateAndSanitizeSecretKey(rawApiKey);
|
|
2648
|
-
const headers = {
|
|
2649
|
-
"Content-Type": "application/json",
|
|
2650
|
-
Authorization: `Bearer ${apiKey}`
|
|
2651
|
-
};
|
|
2652
|
-
async function chat(opts) {
|
|
2653
|
-
const response = await fetch(`${baseURL}/api/v1/chat/completions`, {
|
|
2654
|
-
method: "POST",
|
|
2655
|
-
headers,
|
|
2656
|
-
body: JSON.stringify(opts)
|
|
2657
|
-
});
|
|
2658
|
-
if (!response.ok) {
|
|
2659
|
-
const error = await response.json().catch(() => ({ error: { message: "Chat failed" } }));
|
|
2660
|
-
throw new Error(error.error?.message || "Chat failed");
|
|
2661
|
-
}
|
|
2662
|
-
if (opts.stream) {
|
|
2663
|
-
return parseSSEStream(response);
|
|
2664
|
-
}
|
|
2665
|
-
return response.json();
|
|
2666
|
-
}
|
|
2667
|
-
async function embed(opts) {
|
|
2668
|
-
const response = await fetch(`${baseURL}/api/v1/embeddings`, {
|
|
2669
|
-
method: "POST",
|
|
2670
|
-
headers,
|
|
2671
|
-
body: JSON.stringify(opts)
|
|
2672
|
-
});
|
|
2673
|
-
if (!response.ok) {
|
|
2674
|
-
const error = await response.json().catch(() => ({ error: { message: "Embedding failed" } }));
|
|
2675
|
-
throw new Error(error.error?.message || "Embedding failed");
|
|
2676
|
-
}
|
|
2677
|
-
return response.json();
|
|
2678
|
-
}
|
|
2679
|
-
async function listModels(opts) {
|
|
2680
|
-
const params = new URLSearchParams();
|
|
2681
|
-
if (opts?.capability) params.set("capability", opts.capability);
|
|
2682
|
-
if (opts?.search) params.set("search", opts.search);
|
|
2683
|
-
const query = params.toString();
|
|
2684
|
-
const response = await fetch(`${baseURL}/api/v1/models${query ? `?${query}` : ""}`);
|
|
2685
|
-
if (!response.ok) {
|
|
2686
|
-
throw new Error("Failed to fetch models");
|
|
2687
|
-
}
|
|
2688
|
-
return response.json();
|
|
2689
|
-
}
|
|
2690
|
-
return {
|
|
2691
|
-
chat,
|
|
2692
|
-
embed,
|
|
2693
|
-
listModels
|
|
2694
|
-
};
|
|
2695
|
-
}
|
|
2696
|
-
async function* parseSSEStream(response) {
|
|
2697
|
-
const reader = response.body?.getReader();
|
|
2698
|
-
if (!reader) {
|
|
2699
|
-
throw new Error("Response body is not readable");
|
|
2700
|
-
}
|
|
2701
|
-
const decoder2 = new TextDecoder();
|
|
2702
|
-
let buffer = "";
|
|
2703
|
-
try {
|
|
2704
|
-
while (true) {
|
|
2705
|
-
const { done, value } = await reader.read();
|
|
2706
|
-
if (done) break;
|
|
2707
|
-
buffer += decoder2.decode(value, { stream: true });
|
|
2708
|
-
const lines = buffer.split("\n");
|
|
2709
|
-
buffer = lines.pop() || "";
|
|
2710
|
-
for (const line of lines) {
|
|
2711
|
-
if (line.startsWith("data: ")) {
|
|
2712
|
-
const data = line.slice(6);
|
|
2713
|
-
if (data === "[DONE]") {
|
|
2714
|
-
return;
|
|
2715
|
-
}
|
|
2716
|
-
try {
|
|
2717
|
-
const chunk = JSON.parse(data);
|
|
2718
|
-
yield chunk;
|
|
2719
|
-
} catch {
|
|
2720
|
-
}
|
|
2721
|
-
}
|
|
2722
|
-
}
|
|
2723
|
-
}
|
|
2724
|
-
} finally {
|
|
2725
|
-
reader.releaseLock();
|
|
2726
|
-
}
|
|
2727
|
-
}
|
|
2728
|
-
var defaultClient = null;
|
|
2729
|
-
function getAI() {
|
|
2730
|
-
if (!defaultClient) {
|
|
2731
|
-
defaultClient = createAI();
|
|
2732
|
-
}
|
|
2733
|
-
return defaultClient;
|
|
2734
|
-
}
|
|
2735
|
-
|
|
2736
|
-
// src/server/kv.ts
|
|
2737
|
-
function createKv(options = {}) {
|
|
2738
|
-
const platformUrl = (options.platformUrl || `https://${DEFAULT_SDK_API_HOST}`).trim();
|
|
2739
|
-
const secretKey = validateAndSanitizeSecretKey(resolveSecretUrl(options.secretKey));
|
|
2740
|
-
const headers = {
|
|
2741
|
-
"Content-Type": "application/json",
|
|
2742
|
-
"x-app-secret": secretKey,
|
|
2743
|
-
"X-SDK-Version": SDK_VERSION,
|
|
2744
|
-
"X-SDK-Platform": SDK_PLATFORM
|
|
2745
|
-
};
|
|
2746
|
-
async function request(method, path, body) {
|
|
2747
|
-
let lastError;
|
|
2748
|
-
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
2749
|
-
try {
|
|
2750
|
-
const response = await fetch(`${platformUrl}${SDK_API_PATH}/kv${path}`, {
|
|
2751
|
-
method,
|
|
2752
|
-
headers,
|
|
2753
|
-
body: body ? JSON.stringify(body) : void 0
|
|
2754
|
-
});
|
|
2755
|
-
if (!response.ok) {
|
|
2756
|
-
const errorBody = await response.json().catch(() => ({ error: "Request failed" }));
|
|
2757
|
-
const message2 = typeof errorBody.error === "string" ? errorBody.error : errorBody.error?.message ?? "Request failed";
|
|
2758
|
-
if (response.status === 429) {
|
|
2759
|
-
const retryAfter = Number(response.headers.get("Retry-After")) || void 0;
|
|
2760
|
-
throw new RateLimitError(message2, {
|
|
2761
|
-
retryAfter,
|
|
2762
|
-
limit: Number(response.headers.get("X-RateLimit-Limit")) || void 0,
|
|
2763
|
-
remaining: Number(response.headers.get("X-RateLimit-Remaining")) || void 0
|
|
2764
|
-
});
|
|
2765
|
-
}
|
|
2766
|
-
const codeMap = {
|
|
2767
|
-
400: "BAD_REQUEST",
|
|
2768
|
-
401: "UNAUTHORIZED",
|
|
2769
|
-
403: "FORBIDDEN",
|
|
2770
|
-
404: "NOT_FOUND",
|
|
2771
|
-
409: "CONFLICT",
|
|
2772
|
-
422: "UNPROCESSABLE_ENTITY",
|
|
2773
|
-
500: "INTERNAL_SERVER_ERROR",
|
|
2774
|
-
502: "BAD_GATEWAY",
|
|
2775
|
-
503: "SERVICE_UNAVAILABLE",
|
|
2776
|
-
504: "GATEWAY_TIMEOUT"
|
|
2777
|
-
};
|
|
2778
|
-
throw new SylphxError(message2, {
|
|
2779
|
-
code: codeMap[response.status] ?? "UNKNOWN",
|
|
2780
|
-
status: response.status,
|
|
2781
|
-
data: errorBody.data
|
|
2782
|
-
});
|
|
2783
|
-
}
|
|
2784
|
-
return response.json();
|
|
2785
|
-
} catch (error) {
|
|
2786
|
-
lastError = error instanceof Error ? error : new Error(String(error));
|
|
2787
|
-
const isServerOrNetworkError = error instanceof SylphxError ? error.isRetryable && error.code !== "TOO_MANY_REQUESTS" : error instanceof TypeError;
|
|
2788
|
-
if (!isServerOrNetworkError || attempt >= MAX_RETRIES) {
|
|
2789
|
-
throw error instanceof SylphxError ? error : new SylphxError(lastError.message, {
|
|
2790
|
-
code: "NETWORK_ERROR",
|
|
2791
|
-
cause: lastError
|
|
2792
|
-
});
|
|
2793
|
-
}
|
|
2794
|
-
await new Promise((resolve) => setTimeout(resolve, exponentialBackoff(attempt)));
|
|
2795
|
-
}
|
|
2796
|
-
}
|
|
2797
|
-
throw lastError ?? new SylphxError("Request failed", { code: "UNKNOWN" });
|
|
2798
|
-
}
|
|
2799
|
-
async function get(key) {
|
|
2800
|
-
return request("GET", `/${encodeURIComponent(key)}`);
|
|
2801
|
-
}
|
|
2802
|
-
async function set(key, value, options2) {
|
|
2803
|
-
const result = await request("POST", "", {
|
|
2804
|
-
key,
|
|
2805
|
-
value,
|
|
2806
|
-
...options2
|
|
2807
|
-
});
|
|
2808
|
-
return result.success;
|
|
2809
|
-
}
|
|
2810
|
-
async function del(key) {
|
|
2811
|
-
const result = await request("DELETE", `/${encodeURIComponent(key)}`);
|
|
2812
|
-
return result.deleted;
|
|
2813
|
-
}
|
|
2814
|
-
async function exists(key) {
|
|
2815
|
-
const result = await request("GET", `/exists/${encodeURIComponent(key)}`);
|
|
2816
|
-
return result.exists;
|
|
2817
|
-
}
|
|
2818
|
-
async function mget(keys) {
|
|
2819
|
-
const result = await request("POST", "/mget", { keys });
|
|
2820
|
-
return result.values;
|
|
2821
|
-
}
|
|
2822
|
-
async function mset(entries, options2) {
|
|
2823
|
-
await request("POST", "/mset", {
|
|
2824
|
-
entries,
|
|
2825
|
-
...options2
|
|
2826
|
-
});
|
|
2827
|
-
}
|
|
2828
|
-
async function incr(key, by = 1) {
|
|
2829
|
-
const result = await request("POST", "/incr", {
|
|
2830
|
-
key,
|
|
2831
|
-
by
|
|
2832
|
-
});
|
|
2833
|
-
return result.value;
|
|
2834
|
-
}
|
|
2835
|
-
async function expire(key, seconds) {
|
|
2836
|
-
const result = await request("POST", "/expire", {
|
|
2837
|
-
key,
|
|
2838
|
-
seconds
|
|
2839
|
-
});
|
|
2840
|
-
return result.success;
|
|
2841
|
-
}
|
|
2842
|
-
async function ratelimit(key, options2) {
|
|
2843
|
-
return request("POST", "/ratelimit", {
|
|
2844
|
-
key,
|
|
2845
|
-
...options2
|
|
2846
|
-
});
|
|
2847
|
-
}
|
|
2848
|
-
async function hset(key, fields) {
|
|
2849
|
-
const result = await request("POST", "/hset", {
|
|
2850
|
-
key,
|
|
2851
|
-
fields
|
|
2852
|
-
});
|
|
2853
|
-
return result.created;
|
|
2854
|
-
}
|
|
2855
|
-
async function hget(key, field) {
|
|
2856
|
-
const result = await request("POST", "/hget", {
|
|
2857
|
-
key,
|
|
2858
|
-
field
|
|
2859
|
-
});
|
|
2860
|
-
return result.value;
|
|
2861
|
-
}
|
|
2862
|
-
async function hgetall(key) {
|
|
2863
|
-
const result = await request("POST", "/hgetall", { key });
|
|
2864
|
-
return result.fields;
|
|
2865
|
-
}
|
|
2866
|
-
async function lpush(key, ...values) {
|
|
2867
|
-
const result = await request("POST", "/lpush", {
|
|
2868
|
-
key,
|
|
2869
|
-
values
|
|
2870
|
-
});
|
|
2871
|
-
return result.length;
|
|
2872
|
-
}
|
|
2873
|
-
async function lrange(key, start = 0, stop = -1) {
|
|
2874
|
-
const result = await request("POST", "/lrange", {
|
|
2875
|
-
key,
|
|
2876
|
-
start,
|
|
2877
|
-
stop
|
|
2878
|
-
});
|
|
2879
|
-
return result.values;
|
|
2880
|
-
}
|
|
2881
|
-
async function zadd(key, ...members) {
|
|
2882
|
-
const result = await request("POST", "/zadd", {
|
|
2883
|
-
key,
|
|
2884
|
-
members
|
|
2885
|
-
});
|
|
2886
|
-
return result.added;
|
|
2887
|
-
}
|
|
2888
|
-
async function zrange(key, start = 0, stop = 9, options2) {
|
|
2889
|
-
const result = await request("POST", "/zrange", {
|
|
2890
|
-
key,
|
|
2891
|
-
start,
|
|
2892
|
-
stop,
|
|
2893
|
-
withScores: options2?.withScores ?? false,
|
|
2894
|
-
rev: options2?.rev ?? false
|
|
2895
|
-
});
|
|
2896
|
-
return result.members;
|
|
2897
|
-
}
|
|
2898
|
-
return {
|
|
2899
|
-
get,
|
|
2900
|
-
set,
|
|
2901
|
-
del,
|
|
2902
|
-
exists,
|
|
2903
|
-
mget,
|
|
2904
|
-
mset,
|
|
2905
|
-
incr,
|
|
2906
|
-
expire,
|
|
2907
|
-
ratelimit,
|
|
2908
|
-
hset,
|
|
2909
|
-
hget,
|
|
2910
|
-
hgetall,
|
|
2911
|
-
lpush,
|
|
2912
|
-
lrange,
|
|
2913
|
-
zadd,
|
|
2914
|
-
zrange
|
|
2915
|
-
};
|
|
2916
|
-
}
|
|
2917
|
-
var defaultClient2 = null;
|
|
2918
|
-
function getKv() {
|
|
2919
|
-
if (!defaultClient2) {
|
|
2920
|
-
defaultClient2 = createKv();
|
|
2921
|
-
}
|
|
2922
|
-
return defaultClient2;
|
|
2923
|
-
}
|
|
2924
|
-
|
|
2925
|
-
// src/server/streams.ts
|
|
2926
|
-
function createStreams(options = {}) {
|
|
2927
|
-
const baseURL = (options.platformUrl || `https://${DEFAULT_SDK_API_HOST}`).trim();
|
|
2928
|
-
const rawApiKey = options.secretKey || process.env.SYLPHX_SECRET_KEY;
|
|
2929
|
-
const apiKey = validateAndSanitizeSecretKey(rawApiKey);
|
|
2930
|
-
const headers = {
|
|
2931
|
-
"Content-Type": "application/json",
|
|
2932
|
-
"x-app-secret": apiKey
|
|
2933
|
-
};
|
|
2934
|
-
async function emit(channel, event, data) {
|
|
2935
|
-
const response = await fetch(`${baseURL}${SDK_API_PATH}/realtime/emit`, {
|
|
2936
|
-
method: "POST",
|
|
2937
|
-
headers,
|
|
2938
|
-
body: JSON.stringify({ channel, event, data })
|
|
2939
|
-
});
|
|
2940
|
-
if (!response.ok) {
|
|
2941
|
-
const error = await response.json().catch(() => ({ error: "Emit failed" }));
|
|
2942
|
-
throw new Error(typeof error.error === "string" ? error.error : "Emit failed");
|
|
2943
|
-
}
|
|
2944
|
-
const result = await response.json();
|
|
2945
|
-
return result.id;
|
|
2946
|
-
}
|
|
2947
|
-
async function history(channel, options2) {
|
|
2948
|
-
const response = await fetch(`${baseURL}${SDK_API_PATH}/realtime/history`, {
|
|
2949
|
-
method: "POST",
|
|
2950
|
-
headers,
|
|
2951
|
-
body: JSON.stringify({
|
|
2952
|
-
channel,
|
|
2953
|
-
start: options2?.start,
|
|
2954
|
-
end: options2?.end,
|
|
2955
|
-
limit: options2?.limit
|
|
2956
|
-
})
|
|
2957
|
-
});
|
|
2958
|
-
if (!response.ok) {
|
|
2959
|
-
const error = await response.json().catch(() => ({ error: "History fetch failed" }));
|
|
2960
|
-
throw new Error(typeof error.error === "string" ? error.error : "History fetch failed");
|
|
2961
|
-
}
|
|
2962
|
-
const result = await response.json();
|
|
2963
|
-
return result.messages;
|
|
2964
|
-
}
|
|
2965
|
-
function channelHelper(name) {
|
|
2966
|
-
return {
|
|
2967
|
-
emit: (event, data) => emit(name, event, data),
|
|
2968
|
-
history: (options2) => history(name, options2)
|
|
2969
|
-
};
|
|
2970
|
-
}
|
|
2971
|
-
return {
|
|
2972
|
-
emit,
|
|
2973
|
-
history,
|
|
2974
|
-
channel: channelHelper
|
|
2975
|
-
};
|
|
2976
|
-
}
|
|
2977
|
-
var defaultClient3 = null;
|
|
2978
|
-
function getStreams() {
|
|
2979
|
-
if (!defaultClient3) {
|
|
2980
|
-
defaultClient3 = createStreams();
|
|
2981
|
-
}
|
|
2982
|
-
return defaultClient3;
|
|
2983
|
-
}
|
|
2984
|
-
|
|
2985
|
-
// src/server/index.ts
|
|
2986
|
-
function createServerRestClient(config) {
|
|
2987
|
-
const secretKey = validateAndSanitizeSecretKey(config.secretKey);
|
|
2988
|
-
return createRestClient({
|
|
2989
|
-
secretKey,
|
|
2990
|
-
platformUrl: config.platformUrl?.trim()
|
|
2991
|
-
});
|
|
2992
|
-
}
|
|
2993
|
-
function createAuthenticatedServerClient(config, accessToken) {
|
|
2994
|
-
return createDynamicRestClient({
|
|
2995
|
-
secretKey: config.secretKey,
|
|
2996
|
-
platformUrl: config.platformUrl,
|
|
2997
|
-
getAccessToken: () => accessToken
|
|
2998
|
-
});
|
|
2999
|
-
}
|
|
3000
|
-
function isJwksResponse(data) {
|
|
3001
|
-
return typeof data === "object" && data !== null && "keys" in data && Array.isArray(data.keys);
|
|
3002
|
-
}
|
|
3003
|
-
function isAccessTokenPayload(payload) {
|
|
3004
|
-
return typeof payload.sub === "string" && typeof payload.email === "string" && typeof payload.app_id === "string" && typeof payload.iat === "number" && typeof payload.exp === "number";
|
|
3005
|
-
}
|
|
3006
|
-
var jwksCache = null;
|
|
3007
|
-
function resetJwksCache() {
|
|
3008
|
-
jwksCache = null;
|
|
3009
|
-
}
|
|
3010
|
-
async function getJwks(platformUrl = `https://${DEFAULT_SDK_API_HOST}`) {
|
|
3011
|
-
const now = Date.now();
|
|
3012
|
-
if (jwksCache && jwksCache.expiresAt > now) {
|
|
3013
|
-
return jwksCache.keys;
|
|
3014
|
-
}
|
|
3015
|
-
const response = await fetch(`${platformUrl}/api/v1/auth/.well-known/jwks.json`);
|
|
3016
|
-
if (!response.ok) {
|
|
3017
|
-
throw new Error("Failed to fetch JWKS");
|
|
3018
|
-
}
|
|
3019
|
-
const data = await response.json();
|
|
3020
|
-
if (!isJwksResponse(data)) {
|
|
3021
|
-
throw new Error("Invalid JWKS response format");
|
|
3022
|
-
}
|
|
3023
|
-
jwksCache = {
|
|
3024
|
-
keys: data.keys,
|
|
3025
|
-
expiresAt: now + JWK_CACHE_TTL_MS
|
|
3026
|
-
// Cache for 1 hour
|
|
3027
|
-
};
|
|
3028
|
-
return data.keys;
|
|
3029
|
-
}
|
|
3030
|
-
async function verifyAccessToken(token, options) {
|
|
3031
|
-
const platformUrl = options.platformUrl || `https://${DEFAULT_SDK_API_HOST}`;
|
|
3032
|
-
const keys = await getJwks(platformUrl);
|
|
3033
|
-
if (!keys.length) {
|
|
3034
|
-
throw new Error("No keys in JWKS");
|
|
3035
|
-
}
|
|
3036
|
-
let lastError = null;
|
|
3037
|
-
for (const key of keys) {
|
|
3038
|
-
try {
|
|
3039
|
-
const jwk = await importJWK(key, "RS256");
|
|
3040
|
-
const { payload } = await jwtVerify(token, jwk, {
|
|
3041
|
-
issuer: platformUrl
|
|
3042
|
-
});
|
|
3043
|
-
if (!isAccessTokenPayload(payload)) {
|
|
3044
|
-
throw new Error("Invalid token payload structure");
|
|
3045
|
-
}
|
|
3046
|
-
return {
|
|
3047
|
-
sub: payload.sub,
|
|
3048
|
-
pid: payload.pid,
|
|
3049
|
-
email: payload.email,
|
|
3050
|
-
name: payload.name,
|
|
3051
|
-
picture: payload.picture,
|
|
3052
|
-
email_verified: payload.email_verified,
|
|
3053
|
-
app_id: payload.app_id,
|
|
3054
|
-
role: payload.role,
|
|
3055
|
-
iat: payload.iat,
|
|
3056
|
-
exp: payload.exp
|
|
3057
|
-
};
|
|
3058
|
-
} catch (err) {
|
|
3059
|
-
lastError = err;
|
|
3060
|
-
}
|
|
3061
|
-
}
|
|
3062
|
-
throw lastError || new Error("Token verification failed");
|
|
3063
|
-
}
|
|
3064
|
-
async function verifyWebhook(options) {
|
|
3065
|
-
const { payload, secret, verifyOptions = {} } = options;
|
|
3066
|
-
const { maxAge = WEBHOOK_MAX_AGE_MS, clockSkew = WEBHOOK_CLOCK_SKEW_MS } = verifyOptions;
|
|
3067
|
-
let signatureHex = options.signature ?? null;
|
|
3068
|
-
let timestampStr = options.timestamp ?? null;
|
|
3069
|
-
if (options.signatureHeader) {
|
|
3070
|
-
const tMatch = options.signatureHeader.match(/t=(\d+)/);
|
|
3071
|
-
const vMatch = options.signatureHeader.match(/v1=([a-f0-9]+)/);
|
|
3072
|
-
if (tMatch) timestampStr = tMatch[1];
|
|
3073
|
-
if (vMatch) signatureHex = vMatch[1];
|
|
3074
|
-
}
|
|
3075
|
-
if (!signatureHex) {
|
|
3076
|
-
return { valid: false, error: "Missing signature" };
|
|
3077
|
-
}
|
|
3078
|
-
if (!timestampStr) {
|
|
3079
|
-
return { valid: false, error: "Missing timestamp" };
|
|
3080
|
-
}
|
|
3081
|
-
const webhookTimeSeconds = Number.parseInt(timestampStr, 10);
|
|
3082
|
-
if (Number.isNaN(webhookTimeSeconds)) {
|
|
3083
|
-
return { valid: false, error: "Invalid timestamp format" };
|
|
3084
|
-
}
|
|
3085
|
-
const webhookTimeMs = webhookTimeSeconds * 1e3;
|
|
3086
|
-
const now = Date.now();
|
|
3087
|
-
const age = now - webhookTimeMs;
|
|
3088
|
-
if (age > maxAge) {
|
|
3089
|
-
return { valid: false, error: `Webhook too old: ${age}ms` };
|
|
3090
|
-
}
|
|
3091
|
-
if (age < -clockSkew) {
|
|
3092
|
-
return { valid: false, error: "Webhook timestamp is in the future" };
|
|
3093
|
-
}
|
|
3094
|
-
const signedPayload = `${timestampStr}.${payload}`;
|
|
3095
|
-
try {
|
|
3096
|
-
const expectedSignature = await computeHmacSha256(signedPayload, secret);
|
|
3097
|
-
if (!timingSafeEqual(signatureHex, expectedSignature)) {
|
|
3098
|
-
return { valid: false, error: "Invalid signature" };
|
|
3099
|
-
}
|
|
3100
|
-
const parsedPayload = JSON.parse(payload);
|
|
3101
|
-
return { valid: true, payload: parsedPayload };
|
|
3102
|
-
} catch (error) {
|
|
3103
|
-
return {
|
|
3104
|
-
valid: false,
|
|
3105
|
-
error: error instanceof Error ? error.message : "Verification failed"
|
|
3106
|
-
};
|
|
3107
|
-
}
|
|
3108
|
-
}
|
|
3109
|
-
async function computeHmacSha256(message2, secret) {
|
|
3110
|
-
const encoder2 = new TextEncoder();
|
|
3111
|
-
const keyData = encoder2.encode(secret);
|
|
3112
|
-
const messageData = encoder2.encode(message2);
|
|
3113
|
-
const cryptoKey = await crypto.subtle.importKey(
|
|
3114
|
-
"raw",
|
|
3115
|
-
keyData,
|
|
3116
|
-
{ name: "HMAC", hash: "SHA-256" },
|
|
3117
|
-
false,
|
|
3118
|
-
["sign"]
|
|
3119
|
-
);
|
|
3120
|
-
const signature = await crypto.subtle.sign("HMAC", cryptoKey, messageData);
|
|
3121
|
-
return Buffer.from(signature).toString("hex");
|
|
3122
|
-
}
|
|
3123
|
-
function timingSafeEqual(a, b) {
|
|
3124
|
-
const target = a.length === b.length ? b : a;
|
|
3125
|
-
let result = a.length ^ b.length;
|
|
3126
|
-
for (let i = 0; i < a.length; i++) {
|
|
3127
|
-
result |= a.charCodeAt(i) ^ target.charCodeAt(i);
|
|
3128
|
-
}
|
|
3129
|
-
return result === 0;
|
|
3130
|
-
}
|
|
3131
|
-
function createWebhookHandler(config) {
|
|
3132
|
-
return async (request) => {
|
|
3133
|
-
const signatureHeader = request.headers.get("x-webhook-signature");
|
|
3134
|
-
const body = await request.text();
|
|
3135
|
-
const result = await verifyWebhook({
|
|
3136
|
-
payload: body,
|
|
3137
|
-
signatureHeader,
|
|
3138
|
-
secret: config.secret,
|
|
3139
|
-
verifyOptions: config.verifyOptions
|
|
3140
|
-
});
|
|
3141
|
-
if (!result.valid) {
|
|
3142
|
-
return new Response(JSON.stringify({ error: result.error }), {
|
|
3143
|
-
status: 401,
|
|
3144
|
-
headers: { "Content-Type": "application/json" }
|
|
3145
|
-
});
|
|
3146
|
-
}
|
|
3147
|
-
if (!result.payload) {
|
|
3148
|
-
return new Response(JSON.stringify({ error: "Missing payload" }), {
|
|
3149
|
-
status: 400,
|
|
3150
|
-
headers: { "Content-Type": "application/json" }
|
|
3151
|
-
});
|
|
3152
|
-
}
|
|
3153
|
-
const { event, data } = result.payload;
|
|
3154
|
-
const handler = config.handlers[event];
|
|
3155
|
-
if (!handler) {
|
|
3156
|
-
return new Response(JSON.stringify({ received: true, handled: false }), {
|
|
3157
|
-
status: 200,
|
|
3158
|
-
headers: { "Content-Type": "application/json" }
|
|
3159
|
-
});
|
|
3160
|
-
}
|
|
3161
|
-
try {
|
|
3162
|
-
await handler(data);
|
|
3163
|
-
return new Response(JSON.stringify({ received: true, handled: true }), {
|
|
3164
|
-
status: 200,
|
|
3165
|
-
headers: { "Content-Type": "application/json" }
|
|
3166
|
-
});
|
|
3167
|
-
} catch (error) {
|
|
3168
|
-
return new Response(
|
|
3169
|
-
JSON.stringify({
|
|
3170
|
-
error: "Handler failed",
|
|
3171
|
-
message: error instanceof Error ? error.message : "Unknown error"
|
|
3172
|
-
}),
|
|
3173
|
-
{
|
|
3174
|
-
status: 500,
|
|
3175
|
-
headers: { "Content-Type": "application/json" }
|
|
3176
|
-
}
|
|
3177
|
-
);
|
|
3178
|
-
}
|
|
3179
|
-
};
|
|
3180
|
-
}
|
|
3181
|
-
async function cachedFetch(params) {
|
|
3182
|
-
const { url, headers, fallback, label, revalidate = 60, timeout = 3e3 } = params;
|
|
3183
|
-
try {
|
|
3184
|
-
const controller = new AbortController();
|
|
3185
|
-
const timer = setTimeout(() => controller.abort(), timeout);
|
|
3186
|
-
const response = await fetch(url, {
|
|
3187
|
-
headers,
|
|
3188
|
-
signal: controller.signal,
|
|
3189
|
-
// @ts-expect-error - Next.js extended fetch option
|
|
3190
|
-
next: { revalidate }
|
|
3191
|
-
// Next.js Data Cache with TTL
|
|
3192
|
-
});
|
|
3193
|
-
clearTimeout(timer);
|
|
3194
|
-
if (!response.ok) {
|
|
3195
|
-
console.warn(`[Sylphx] Failed to fetch ${label}:`, response.status);
|
|
3196
|
-
return fallback;
|
|
3197
|
-
}
|
|
3198
|
-
const data = await response.json();
|
|
3199
|
-
return data ?? fallback;
|
|
3200
|
-
} catch (error) {
|
|
3201
|
-
if (error instanceof DOMException && error.name === "AbortError") {
|
|
3202
|
-
console.warn(`[Sylphx] Timeout fetching ${label} (${timeout}ms)`);
|
|
3203
|
-
} else {
|
|
3204
|
-
console.warn(`[Sylphx] Failed to fetch ${label}:`, error);
|
|
3205
|
-
}
|
|
3206
|
-
return fallback;
|
|
3207
|
-
}
|
|
3208
|
-
}
|
|
3209
|
-
function sanitizeOptions(options) {
|
|
3210
|
-
const secretKey = validateAndSanitizeSecretKey(options.secretKey);
|
|
3211
|
-
let platformUrl;
|
|
3212
|
-
if (options.platformUrl) {
|
|
3213
|
-
platformUrl = options.platformUrl.trim();
|
|
3214
|
-
} else {
|
|
3215
|
-
const parts = secretKey.split("_");
|
|
3216
|
-
const ref = parts.length === 4 ? parts[2] : null;
|
|
3217
|
-
platformUrl = ref ? `https://${ref}.${DEFAULT_SDK_API_HOST}` : `https://${DEFAULT_SDK_API_HOST}`;
|
|
3218
|
-
}
|
|
3219
|
-
return { ...options, secretKey, platformUrl };
|
|
3220
|
-
}
|
|
3221
|
-
function sdkHeaders(secretKey) {
|
|
3222
|
-
return { "x-app-secret": secretKey };
|
|
3223
|
-
}
|
|
3224
|
-
async function getOAuthProviders(options) {
|
|
3225
|
-
const data = await fetchOAuthProviders(options);
|
|
3226
|
-
return (data.providers || []).map((p) => p.id);
|
|
3227
|
-
}
|
|
3228
|
-
async function getOAuthProvidersWithInfo(options) {
|
|
3229
|
-
const data = await fetchOAuthProviders(options);
|
|
3230
|
-
return data.providers || [];
|
|
3231
|
-
}
|
|
3232
|
-
async function fetchOAuthProviders(options) {
|
|
3233
|
-
const baseURL = (options.platformUrl ?? `https://${DEFAULT_SDK_API_HOST}`).trim();
|
|
3234
|
-
const appId = validateAndSanitizeAppId(options.appId);
|
|
3235
|
-
return cachedFetch({
|
|
3236
|
-
url: `${baseURL}/api/auth/providers`,
|
|
3237
|
-
headers: { "X-App-Id": appId },
|
|
3238
|
-
fallback: { providers: [] },
|
|
3239
|
-
label: "OAuth providers"
|
|
3240
|
-
});
|
|
3241
|
-
}
|
|
3242
|
-
async function getPlans(options) {
|
|
3243
|
-
const { secretKey, platformUrl = `https://${DEFAULT_SDK_API_HOST}` } = sanitizeOptions(options);
|
|
3244
|
-
return cachedFetch({
|
|
3245
|
-
url: `${platformUrl}${SDK_API_PATH}/billing/plans`,
|
|
3246
|
-
headers: sdkHeaders(secretKey),
|
|
3247
|
-
fallback: [],
|
|
3248
|
-
label: "plans"
|
|
3249
|
-
});
|
|
3250
|
-
}
|
|
3251
|
-
async function getConsentTypes(options) {
|
|
3252
|
-
const { secretKey, platformUrl = `https://${DEFAULT_SDK_API_HOST}` } = sanitizeOptions(options);
|
|
3253
|
-
return cachedFetch({
|
|
3254
|
-
url: `${platformUrl}${SDK_API_PATH}/consent/types`,
|
|
3255
|
-
headers: sdkHeaders(secretKey),
|
|
3256
|
-
fallback: [],
|
|
3257
|
-
label: "consent types"
|
|
3258
|
-
});
|
|
3259
|
-
}
|
|
3260
|
-
async function getFeatureFlags(options) {
|
|
3261
|
-
const { secretKey, platformUrl = `https://${DEFAULT_SDK_API_HOST}` } = sanitizeOptions(options);
|
|
3262
|
-
return cachedFetch({
|
|
3263
|
-
url: `${platformUrl}${SDK_API_PATH}/flags`,
|
|
3264
|
-
headers: sdkHeaders(secretKey),
|
|
3265
|
-
fallback: [],
|
|
3266
|
-
label: "feature flags"
|
|
3267
|
-
});
|
|
3268
|
-
}
|
|
3269
|
-
async function getAppMetadata(options) {
|
|
3270
|
-
const { secretKey, platformUrl = `https://${DEFAULT_SDK_API_HOST}` } = sanitizeOptions(options);
|
|
3271
|
-
return cachedFetch({
|
|
3272
|
-
url: `${platformUrl}${SDK_API_PATH}/app`,
|
|
3273
|
-
headers: sdkHeaders(secretKey),
|
|
3274
|
-
fallback: { id: "", name: "", slug: "" },
|
|
3275
|
-
label: "app metadata"
|
|
3276
|
-
});
|
|
3277
|
-
}
|
|
3278
|
-
async function getAppConfig(options) {
|
|
3279
|
-
const { secretKey, appId } = options;
|
|
3280
|
-
const resolvedPlatformUrl = (() => {
|
|
3281
|
-
if (options.platformUrl) return options.platformUrl.trim();
|
|
3282
|
-
const keyForRef = secretKey || appId;
|
|
3283
|
-
const parts = keyForRef?.split("_") ?? [];
|
|
3284
|
-
const ref = parts.length === 4 ? parts[2] : null;
|
|
3285
|
-
return ref ? `https://${ref}.${DEFAULT_SDK_API_HOST}` : `https://${DEFAULT_SDK_API_HOST}`;
|
|
3286
|
-
})();
|
|
3287
|
-
const [plans, consentTypes, oauthProviders, featureFlags, app] = await Promise.all([
|
|
3288
|
-
getPlans({ secretKey, platformUrl: resolvedPlatformUrl }),
|
|
3289
|
-
getConsentTypes({ secretKey, platformUrl: resolvedPlatformUrl }),
|
|
3290
|
-
getOAuthProvidersWithInfo({ appId, platformUrl: resolvedPlatformUrl }),
|
|
3291
|
-
getFeatureFlags({ secretKey, platformUrl: resolvedPlatformUrl }),
|
|
3292
|
-
getAppMetadata({ secretKey, platformUrl: resolvedPlatformUrl })
|
|
3293
|
-
]);
|
|
3294
|
-
return {
|
|
3295
|
-
plans,
|
|
3296
|
-
consentTypes,
|
|
3297
|
-
oauthProviders,
|
|
3298
|
-
featureFlags,
|
|
3299
|
-
app,
|
|
3300
|
-
fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3301
|
-
};
|
|
3302
|
-
}
|
|
3303
|
-
async function getReferralLeaderboard(options) {
|
|
3304
|
-
const {
|
|
3305
|
-
secretKey,
|
|
3306
|
-
platformUrl = `https://${DEFAULT_SDK_API_HOST}`,
|
|
3307
|
-
limit = 10,
|
|
3308
|
-
period = "all"
|
|
3309
|
-
} = sanitizeOptions(options);
|
|
3310
|
-
const url = new URL(`${platformUrl}${SDK_API_PATH}/referrals/leaderboard`);
|
|
3311
|
-
url.searchParams.set("limit", String(limit));
|
|
3312
|
-
url.searchParams.set("period", period);
|
|
3313
|
-
return cachedFetch({
|
|
3314
|
-
url: url.toString(),
|
|
3315
|
-
headers: sdkHeaders(secretKey),
|
|
3316
|
-
fallback: { entries: [], total: 0, period },
|
|
3317
|
-
label: "referral leaderboard"
|
|
3318
|
-
});
|
|
3319
|
-
}
|
|
3320
|
-
async function getEngagementLeaderboard(options) {
|
|
3321
|
-
const {
|
|
3322
|
-
secretKey,
|
|
3323
|
-
leaderboardId,
|
|
3324
|
-
platformUrl = `https://${DEFAULT_SDK_API_HOST}`,
|
|
3325
|
-
limit = 10
|
|
3326
|
-
} = sanitizeOptions(options);
|
|
3327
|
-
const url = new URL(
|
|
3328
|
-
`${platformUrl}${SDK_API_PATH}/engagement/leaderboards/${encodeURIComponent(leaderboardId)}`
|
|
3329
|
-
);
|
|
3330
|
-
url.searchParams.set("limit", String(limit));
|
|
3331
|
-
return cachedFetch({
|
|
3332
|
-
url: url.toString(),
|
|
3333
|
-
headers: sdkHeaders(secretKey),
|
|
3334
|
-
fallback: {
|
|
3335
|
-
leaderboardId,
|
|
3336
|
-
entries: [],
|
|
3337
|
-
period: "all",
|
|
3338
|
-
resetTime: null,
|
|
3339
|
-
userEntry: null
|
|
3340
|
-
},
|
|
3341
|
-
label: "engagement leaderboard"
|
|
3342
|
-
});
|
|
3343
|
-
}
|
|
3344
|
-
async function getDatabaseConnection(options) {
|
|
3345
|
-
const { secretKey, platformUrl = `https://${DEFAULT_SDK_API_HOST}` } = sanitizeOptions(options);
|
|
3346
|
-
try {
|
|
3347
|
-
const response = await fetch(`${platformUrl}${SDK_API_PATH}/database/connection-string`, {
|
|
3348
|
-
headers: sdkHeaders(secretKey),
|
|
3349
|
-
cache: "no-store"
|
|
3350
|
-
// Always fetch fresh connection string
|
|
3351
|
-
});
|
|
3352
|
-
if (!response.ok) {
|
|
3353
|
-
if (response.status === 404) {
|
|
3354
|
-
return null;
|
|
3355
|
-
}
|
|
3356
|
-
if (response.status === 412) {
|
|
3357
|
-
console.warn("[Sylphx] Database not ready:", await response.text());
|
|
3358
|
-
return null;
|
|
3359
|
-
}
|
|
3360
|
-
console.warn("[Sylphx] Failed to fetch database connection:", response.status);
|
|
3361
|
-
return null;
|
|
3362
|
-
}
|
|
3363
|
-
return await response.json();
|
|
3364
|
-
} catch (error) {
|
|
3365
|
-
console.warn("[Sylphx] Failed to fetch database connection:", error);
|
|
3366
|
-
return null;
|
|
3367
|
-
}
|
|
3368
|
-
}
|
|
3369
|
-
async function getDatabaseStatus(options) {
|
|
3370
|
-
const { secretKey, platformUrl = `https://${DEFAULT_SDK_API_HOST}` } = sanitizeOptions(options);
|
|
3371
|
-
return cachedFetch({
|
|
3372
|
-
url: `${platformUrl}${SDK_API_PATH}/database/status`,
|
|
3373
|
-
headers: sdkHeaders(secretKey),
|
|
3374
|
-
fallback: {
|
|
3375
|
-
status: "not_provisioned",
|
|
3376
|
-
region: null,
|
|
3377
|
-
pgVersion: null,
|
|
3378
|
-
databaseName: null
|
|
3379
|
-
},
|
|
3380
|
-
label: "database status"
|
|
3381
|
-
});
|
|
3382
|
-
}
|
|
3383
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
3384
|
-
0 && (module.exports = {
|
|
3385
|
-
FunctionsClient,
|
|
3386
|
-
InvalidConnectionUrlError,
|
|
3387
|
-
createAI,
|
|
3388
|
-
createAuthenticatedServerClient,
|
|
3389
|
-
createClient,
|
|
3390
|
-
createKv,
|
|
3391
|
-
createServerClient,
|
|
3392
|
-
createServerRestClient,
|
|
3393
|
-
createStreams,
|
|
3394
|
-
createWebhookHandler,
|
|
3395
|
-
decodeUserId,
|
|
3396
|
-
detectEnvironment,
|
|
3397
|
-
detectKeyType,
|
|
3398
|
-
encodeUserId,
|
|
3399
|
-
getAI,
|
|
3400
|
-
getAppConfig,
|
|
3401
|
-
getAppMetadata,
|
|
3402
|
-
getConsentTypes,
|
|
3403
|
-
getCookieNamespace,
|
|
3404
|
-
getDatabaseConnection,
|
|
3405
|
-
getDatabaseStatus,
|
|
3406
|
-
getEngagementLeaderboard,
|
|
3407
|
-
getFeatureFlags,
|
|
3408
|
-
getJwks,
|
|
3409
|
-
getKv,
|
|
3410
|
-
getOAuthProviders,
|
|
3411
|
-
getOAuthProvidersWithInfo,
|
|
3412
|
-
getPlans,
|
|
3413
|
-
getReferralLeaderboard,
|
|
3414
|
-
getStreams,
|
|
3415
|
-
isAppId,
|
|
3416
|
-
isDevelopmentKey,
|
|
3417
|
-
isDevelopmentRuntime,
|
|
3418
|
-
isProductionKey,
|
|
3419
|
-
isSecretKey,
|
|
3420
|
-
resetJwksCache,
|
|
3421
|
-
validateAndSanitizeAppId,
|
|
3422
|
-
validateAndSanitizeKey,
|
|
3423
|
-
validateAndSanitizeSecretKey,
|
|
3424
|
-
validateAppId,
|
|
3425
|
-
validateKey,
|
|
3426
|
-
validateSecretKey,
|
|
3427
|
-
verifyAccessToken,
|
|
3428
|
-
verifyWebhook
|
|
3429
|
-
});
|
|
3430
|
-
//# sourceMappingURL=index.js.map
|