@hot-updater/cloudflare 0.12.7 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -895,6 +895,9 @@ var process_default = _process;
895
895
  // ../../node_modules/.pnpm/wrangler@4.0.0_@cloudflare+workers-types@4.20250317.0/node_modules/wrangler/_virtual_unenv_global_polyfill-@cloudflare-unenv-preset-node-process
896
896
  globalThis.process = process_default;
897
897
 
898
+ // ../../packages/core/dist/index.js
899
+ var NIL_UUID = "00000000-0000-0000-0000-000000000000";
900
+
898
901
  // ../js/dist/index.js
899
902
  var __webpack_modules__ = {
900
903
  "../../node_modules/.pnpm/semver@7.6.3/node_modules/semver/classes/comparator.js": /* @__PURE__ */ __name(function(module, __unused_webpack_exports, __webpack_require__2) {
@@ -1040,7 +1043,7 @@ var __webpack_modules__ = {
1040
1043
  parseRange(range) {
1041
1044
  const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
1042
1045
  const memoKey = memoOpts + ":" + range;
1043
- const cached = cache.get(memoKey);
1046
+ const cached = cache2.get(memoKey);
1044
1047
  if (cached) return cached;
1045
1048
  const loose = this.options.loose;
1046
1049
  const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
@@ -1070,7 +1073,7 @@ var __webpack_modules__ = {
1070
1073
  const result = [
1071
1074
  ...rangeMap.values()
1072
1075
  ];
1073
- cache.set(memoKey, result);
1076
+ cache2.set(memoKey, result);
1074
1077
  return result;
1075
1078
  }
1076
1079
  intersects(range, options) {
@@ -1090,7 +1093,7 @@ var __webpack_modules__ = {
1090
1093
  }
1091
1094
  module.exports = Range;
1092
1095
  const LRU = __webpack_require__2("../../node_modules/.pnpm/semver@7.6.3/node_modules/semver/internal/lrucache.js");
1093
- const cache = new LRU();
1096
+ const cache2 = new LRU();
1094
1097
  const parseOptions = __webpack_require__2("../../node_modules/.pnpm/semver@7.6.3/node_modules/semver/internal/parse-options.js");
1095
1098
  const Comparator = __webpack_require__2("../../node_modules/.pnpm/semver@7.6.3/node_modules/semver/classes/comparator.js");
1096
1099
  const debug3 = __webpack_require__2("../../node_modules/.pnpm/semver@7.6.3/node_modules/semver/internal/debug.js");
@@ -2265,131 +2268,3017 @@ var filterCompatibleAppVersions = /* @__PURE__ */ __name((targetAppVersionList,
2265
2268
  const compatibleAppVersionList = targetAppVersionList.filter((version2) => semverSatisfies(version2, currentVersion));
2266
2269
  return compatibleAppVersionList.sort((a, b) => b.localeCompare(a));
2267
2270
  }, "filterCompatibleAppVersions");
2268
-
2269
- // worker/src/getUpdateInfo.ts
2270
- var getUpdateInfo = /* @__PURE__ */ __name(async (DB, {
2271
- platform: platform2,
2272
- appVersion,
2273
- bundleId
2274
- }) => {
2275
- const appVersionList = await DB.prepare(
2276
- /* sql */
2277
- `
2278
- SELECT
2279
- target_app_version
2280
- FROM bundles
2281
- WHERE platform = ?
2282
- GROUP BY target_app_version
2283
- `
2284
- ).bind(platform2).all();
2285
- const targetAppVersionList = filterCompatibleAppVersions(
2286
- appVersionList.results.map((group3) => group3.target_app_version),
2287
- appVersion
2288
- );
2289
- const sql = (
2290
- /* sql */
2291
- `
2292
- WITH input AS (
2293
- SELECT
2294
- ? AS app_platform, -- \uC608: 'ios' \uB610\uB294 'android'
2295
- ? AS app_version, -- \uC608: '1.2.3'
2296
- ? AS bundle_id, -- \uD604\uC7AC \uBC88\uB4E4 ID (\uBB38\uC790\uC5F4)
2297
- '00000000-0000-0000-0000-000000000000' AS nil_uuid
2298
- ),
2299
- update_candidate AS (
2300
- SELECT
2301
- b.id,
2302
- b.should_force_update,
2303
- b.file_url,
2304
- b.file_hash,
2305
- 'UPDATE' AS status
2306
- FROM bundles b, input
2307
- WHERE b.enabled = 1
2308
- AND b.platform = input.app_platform
2309
- AND b.id >= input.bundle_id
2310
- AND b.target_app_version IN (${targetAppVersionList.map((version2) => `'${version2}'`).join(",")})
2311
- ORDER BY b.id DESC
2312
- LIMIT 1
2313
- ),
2314
- rollback_candidate AS (
2315
- SELECT
2316
- b.id,
2317
- 1 AS should_force_update,
2318
- b.file_url,
2319
- b.file_hash,
2320
- 'ROLLBACK' AS status
2321
- FROM bundles b, input
2322
- WHERE b.enabled = 1
2323
- AND b.platform = input.app_platform
2324
- AND b.id < input.bundle_id
2325
- ORDER BY b.id DESC
2326
- LIMIT 1
2327
- ),
2328
- final_result AS (
2329
- SELECT * FROM update_candidate
2330
- UNION ALL
2331
- SELECT * FROM rollback_candidate
2332
- WHERE NOT EXISTS (SELECT 1 FROM update_candidate)
2333
- )
2334
- SELECT id, should_force_update, file_url, file_hash, status
2335
- FROM final_result, input
2336
- WHERE id <> bundle_id
2337
-
2338
- UNION ALL
2339
-
2340
- SELECT
2341
- nil_uuid AS id,
2342
- 1 AS should_force_update,
2343
- NULL AS file_url,
2344
- NULL AS file_hash,
2345
- 'ROLLBACK' AS status
2346
- FROM input
2347
- WHERE (SELECT COUNT(*) FROM final_result) = 0
2348
- AND bundle_id <> nil_uuid;
2349
- `
2350
- );
2351
- const result = await DB.prepare(sql).bind(platform2, appVersion, bundleId).first();
2352
- if (!result) {
2353
- return null;
2271
+ var encoder = new TextEncoder();
2272
+ var decoder = new TextDecoder();
2273
+ function concat(...buffers) {
2274
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
2275
+ const buf = new Uint8Array(size);
2276
+ let i = 0;
2277
+ for (const buffer of buffers) {
2278
+ buf.set(buffer, i);
2279
+ i += buffer.length;
2280
+ }
2281
+ return buf;
2282
+ }
2283
+ __name(concat, "concat");
2284
+ function encodeBase64(input) {
2285
+ if (Uint8Array.prototype.toBase64) return input.toBase64();
2286
+ const CHUNK_SIZE = 32768;
2287
+ const arr = [];
2288
+ for (let i = 0; i < input.length; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
2289
+ return btoa(arr.join(""));
2290
+ }
2291
+ __name(encodeBase64, "encodeBase64");
2292
+ function decodeBase64(encoded) {
2293
+ if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded);
2294
+ const binary = atob(encoded);
2295
+ const bytes = new Uint8Array(binary.length);
2296
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
2297
+ return bytes;
2298
+ }
2299
+ __name(decodeBase64, "decodeBase64");
2300
+ function decode(input) {
2301
+ if (Uint8Array.fromBase64) return Uint8Array.fromBase64("string" == typeof input ? input : decoder.decode(input), {
2302
+ alphabet: "base64url"
2303
+ });
2304
+ let encoded = input;
2305
+ if (encoded instanceof Uint8Array) encoded = decoder.decode(encoded);
2306
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
2307
+ try {
2308
+ return decodeBase64(encoded);
2309
+ } catch {
2310
+ throw new TypeError("The input to be decoded is not correctly encoded.");
2311
+ }
2312
+ }
2313
+ __name(decode, "decode");
2314
+ function encode(input) {
2315
+ let unencoded = input;
2316
+ if ("string" == typeof unencoded) unencoded = encoder.encode(unencoded);
2317
+ if (Uint8Array.prototype.toBase64) return unencoded.toBase64({
2318
+ alphabet: "base64url",
2319
+ omitPadding: true
2320
+ });
2321
+ return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
2322
+ }
2323
+ __name(encode, "encode");
2324
+ var JOSEError = class extends Error {
2325
+ static {
2326
+ __name(this, "JOSEError");
2327
+ }
2328
+ static code = "ERR_JOSE_GENERIC";
2329
+ code = "ERR_JOSE_GENERIC";
2330
+ constructor(message, options) {
2331
+ super(message, options);
2332
+ this.name = this.constructor.name;
2333
+ Error.captureStackTrace?.(this, this.constructor);
2334
+ }
2335
+ };
2336
+ var JWTClaimValidationFailed = class extends JOSEError {
2337
+ static {
2338
+ __name(this, "JWTClaimValidationFailed");
2339
+ }
2340
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
2341
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
2342
+ claim;
2343
+ reason;
2344
+ payload;
2345
+ constructor(message, payload, claim = "unspecified", reason = "unspecified") {
2346
+ super(message, {
2347
+ cause: {
2348
+ claim,
2349
+ reason,
2350
+ payload
2351
+ }
2352
+ });
2353
+ this.claim = claim;
2354
+ this.reason = reason;
2355
+ this.payload = payload;
2356
+ }
2357
+ };
2358
+ var JWTExpired = class extends JOSEError {
2359
+ static {
2360
+ __name(this, "JWTExpired");
2361
+ }
2362
+ static code = "ERR_JWT_EXPIRED";
2363
+ code = "ERR_JWT_EXPIRED";
2364
+ claim;
2365
+ reason;
2366
+ payload;
2367
+ constructor(message, payload, claim = "unspecified", reason = "unspecified") {
2368
+ super(message, {
2369
+ cause: {
2370
+ claim,
2371
+ reason,
2372
+ payload
2373
+ }
2374
+ });
2375
+ this.claim = claim;
2376
+ this.reason = reason;
2377
+ this.payload = payload;
2378
+ }
2379
+ };
2380
+ var JOSEAlgNotAllowed = class extends JOSEError {
2381
+ static {
2382
+ __name(this, "JOSEAlgNotAllowed");
2383
+ }
2384
+ static code = "ERR_JOSE_ALG_NOT_ALLOWED";
2385
+ code = "ERR_JOSE_ALG_NOT_ALLOWED";
2386
+ };
2387
+ var JOSENotSupported = class extends JOSEError {
2388
+ static {
2389
+ __name(this, "JOSENotSupported");
2390
+ }
2391
+ static code = "ERR_JOSE_NOT_SUPPORTED";
2392
+ code = "ERR_JOSE_NOT_SUPPORTED";
2393
+ };
2394
+ var JWSInvalid = class extends JOSEError {
2395
+ static {
2396
+ __name(this, "JWSInvalid");
2397
+ }
2398
+ static code = "ERR_JWS_INVALID";
2399
+ code = "ERR_JWS_INVALID";
2400
+ };
2401
+ var JWTInvalid = class extends JOSEError {
2402
+ static {
2403
+ __name(this, "JWTInvalid");
2404
+ }
2405
+ static code = "ERR_JWT_INVALID";
2406
+ code = "ERR_JWT_INVALID";
2407
+ };
2408
+ var JWSSignatureVerificationFailed = class extends JOSEError {
2409
+ static {
2410
+ __name(this, "JWSSignatureVerificationFailed");
2411
+ }
2412
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
2413
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
2414
+ constructor(message = "signature verification failed", options) {
2415
+ super(message, options);
2416
+ }
2417
+ };
2418
+ var subtle_dsa = /* @__PURE__ */ __name((alg, algorithm) => {
2419
+ const hash = `SHA-${alg.slice(-3)}`;
2420
+ switch (alg) {
2421
+ case "HS256":
2422
+ case "HS384":
2423
+ case "HS512":
2424
+ return {
2425
+ hash,
2426
+ name: "HMAC"
2427
+ };
2428
+ case "PS256":
2429
+ case "PS384":
2430
+ case "PS512":
2431
+ return {
2432
+ hash,
2433
+ name: "RSA-PSS",
2434
+ saltLength: parseInt(alg.slice(-3), 10) >> 3
2435
+ };
2436
+ case "RS256":
2437
+ case "RS384":
2438
+ case "RS512":
2439
+ return {
2440
+ hash,
2441
+ name: "RSASSA-PKCS1-v1_5"
2442
+ };
2443
+ case "ES256":
2444
+ case "ES384":
2445
+ case "ES512":
2446
+ return {
2447
+ hash,
2448
+ name: "ECDSA",
2449
+ namedCurve: algorithm.namedCurve
2450
+ };
2451
+ case "Ed25519":
2452
+ case "EdDSA":
2453
+ return {
2454
+ name: "Ed25519"
2455
+ };
2456
+ default:
2457
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
2458
+ }
2459
+ }, "subtle_dsa");
2460
+ var check_key_length = /* @__PURE__ */ __name((alg, key) => {
2461
+ if (alg.startsWith("RS") || alg.startsWith("PS")) {
2462
+ const { modulusLength } = key.algorithm;
2463
+ if ("number" != typeof modulusLength || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
2464
+ }
2465
+ }, "check_key_length");
2466
+ function unusable(name, prop = "algorithm.name") {
2467
+ return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
2468
+ }
2469
+ __name(unusable, "unusable");
2470
+ function isAlgorithm(algorithm, name) {
2471
+ return algorithm.name === name;
2472
+ }
2473
+ __name(isAlgorithm, "isAlgorithm");
2474
+ function getHashLength(hash) {
2475
+ return parseInt(hash.name.slice(4), 10);
2476
+ }
2477
+ __name(getHashLength, "getHashLength");
2478
+ function getNamedCurve(alg) {
2479
+ switch (alg) {
2480
+ case "ES256":
2481
+ return "P-256";
2482
+ case "ES384":
2483
+ return "P-384";
2484
+ case "ES512":
2485
+ return "P-521";
2486
+ default:
2487
+ throw new Error("unreachable");
2488
+ }
2489
+ }
2490
+ __name(getNamedCurve, "getNamedCurve");
2491
+ function checkUsage(key, usage) {
2492
+ if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
2493
+ }
2494
+ __name(checkUsage, "checkUsage");
2495
+ function checkSigCryptoKey(key, alg, usage) {
2496
+ switch (alg) {
2497
+ case "HS256":
2498
+ case "HS384":
2499
+ case "HS512": {
2500
+ if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC");
2501
+ const expected = parseInt(alg.slice(2), 10);
2502
+ const actual = getHashLength(key.algorithm.hash);
2503
+ if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
2504
+ break;
2505
+ }
2506
+ case "RS256":
2507
+ case "RS384":
2508
+ case "RS512": {
2509
+ if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5");
2510
+ const expected = parseInt(alg.slice(2), 10);
2511
+ const actual = getHashLength(key.algorithm.hash);
2512
+ if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
2513
+ break;
2514
+ }
2515
+ case "PS256":
2516
+ case "PS384":
2517
+ case "PS512": {
2518
+ if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS");
2519
+ const expected = parseInt(alg.slice(2), 10);
2520
+ const actual = getHashLength(key.algorithm.hash);
2521
+ if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash");
2522
+ break;
2523
+ }
2524
+ case "Ed25519":
2525
+ case "EdDSA":
2526
+ if (!isAlgorithm(key.algorithm, "Ed25519")) throw unusable("Ed25519");
2527
+ break;
2528
+ case "ES256":
2529
+ case "ES384":
2530
+ case "ES512": {
2531
+ if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA");
2532
+ const expected = getNamedCurve(alg);
2533
+ const actual = key.algorithm.namedCurve;
2534
+ if (actual !== expected) throw unusable(expected, "algorithm.namedCurve");
2535
+ break;
2536
+ }
2537
+ default:
2538
+ throw new TypeError("CryptoKey does not support this operation");
2539
+ }
2540
+ checkUsage(key, usage);
2541
+ }
2542
+ __name(checkSigCryptoKey, "checkSigCryptoKey");
2543
+ function invalid_key_input_message(msg, actual, ...types) {
2544
+ types = types.filter(Boolean);
2545
+ if (types.length > 2) {
2546
+ const last = types.pop();
2547
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
2548
+ } else if (2 === types.length) msg += `one of type ${types[0]} or ${types[1]}.`;
2549
+ else msg += `of type ${types[0]}.`;
2550
+ if (null == actual) msg += ` Received ${actual}`;
2551
+ else if ("function" == typeof actual && actual.name) msg += ` Received function ${actual.name}`;
2552
+ else if ("object" == typeof actual && null != actual) {
2553
+ if (actual.constructor?.name) msg += ` Received an instance of ${actual.constructor.name}`;
2554
+ }
2555
+ return msg;
2556
+ }
2557
+ __name(invalid_key_input_message, "invalid_key_input_message");
2558
+ var invalid_key_input = /* @__PURE__ */ __name((actual, ...types) => invalid_key_input_message("Key must be ", actual, ...types), "invalid_key_input");
2559
+ function withAlg(alg, actual, ...types) {
2560
+ return invalid_key_input_message(`Key for the ${alg} algorithm must be `, actual, ...types);
2561
+ }
2562
+ __name(withAlg, "withAlg");
2563
+ var get_sign_verify_key = /* @__PURE__ */ __name(async (alg, key, usage) => {
2564
+ if (key instanceof Uint8Array) {
2565
+ if (!alg.startsWith("HS")) throw new TypeError(invalid_key_input(key, "CryptoKey", "KeyObject", "JSON Web Key"));
2566
+ return crypto.subtle.importKey("raw", key, {
2567
+ hash: `SHA-${alg.slice(-3)}`,
2568
+ name: "HMAC"
2569
+ }, false, [
2570
+ usage
2571
+ ]);
2572
+ }
2573
+ checkSigCryptoKey(key, alg, usage);
2574
+ return key;
2575
+ }, "get_sign_verify_key");
2576
+ var sign = /* @__PURE__ */ __name(async (alg, key, data) => {
2577
+ const cryptoKey = await get_sign_verify_key(alg, key, "sign");
2578
+ check_key_length(alg, cryptoKey);
2579
+ const signature = await crypto.subtle.sign(subtle_dsa(alg, cryptoKey.algorithm), cryptoKey, data);
2580
+ return new Uint8Array(signature);
2581
+ }, "sign");
2582
+ var is_disjoint = /* @__PURE__ */ __name((...headers) => {
2583
+ const sources = headers.filter(Boolean);
2584
+ if (0 === sources.length || 1 === sources.length) return true;
2585
+ let acc;
2586
+ for (const header of sources) {
2587
+ const parameters = Object.keys(header);
2588
+ if (!acc || 0 === acc.size) {
2589
+ acc = new Set(parameters);
2590
+ continue;
2591
+ }
2592
+ for (const parameter of parameters) {
2593
+ if (acc.has(parameter)) return false;
2594
+ acc.add(parameter);
2595
+ }
2596
+ }
2597
+ return true;
2598
+ }, "is_disjoint");
2599
+ function isCryptoKey(key) {
2600
+ return key?.[Symbol.toStringTag] === "CryptoKey";
2601
+ }
2602
+ __name(isCryptoKey, "isCryptoKey");
2603
+ function isKeyObject(key) {
2604
+ return key?.[Symbol.toStringTag] === "KeyObject";
2605
+ }
2606
+ __name(isKeyObject, "isKeyObject");
2607
+ var is_key_like = /* @__PURE__ */ __name((key) => isCryptoKey(key) || isKeyObject(key), "is_key_like");
2608
+ function isObjectLike(value) {
2609
+ return "object" == typeof value && null !== value;
2610
+ }
2611
+ __name(isObjectLike, "isObjectLike");
2612
+ var is_object = /* @__PURE__ */ __name((input) => {
2613
+ if (!isObjectLike(input) || "[object Object]" !== Object.prototype.toString.call(input)) return false;
2614
+ if (null === Object.getPrototypeOf(input)) return true;
2615
+ let proto = input;
2616
+ while (null !== Object.getPrototypeOf(proto)) proto = Object.getPrototypeOf(proto);
2617
+ return Object.getPrototypeOf(input) === proto;
2618
+ }, "is_object");
2619
+ function isJWK(key) {
2620
+ return is_object(key) && "string" == typeof key.kty;
2621
+ }
2622
+ __name(isJWK, "isJWK");
2623
+ function isPrivateJWK(key) {
2624
+ return "oct" !== key.kty && "string" == typeof key.d;
2625
+ }
2626
+ __name(isPrivateJWK, "isPrivateJWK");
2627
+ function isPublicJWK(key) {
2628
+ return "oct" !== key.kty && void 0 === key.d;
2629
+ }
2630
+ __name(isPublicJWK, "isPublicJWK");
2631
+ function isSecretJWK(key) {
2632
+ return "oct" === key.kty && "string" == typeof key.k;
2633
+ }
2634
+ __name(isSecretJWK, "isSecretJWK");
2635
+ var tag = /* @__PURE__ */ __name((key) => key?.[Symbol.toStringTag], "tag");
2636
+ var jwkMatchesOp = /* @__PURE__ */ __name((alg, key, usage) => {
2637
+ if (void 0 !== key.use) {
2638
+ let expected;
2639
+ switch (usage) {
2640
+ case "sign":
2641
+ case "verify":
2642
+ expected = "sig";
2643
+ break;
2644
+ case "encrypt":
2645
+ case "decrypt":
2646
+ expected = "enc";
2647
+ break;
2648
+ }
2649
+ if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
2650
+ }
2651
+ if (void 0 !== key.alg && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
2652
+ if (Array.isArray(key.key_ops)) {
2653
+ let expectedKeyOp;
2654
+ switch (true) {
2655
+ case ("sign" === usage || "verify" === usage):
2656
+ case "dir" === alg:
2657
+ case alg.includes("CBC-HS"):
2658
+ expectedKeyOp = usage;
2659
+ break;
2660
+ case alg.startsWith("PBES2"):
2661
+ expectedKeyOp = "deriveBits";
2662
+ break;
2663
+ case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
2664
+ expectedKeyOp = !alg.includes("GCM") && alg.endsWith("KW") ? "encrypt" === usage ? "wrapKey" : "unwrapKey" : usage;
2665
+ break;
2666
+ case ("encrypt" === usage && alg.startsWith("RSA")):
2667
+ expectedKeyOp = "wrapKey";
2668
+ break;
2669
+ case "decrypt" === usage:
2670
+ expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
2671
+ break;
2672
+ }
2673
+ if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
2674
+ }
2675
+ return true;
2676
+ }, "jwkMatchesOp");
2677
+ var symmetricTypeCheck = /* @__PURE__ */ __name((alg, key, usage) => {
2678
+ if (key instanceof Uint8Array) return;
2679
+ if (isJWK(key)) {
2680
+ if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return;
2681
+ 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');
2682
+ }
2683
+ if (!is_key_like(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
2684
+ if ("secret" !== key.type) throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
2685
+ }, "symmetricTypeCheck");
2686
+ var asymmetricTypeCheck = /* @__PURE__ */ __name((alg, key, usage) => {
2687
+ if (isJWK(key)) switch (usage) {
2688
+ case "decrypt":
2689
+ case "sign":
2690
+ if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return;
2691
+ throw new TypeError("JSON Web Key for this operation be a private JWK");
2692
+ case "encrypt":
2693
+ case "verify":
2694
+ if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return;
2695
+ throw new TypeError("JSON Web Key for this operation be a public JWK");
2696
+ }
2697
+ if (!is_key_like(key)) throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
2698
+ if ("secret" === key.type) throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
2699
+ if ("public" === key.type) switch (usage) {
2700
+ case "sign":
2701
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
2702
+ case "decrypt":
2703
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
2704
+ default:
2705
+ break;
2706
+ }
2707
+ if ("private" === key.type) switch (usage) {
2708
+ case "verify":
2709
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
2710
+ case "encrypt":
2711
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
2712
+ default:
2713
+ break;
2714
+ }
2715
+ }, "asymmetricTypeCheck");
2716
+ var check_key_type = /* @__PURE__ */ __name((alg, key, usage) => {
2717
+ const symmetric = alg.startsWith("HS") || "dir" === alg || alg.startsWith("PBES2") || /^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(alg) || /^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(alg);
2718
+ if (symmetric) symmetricTypeCheck(alg, key, usage);
2719
+ else asymmetricTypeCheck(alg, key, usage);
2720
+ }, "check_key_type");
2721
+ var validate_crit = /* @__PURE__ */ __name((Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) => {
2722
+ if (void 0 !== joseHeader.crit && protectedHeader?.crit === void 0) throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
2723
+ if (!protectedHeader || void 0 === protectedHeader.crit) return /* @__PURE__ */ new Set();
2724
+ if (!Array.isArray(protectedHeader.crit) || 0 === protectedHeader.crit.length || protectedHeader.crit.some((input) => "string" != typeof input || 0 === input.length)) throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
2725
+ let recognized;
2726
+ recognized = void 0 !== recognizedOption ? new Map([
2727
+ ...Object.entries(recognizedOption),
2728
+ ...recognizedDefault.entries()
2729
+ ]) : recognizedDefault;
2730
+ for (const parameter of protectedHeader.crit) {
2731
+ if (!recognized.has(parameter)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
2732
+ if (void 0 === joseHeader[parameter]) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
2733
+ if (recognized.get(parameter) && void 0 === protectedHeader[parameter]) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
2734
+ }
2735
+ return new Set(protectedHeader.crit);
2736
+ }, "validate_crit");
2737
+ function subtleMapping(jwk) {
2738
+ let algorithm;
2739
+ let keyUsages;
2740
+ switch (jwk.kty) {
2741
+ case "RSA":
2742
+ switch (jwk.alg) {
2743
+ case "PS256":
2744
+ case "PS384":
2745
+ case "PS512":
2746
+ algorithm = {
2747
+ name: "RSA-PSS",
2748
+ hash: `SHA-${jwk.alg.slice(-3)}`
2749
+ };
2750
+ keyUsages = jwk.d ? [
2751
+ "sign"
2752
+ ] : [
2753
+ "verify"
2754
+ ];
2755
+ break;
2756
+ case "RS256":
2757
+ case "RS384":
2758
+ case "RS512":
2759
+ algorithm = {
2760
+ name: "RSASSA-PKCS1-v1_5",
2761
+ hash: `SHA-${jwk.alg.slice(-3)}`
2762
+ };
2763
+ keyUsages = jwk.d ? [
2764
+ "sign"
2765
+ ] : [
2766
+ "verify"
2767
+ ];
2768
+ break;
2769
+ case "RSA-OAEP":
2770
+ case "RSA-OAEP-256":
2771
+ case "RSA-OAEP-384":
2772
+ case "RSA-OAEP-512":
2773
+ algorithm = {
2774
+ name: "RSA-OAEP",
2775
+ hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
2776
+ };
2777
+ keyUsages = jwk.d ? [
2778
+ "decrypt",
2779
+ "unwrapKey"
2780
+ ] : [
2781
+ "encrypt",
2782
+ "wrapKey"
2783
+ ];
2784
+ break;
2785
+ default:
2786
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
2787
+ }
2788
+ break;
2789
+ case "EC":
2790
+ switch (jwk.alg) {
2791
+ case "ES256":
2792
+ algorithm = {
2793
+ name: "ECDSA",
2794
+ namedCurve: "P-256"
2795
+ };
2796
+ keyUsages = jwk.d ? [
2797
+ "sign"
2798
+ ] : [
2799
+ "verify"
2800
+ ];
2801
+ break;
2802
+ case "ES384":
2803
+ algorithm = {
2804
+ name: "ECDSA",
2805
+ namedCurve: "P-384"
2806
+ };
2807
+ keyUsages = jwk.d ? [
2808
+ "sign"
2809
+ ] : [
2810
+ "verify"
2811
+ ];
2812
+ break;
2813
+ case "ES512":
2814
+ algorithm = {
2815
+ name: "ECDSA",
2816
+ namedCurve: "P-521"
2817
+ };
2818
+ keyUsages = jwk.d ? [
2819
+ "sign"
2820
+ ] : [
2821
+ "verify"
2822
+ ];
2823
+ break;
2824
+ case "ECDH-ES":
2825
+ case "ECDH-ES+A128KW":
2826
+ case "ECDH-ES+A192KW":
2827
+ case "ECDH-ES+A256KW":
2828
+ algorithm = {
2829
+ name: "ECDH",
2830
+ namedCurve: jwk.crv
2831
+ };
2832
+ keyUsages = jwk.d ? [
2833
+ "deriveBits"
2834
+ ] : [];
2835
+ break;
2836
+ default:
2837
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
2838
+ }
2839
+ break;
2840
+ case "OKP":
2841
+ switch (jwk.alg) {
2842
+ case "Ed25519":
2843
+ case "EdDSA":
2844
+ algorithm = {
2845
+ name: "Ed25519"
2846
+ };
2847
+ keyUsages = jwk.d ? [
2848
+ "sign"
2849
+ ] : [
2850
+ "verify"
2851
+ ];
2852
+ break;
2853
+ case "ECDH-ES":
2854
+ case "ECDH-ES+A128KW":
2855
+ case "ECDH-ES+A192KW":
2856
+ case "ECDH-ES+A256KW":
2857
+ algorithm = {
2858
+ name: jwk.crv
2859
+ };
2860
+ keyUsages = jwk.d ? [
2861
+ "deriveBits"
2862
+ ] : [];
2863
+ break;
2864
+ default:
2865
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
2866
+ }
2867
+ break;
2868
+ default:
2869
+ throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
2354
2870
  }
2355
2871
  return {
2356
- id: result.id,
2357
- shouldForceUpdate: Boolean(result.should_force_update),
2358
- fileUrl: result.file_url,
2359
- fileHash: result.file_hash,
2360
- status: result.status
2872
+ algorithm,
2873
+ keyUsages
2361
2874
  };
2362
- }, "getUpdateInfo");
2363
-
2364
- // worker/src/index.ts
2365
- var index_default = {
2366
- async fetch(request, env2, ctx) {
2367
- const url = new URL(request.url);
2368
- if (url.pathname !== "/api/check-update") {
2369
- return new Response("Not found", { status: 404 });
2370
- }
2371
- const bundleId = request.headers.get("x-bundle-id");
2372
- const appPlatform = request.headers.get("x-app-platform");
2373
- const appVersion = request.headers.get("x-app-version");
2374
- if (!bundleId || !appPlatform || !appVersion) {
2375
- return new Response(
2376
- JSON.stringify({
2377
- error: "Missing bundleId, appPlatform, or appVersion"
2378
- }),
2379
- { status: 400 }
2380
- );
2381
- }
2382
- const updateInfo = await getUpdateInfo(env2.DB, {
2383
- appVersion,
2384
- bundleId,
2385
- platform: appPlatform
2386
- });
2387
- return new Response(JSON.stringify(updateInfo), {
2388
- headers: { "Content-Type": "application/json" },
2389
- status: 200
2875
+ }
2876
+ __name(subtleMapping, "subtleMapping");
2877
+ var jwk_to_key = /* @__PURE__ */ __name(async (jwk) => {
2878
+ if (!jwk.alg) throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
2879
+ const { algorithm, keyUsages } = subtleMapping(jwk);
2880
+ const keyData = {
2881
+ ...jwk
2882
+ };
2883
+ delete keyData.alg;
2884
+ delete keyData.use;
2885
+ return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? !jwk.d, jwk.key_ops ?? keyUsages);
2886
+ }, "jwk_to_key");
2887
+ var cache;
2888
+ var handleJWK = /* @__PURE__ */ __name(async (key, jwk, alg, freeze = false) => {
2889
+ cache ||= /* @__PURE__ */ new WeakMap();
2890
+ let cached = cache.get(key);
2891
+ if (cached?.[alg]) return cached[alg];
2892
+ const cryptoKey = await jwk_to_key({
2893
+ ...jwk,
2894
+ alg
2895
+ });
2896
+ if (freeze) Object.freeze(key);
2897
+ if (cached) cached[alg] = cryptoKey;
2898
+ else cache.set(key, {
2899
+ [alg]: cryptoKey
2900
+ });
2901
+ return cryptoKey;
2902
+ }, "handleJWK");
2903
+ var handleKeyObject = /* @__PURE__ */ __name((keyObject, alg) => {
2904
+ cache ||= /* @__PURE__ */ new WeakMap();
2905
+ let cached = cache.get(keyObject);
2906
+ if (cached?.[alg]) return cached[alg];
2907
+ const isPublic = "public" === keyObject.type;
2908
+ const extractable = !!isPublic;
2909
+ let cryptoKey;
2910
+ if ("x25519" === keyObject.asymmetricKeyType) {
2911
+ switch (alg) {
2912
+ case "ECDH-ES":
2913
+ case "ECDH-ES+A128KW":
2914
+ case "ECDH-ES+A192KW":
2915
+ case "ECDH-ES+A256KW":
2916
+ break;
2917
+ default:
2918
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
2919
+ }
2920
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : [
2921
+ "deriveBits"
2922
+ ]);
2923
+ }
2924
+ if ("ed25519" === keyObject.asymmetricKeyType) {
2925
+ if ("EdDSA" !== alg && "Ed25519" !== alg) throw new TypeError("given KeyObject instance cannot be used for this algorithm");
2926
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
2927
+ isPublic ? "verify" : "sign"
2928
+ ]);
2929
+ }
2930
+ if ("rsa" === keyObject.asymmetricKeyType) {
2931
+ let hash;
2932
+ switch (alg) {
2933
+ case "RSA-OAEP":
2934
+ hash = "SHA-1";
2935
+ break;
2936
+ case "RS256":
2937
+ case "PS256":
2938
+ case "RSA-OAEP-256":
2939
+ hash = "SHA-256";
2940
+ break;
2941
+ case "RS384":
2942
+ case "PS384":
2943
+ case "RSA-OAEP-384":
2944
+ hash = "SHA-384";
2945
+ break;
2946
+ case "RS512":
2947
+ case "PS512":
2948
+ case "RSA-OAEP-512":
2949
+ hash = "SHA-512";
2950
+ break;
2951
+ default:
2952
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
2953
+ }
2954
+ if (alg.startsWith("RSA-OAEP")) return keyObject.toCryptoKey({
2955
+ name: "RSA-OAEP",
2956
+ hash
2957
+ }, extractable, isPublic ? [
2958
+ "encrypt"
2959
+ ] : [
2960
+ "decrypt"
2961
+ ]);
2962
+ cryptoKey = keyObject.toCryptoKey({
2963
+ name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
2964
+ hash
2965
+ }, extractable, [
2966
+ isPublic ? "verify" : "sign"
2967
+ ]);
2968
+ }
2969
+ if ("ec" === keyObject.asymmetricKeyType) {
2970
+ const nist = /* @__PURE__ */ new Map([
2971
+ [
2972
+ "prime256v1",
2973
+ "P-256"
2974
+ ],
2975
+ [
2976
+ "secp384r1",
2977
+ "P-384"
2978
+ ],
2979
+ [
2980
+ "secp521r1",
2981
+ "P-521"
2982
+ ]
2983
+ ]);
2984
+ const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
2985
+ if (!namedCurve) throw new TypeError("given KeyObject instance cannot be used for this algorithm");
2986
+ if ("ES256" === alg && "P-256" === namedCurve) cryptoKey = keyObject.toCryptoKey({
2987
+ name: "ECDSA",
2988
+ namedCurve
2989
+ }, extractable, [
2990
+ isPublic ? "verify" : "sign"
2991
+ ]);
2992
+ if ("ES384" === alg && "P-384" === namedCurve) cryptoKey = keyObject.toCryptoKey({
2993
+ name: "ECDSA",
2994
+ namedCurve
2995
+ }, extractable, [
2996
+ isPublic ? "verify" : "sign"
2997
+ ]);
2998
+ if ("ES512" === alg && "P-521" === namedCurve) cryptoKey = keyObject.toCryptoKey({
2999
+ name: "ECDSA",
3000
+ namedCurve
3001
+ }, extractable, [
3002
+ isPublic ? "verify" : "sign"
3003
+ ]);
3004
+ if (alg.startsWith("ECDH-ES")) cryptoKey = keyObject.toCryptoKey({
3005
+ name: "ECDH",
3006
+ namedCurve
3007
+ }, extractable, isPublic ? [] : [
3008
+ "deriveBits"
3009
+ ]);
3010
+ }
3011
+ if (!cryptoKey) throw new TypeError("given KeyObject instance cannot be used for this algorithm");
3012
+ if (cached) cached[alg] = cryptoKey;
3013
+ else cache.set(keyObject, {
3014
+ [alg]: cryptoKey
3015
+ });
3016
+ return cryptoKey;
3017
+ }, "handleKeyObject");
3018
+ var normalize_key = /* @__PURE__ */ __name(async (key, alg) => {
3019
+ if (key instanceof Uint8Array) return key;
3020
+ if (isCryptoKey(key)) return key;
3021
+ if (isKeyObject(key)) {
3022
+ if ("secret" === key.type) return key.export();
3023
+ if ("toCryptoKey" in key && "function" == typeof key.toCryptoKey) try {
3024
+ return handleKeyObject(key, alg);
3025
+ } catch (err) {
3026
+ if (err instanceof TypeError) throw err;
3027
+ }
3028
+ let jwk = key.export({
3029
+ format: "jwk"
2390
3030
  });
3031
+ return handleJWK(key, jwk, alg);
3032
+ }
3033
+ if (isJWK(key)) {
3034
+ if (key.k) return decode(key.k);
3035
+ return handleJWK(key, key, alg, true);
3036
+ }
3037
+ throw new Error("unreachable");
3038
+ }, "normalize_key");
3039
+ var FlattenedSign = class {
3040
+ static {
3041
+ __name(this, "FlattenedSign");
3042
+ }
3043
+ #payload;
3044
+ #protectedHeader;
3045
+ #unprotectedHeader;
3046
+ constructor(payload) {
3047
+ if (!(payload instanceof Uint8Array)) throw new TypeError("payload must be an instance of Uint8Array");
3048
+ this.#payload = payload;
3049
+ }
3050
+ setProtectedHeader(protectedHeader) {
3051
+ if (this.#protectedHeader) throw new TypeError("setProtectedHeader can only be called once");
3052
+ this.#protectedHeader = protectedHeader;
3053
+ return this;
3054
+ }
3055
+ setUnprotectedHeader(unprotectedHeader) {
3056
+ if (this.#unprotectedHeader) throw new TypeError("setUnprotectedHeader can only be called once");
3057
+ this.#unprotectedHeader = unprotectedHeader;
3058
+ return this;
3059
+ }
3060
+ async sign(key, options) {
3061
+ if (!this.#protectedHeader && !this.#unprotectedHeader) throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
3062
+ if (!is_disjoint(this.#protectedHeader, this.#unprotectedHeader)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
3063
+ const joseHeader = {
3064
+ ...this.#protectedHeader,
3065
+ ...this.#unprotectedHeader
3066
+ };
3067
+ const extensions = validate_crit(JWSInvalid, /* @__PURE__ */ new Map([
3068
+ [
3069
+ "b64",
3070
+ true
3071
+ ]
3072
+ ]), options?.crit, this.#protectedHeader, joseHeader);
3073
+ let b64 = true;
3074
+ if (extensions.has("b64")) {
3075
+ b64 = this.#protectedHeader.b64;
3076
+ if ("boolean" != typeof b64) throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
3077
+ }
3078
+ const { alg } = joseHeader;
3079
+ if ("string" != typeof alg || !alg) throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
3080
+ check_key_type(alg, key, "sign");
3081
+ let payload = this.#payload;
3082
+ if (b64) payload = encoder.encode(encode(payload));
3083
+ let protectedHeader;
3084
+ protectedHeader = this.#protectedHeader ? encoder.encode(encode(JSON.stringify(this.#protectedHeader))) : encoder.encode("");
3085
+ const data = concat(protectedHeader, encoder.encode("."), payload);
3086
+ const k = await normalize_key(key, alg);
3087
+ const signature = await sign(alg, k, data);
3088
+ const jws = {
3089
+ signature: encode(signature),
3090
+ payload: ""
3091
+ };
3092
+ if (b64) jws.payload = decoder.decode(payload);
3093
+ if (this.#unprotectedHeader) jws.header = this.#unprotectedHeader;
3094
+ if (this.#protectedHeader) jws.protected = decoder.decode(protectedHeader);
3095
+ return jws;
3096
+ }
3097
+ };
3098
+ var CompactSign = class {
3099
+ static {
3100
+ __name(this, "CompactSign");
3101
+ }
3102
+ #flattened;
3103
+ constructor(payload) {
3104
+ this.#flattened = new FlattenedSign(payload);
3105
+ }
3106
+ setProtectedHeader(protectedHeader) {
3107
+ this.#flattened.setProtectedHeader(protectedHeader);
3108
+ return this;
3109
+ }
3110
+ async sign(key, options) {
3111
+ const jws = await this.#flattened.sign(key, options);
3112
+ if (void 0 === jws.payload) throw new TypeError("use the flattened module for creating JWS with b64: false");
3113
+ return `${jws.protected}.${jws.payload}.${jws.signature}`;
3114
+ }
3115
+ };
3116
+ var epoch = /* @__PURE__ */ __name((date) => Math.floor(date.getTime() / 1e3), "epoch");
3117
+ var minute = 60;
3118
+ var hour = 60 * minute;
3119
+ var day = 24 * hour;
3120
+ var week = 7 * day;
3121
+ var year = 365.25 * day;
3122
+ 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;
3123
+ var secs = /* @__PURE__ */ __name((str) => {
3124
+ const matched = REGEX.exec(str);
3125
+ if (!matched || matched[4] && matched[1]) throw new TypeError("Invalid time period format");
3126
+ const value = parseFloat(matched[2]);
3127
+ const unit = matched[3].toLowerCase();
3128
+ let numericDate;
3129
+ switch (unit) {
3130
+ case "sec":
3131
+ case "secs":
3132
+ case "second":
3133
+ case "seconds":
3134
+ case "s":
3135
+ numericDate = Math.round(value);
3136
+ break;
3137
+ case "minute":
3138
+ case "minutes":
3139
+ case "min":
3140
+ case "mins":
3141
+ case "m":
3142
+ numericDate = Math.round(value * minute);
3143
+ break;
3144
+ case "hour":
3145
+ case "hours":
3146
+ case "hr":
3147
+ case "hrs":
3148
+ case "h":
3149
+ numericDate = Math.round(value * hour);
3150
+ break;
3151
+ case "day":
3152
+ case "days":
3153
+ case "d":
3154
+ numericDate = Math.round(value * day);
3155
+ break;
3156
+ case "week":
3157
+ case "weeks":
3158
+ case "w":
3159
+ numericDate = Math.round(value * week);
3160
+ break;
3161
+ default:
3162
+ numericDate = Math.round(value * year);
3163
+ break;
3164
+ }
3165
+ if ("-" === matched[1] || "ago" === matched[4]) return -numericDate;
3166
+ return numericDate;
3167
+ }, "secs");
3168
+ function validateInput(label, input) {
3169
+ if (!Number.isFinite(input)) throw new TypeError(`Invalid ${label} input`);
3170
+ return input;
3171
+ }
3172
+ __name(validateInput, "validateInput");
3173
+ var normalizeTyp = /* @__PURE__ */ __name((value) => value.toLowerCase().replace(/^application\//, ""), "normalizeTyp");
3174
+ var checkAudiencePresence = /* @__PURE__ */ __name((audPayload, audOption) => {
3175
+ if ("string" == typeof audPayload) return audOption.includes(audPayload);
3176
+ if (Array.isArray(audPayload)) return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
3177
+ return false;
3178
+ }, "checkAudiencePresence");
3179
+ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
3180
+ let payload;
3181
+ try {
3182
+ payload = JSON.parse(decoder.decode(encodedPayload));
3183
+ } catch {
3184
+ }
3185
+ if (!is_object(payload)) throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
3186
+ const { typ } = options;
3187
+ if (typ && ("string" != typeof protectedHeader.typ || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed");
3188
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
3189
+ const presenceCheck = [
3190
+ ...requiredClaims
3191
+ ];
3192
+ if (void 0 !== maxTokenAge) presenceCheck.push("iat");
3193
+ if (void 0 !== audience) presenceCheck.push("aud");
3194
+ if (void 0 !== subject) presenceCheck.push("sub");
3195
+ if (void 0 !== issuer) presenceCheck.push("iss");
3196
+ for (const claim of new Set(presenceCheck.reverse())) if (!(claim in payload)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
3197
+ if (issuer && !(Array.isArray(issuer) ? issuer : [
3198
+ issuer
3199
+ ]).includes(payload.iss)) throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed");
3200
+ if (subject && payload.sub !== subject) throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed");
3201
+ if (audience && !checkAudiencePresence(payload.aud, "string" == typeof audience ? [
3202
+ audience
3203
+ ] : audience)) throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed");
3204
+ let tolerance;
3205
+ switch (typeof options.clockTolerance) {
3206
+ case "string":
3207
+ tolerance = secs(options.clockTolerance);
3208
+ break;
3209
+ case "number":
3210
+ tolerance = options.clockTolerance;
3211
+ break;
3212
+ case "undefined":
3213
+ tolerance = 0;
3214
+ break;
3215
+ default:
3216
+ throw new TypeError("Invalid clockTolerance option type");
3217
+ }
3218
+ const { currentDate } = options;
3219
+ const now = epoch(currentDate || /* @__PURE__ */ new Date());
3220
+ if ((void 0 !== payload.iat || maxTokenAge) && "number" != typeof payload.iat) throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid");
3221
+ if (void 0 !== payload.nbf) {
3222
+ if ("number" != typeof payload.nbf) throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid");
3223
+ if (payload.nbf > now + tolerance) throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed");
3224
+ }
3225
+ if (void 0 !== payload.exp) {
3226
+ if ("number" != typeof payload.exp) throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid");
3227
+ if (payload.exp <= now - tolerance) throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed");
3228
+ }
3229
+ if (maxTokenAge) {
3230
+ const age = now - payload.iat;
3231
+ const max = "number" == typeof maxTokenAge ? maxTokenAge : secs(maxTokenAge);
3232
+ if (age - tolerance > max) throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed");
3233
+ if (age < 0 - tolerance) throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed");
3234
+ }
3235
+ return payload;
3236
+ }
3237
+ __name(validateClaimsSet, "validateClaimsSet");
3238
+ var JWTClaimsBuilder = class {
3239
+ static {
3240
+ __name(this, "JWTClaimsBuilder");
3241
+ }
3242
+ #payload;
3243
+ constructor(payload) {
3244
+ if (!is_object(payload)) throw new TypeError("JWT Claims Set MUST be an object");
3245
+ this.#payload = structuredClone(payload);
3246
+ }
3247
+ data() {
3248
+ return encoder.encode(JSON.stringify(this.#payload));
3249
+ }
3250
+ get iss() {
3251
+ return this.#payload.iss;
3252
+ }
3253
+ set iss(value) {
3254
+ this.#payload.iss = value;
3255
+ }
3256
+ get sub() {
3257
+ return this.#payload.sub;
3258
+ }
3259
+ set sub(value) {
3260
+ this.#payload.sub = value;
3261
+ }
3262
+ get aud() {
3263
+ return this.#payload.aud;
3264
+ }
3265
+ set aud(value) {
3266
+ this.#payload.aud = value;
3267
+ }
3268
+ set jti(value) {
3269
+ this.#payload.jti = value;
3270
+ }
3271
+ set nbf(value) {
3272
+ if ("number" == typeof value) this.#payload.nbf = validateInput("setNotBefore", value);
3273
+ else if (value instanceof Date) this.#payload.nbf = validateInput("setNotBefore", epoch(value));
3274
+ else this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value);
3275
+ }
3276
+ set exp(value) {
3277
+ if ("number" == typeof value) this.#payload.exp = validateInput("setExpirationTime", value);
3278
+ else if (value instanceof Date) this.#payload.exp = validateInput("setExpirationTime", epoch(value));
3279
+ else this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value);
3280
+ }
3281
+ set iat(value) {
3282
+ if (void 0 === value) this.#payload.iat = epoch(/* @__PURE__ */ new Date());
3283
+ else if (value instanceof Date) this.#payload.iat = validateInput("setIssuedAt", epoch(value));
3284
+ else if ("string" == typeof value) this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value));
3285
+ else this.#payload.iat = validateInput("setIssuedAt", value);
2391
3286
  }
2392
3287
  };
3288
+ var SignJWT = class {
3289
+ static {
3290
+ __name(this, "SignJWT");
3291
+ }
3292
+ #protectedHeader;
3293
+ #jwt;
3294
+ constructor(payload = {}) {
3295
+ this.#jwt = new JWTClaimsBuilder(payload);
3296
+ }
3297
+ setIssuer(issuer) {
3298
+ this.#jwt.iss = issuer;
3299
+ return this;
3300
+ }
3301
+ setSubject(subject) {
3302
+ this.#jwt.sub = subject;
3303
+ return this;
3304
+ }
3305
+ setAudience(audience) {
3306
+ this.#jwt.aud = audience;
3307
+ return this;
3308
+ }
3309
+ setJti(jwtId) {
3310
+ this.#jwt.jti = jwtId;
3311
+ return this;
3312
+ }
3313
+ setNotBefore(input) {
3314
+ this.#jwt.nbf = input;
3315
+ return this;
3316
+ }
3317
+ setExpirationTime(input) {
3318
+ this.#jwt.exp = input;
3319
+ return this;
3320
+ }
3321
+ setIssuedAt(input) {
3322
+ this.#jwt.iat = input;
3323
+ return this;
3324
+ }
3325
+ setProtectedHeader(protectedHeader) {
3326
+ this.#protectedHeader = protectedHeader;
3327
+ return this;
3328
+ }
3329
+ async sign(key, options) {
3330
+ const sig = new CompactSign(this.#jwt.data());
3331
+ sig.setProtectedHeader(this.#protectedHeader);
3332
+ if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && false === this.#protectedHeader.b64) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
3333
+ return sig.sign(key, options);
3334
+ }
3335
+ };
3336
+ var withJwtSignedUrl = /* @__PURE__ */ __name(async ({ data, reqUrl, jwtSecret }) => {
3337
+ if (!data) return null;
3338
+ if (data.id === NIL_UUID) return {
3339
+ ...data,
3340
+ fileUrl: null
3341
+ };
3342
+ const key = `${data.id}/bundle.zip`;
3343
+ const token = await signToken(key, jwtSecret);
3344
+ const url = new URL(reqUrl);
3345
+ url.pathname = `/${key}`;
3346
+ url.searchParams.set("token", token);
3347
+ return {
3348
+ ...data,
3349
+ fileUrl: url.toString()
3350
+ };
3351
+ }, "withJwtSignedUrl");
3352
+ var signToken = /* @__PURE__ */ __name(async (key, jwtSecret) => {
3353
+ const secretKey = new TextEncoder().encode(jwtSecret);
3354
+ const token = await new SignJWT({
3355
+ key
3356
+ }).setProtectedHeader({
3357
+ alg: "HS256"
3358
+ }).setExpirationTime("60s").sign(secretKey);
3359
+ return token;
3360
+ }, "signToken");
3361
+ var verify = /* @__PURE__ */ __name(async (alg, key, signature, data) => {
3362
+ const cryptoKey = await get_sign_verify_key(alg, key, "verify");
3363
+ check_key_length(alg, cryptoKey);
3364
+ const algorithm = subtle_dsa(alg, cryptoKey.algorithm);
3365
+ try {
3366
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
3367
+ } catch {
3368
+ return false;
3369
+ }
3370
+ }, "verify");
3371
+ var validate_algorithms = /* @__PURE__ */ __name((option, algorithms) => {
3372
+ if (void 0 !== algorithms && (!Array.isArray(algorithms) || algorithms.some((s) => "string" != typeof s))) throw new TypeError(`"${option}" option must be an array of strings`);
3373
+ if (!algorithms) return;
3374
+ return new Set(algorithms);
3375
+ }, "validate_algorithms");
3376
+ async function flattenedVerify(jws, key, options) {
3377
+ if (!is_object(jws)) throw new JWSInvalid("Flattened JWS must be an object");
3378
+ if (void 0 === jws.protected && void 0 === jws.header) throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
3379
+ if (void 0 !== jws.protected && "string" != typeof jws.protected) throw new JWSInvalid("JWS Protected Header incorrect type");
3380
+ if (void 0 === jws.payload) throw new JWSInvalid("JWS Payload missing");
3381
+ if ("string" != typeof jws.signature) throw new JWSInvalid("JWS Signature missing or incorrect type");
3382
+ if (void 0 !== jws.header && !is_object(jws.header)) throw new JWSInvalid("JWS Unprotected Header incorrect type");
3383
+ let parsedProt = {};
3384
+ if (jws.protected) try {
3385
+ const protectedHeader = decode(jws.protected);
3386
+ parsedProt = JSON.parse(decoder.decode(protectedHeader));
3387
+ } catch {
3388
+ throw new JWSInvalid("JWS Protected Header is invalid");
3389
+ }
3390
+ if (!is_disjoint(parsedProt, jws.header)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
3391
+ const joseHeader = {
3392
+ ...parsedProt,
3393
+ ...jws.header
3394
+ };
3395
+ const extensions = validate_crit(JWSInvalid, /* @__PURE__ */ new Map([
3396
+ [
3397
+ "b64",
3398
+ true
3399
+ ]
3400
+ ]), options?.crit, parsedProt, joseHeader);
3401
+ let b64 = true;
3402
+ if (extensions.has("b64")) {
3403
+ b64 = parsedProt.b64;
3404
+ if ("boolean" != typeof b64) throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
3405
+ }
3406
+ const { alg } = joseHeader;
3407
+ if ("string" != typeof alg || !alg) throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
3408
+ const algorithms = options && validate_algorithms("algorithms", options.algorithms);
3409
+ if (algorithms && !algorithms.has(alg)) throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
3410
+ if (b64) {
3411
+ if ("string" != typeof jws.payload) throw new JWSInvalid("JWS Payload must be a string");
3412
+ } else if ("string" != typeof jws.payload && !(jws.payload instanceof Uint8Array)) throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
3413
+ let resolvedKey = false;
3414
+ if ("function" == typeof key) {
3415
+ key = await key(parsedProt, jws);
3416
+ resolvedKey = true;
3417
+ }
3418
+ check_key_type(alg, key, "verify");
3419
+ const data = concat(encoder.encode(jws.protected ?? ""), encoder.encode("."), "string" == typeof jws.payload ? encoder.encode(jws.payload) : jws.payload);
3420
+ let signature;
3421
+ try {
3422
+ signature = decode(jws.signature);
3423
+ } catch {
3424
+ throw new JWSInvalid("Failed to base64url decode the signature");
3425
+ }
3426
+ const k = await normalize_key(key, alg);
3427
+ const verified = await verify(alg, k, signature, data);
3428
+ if (!verified) throw new JWSSignatureVerificationFailed();
3429
+ let payload;
3430
+ if (b64) try {
3431
+ payload = decode(jws.payload);
3432
+ } catch {
3433
+ throw new JWSInvalid("Failed to base64url decode the payload");
3434
+ }
3435
+ else payload = "string" == typeof jws.payload ? encoder.encode(jws.payload) : jws.payload;
3436
+ const result = {
3437
+ payload
3438
+ };
3439
+ if (void 0 !== jws.protected) result.protectedHeader = parsedProt;
3440
+ if (void 0 !== jws.header) result.unprotectedHeader = jws.header;
3441
+ if (resolvedKey) return {
3442
+ ...result,
3443
+ key: k
3444
+ };
3445
+ return result;
3446
+ }
3447
+ __name(flattenedVerify, "flattenedVerify");
3448
+ async function compactVerify(jws, key, options) {
3449
+ if (jws instanceof Uint8Array) jws = decoder.decode(jws);
3450
+ if ("string" != typeof jws) throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
3451
+ const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
3452
+ if (3 !== length) throw new JWSInvalid("Invalid Compact JWS");
3453
+ const verified = await flattenedVerify({
3454
+ payload,
3455
+ protected: protectedHeader,
3456
+ signature
3457
+ }, key, options);
3458
+ const result = {
3459
+ payload: verified.payload,
3460
+ protectedHeader: verified.protectedHeader
3461
+ };
3462
+ if ("function" == typeof key) return {
3463
+ ...result,
3464
+ key: verified.key
3465
+ };
3466
+ return result;
3467
+ }
3468
+ __name(compactVerify, "compactVerify");
3469
+ async function jwtVerify(jwt, key, options) {
3470
+ const verified = await compactVerify(jwt, key, options);
3471
+ if (verified.protectedHeader.crit?.includes("b64") && false === verified.protectedHeader.b64) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
3472
+ const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
3473
+ const result = {
3474
+ payload,
3475
+ protectedHeader: verified.protectedHeader
3476
+ };
3477
+ if ("function" == typeof key) return {
3478
+ ...result,
3479
+ key: verified.key
3480
+ };
3481
+ return result;
3482
+ }
3483
+ __name(jwtVerify, "jwtVerify");
3484
+ var verifyJwtToken = /* @__PURE__ */ __name(async ({ path, token, jwtSecret }) => {
3485
+ const key = path.replace(/^\/+/, "");
3486
+ if (!token) return {
3487
+ valid: false,
3488
+ error: "Missing token"
3489
+ };
3490
+ try {
3491
+ const secretKey = new TextEncoder().encode(jwtSecret);
3492
+ const { payload } = await jwtVerify(token, secretKey);
3493
+ if (!payload || payload.key !== key) return {
3494
+ valid: false,
3495
+ error: "Token does not match requested file"
3496
+ };
3497
+ return {
3498
+ valid: true,
3499
+ key
3500
+ };
3501
+ } catch (error3) {
3502
+ return {
3503
+ valid: false,
3504
+ error: "Invalid or expired token"
3505
+ };
3506
+ }
3507
+ }, "verifyJwtToken");
3508
+ var getFileResponse = /* @__PURE__ */ __name(async ({ key, handler }) => {
3509
+ const object = await handler(key);
3510
+ if (!object) return {
3511
+ status: 404,
3512
+ error: "File not found"
3513
+ };
3514
+ const pathParts = key.split("/");
3515
+ const fileName = pathParts[pathParts.length - 1];
3516
+ const headers = {
3517
+ "Content-Type": object.contentType || "application/octet-stream",
3518
+ "Content-Disposition": `attachment; filename=${fileName}`
3519
+ };
3520
+ return {
3521
+ status: 200,
3522
+ responseHeaders: headers,
3523
+ responseBody: object.body
3524
+ };
3525
+ }, "getFileResponse");
3526
+ var verifyJwtSignedUrl = /* @__PURE__ */ __name(async ({ path, token, jwtSecret, handler }) => {
3527
+ const result = await verifyJwtToken({
3528
+ path,
3529
+ token,
3530
+ jwtSecret
3531
+ });
3532
+ if (!result.valid) {
3533
+ if ("Missing token" === result.error) return {
3534
+ status: 400,
3535
+ error: result.error
3536
+ };
3537
+ return {
3538
+ status: 403,
3539
+ error: result.error || "Unauthorized"
3540
+ };
3541
+ }
3542
+ return getFileResponse({
3543
+ key: result.key,
3544
+ handler
3545
+ });
3546
+ }, "verifyJwtSignedUrl");
3547
+
3548
+ // ../../node_modules/.pnpm/hono@4.6.3/node_modules/hono/dist/utils/body.js
3549
+ var parseBody = /* @__PURE__ */ __name(async (request, options = /* @__PURE__ */ Object.create(null)) => {
3550
+ const { all = false, dot = false } = options;
3551
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
3552
+ const contentType = headers.get("Content-Type");
3553
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
3554
+ return parseFormData(request, { all, dot });
3555
+ }
3556
+ return {};
3557
+ }, "parseBody");
3558
+ async function parseFormData(request, options) {
3559
+ const formData = await request.formData();
3560
+ if (formData) {
3561
+ return convertFormDataToBodyData(formData, options);
3562
+ }
3563
+ return {};
3564
+ }
3565
+ __name(parseFormData, "parseFormData");
3566
+ function convertFormDataToBodyData(formData, options) {
3567
+ const form = /* @__PURE__ */ Object.create(null);
3568
+ formData.forEach((value, key) => {
3569
+ const shouldParseAllValues = options.all || key.endsWith("[]");
3570
+ if (!shouldParseAllValues) {
3571
+ form[key] = value;
3572
+ } else {
3573
+ handleParsingAllValues(form, key, value);
3574
+ }
3575
+ });
3576
+ if (options.dot) {
3577
+ Object.entries(form).forEach(([key, value]) => {
3578
+ const shouldParseDotValues = key.includes(".");
3579
+ if (shouldParseDotValues) {
3580
+ handleParsingNestedValues(form, key, value);
3581
+ delete form[key];
3582
+ }
3583
+ });
3584
+ }
3585
+ return form;
3586
+ }
3587
+ __name(convertFormDataToBodyData, "convertFormDataToBodyData");
3588
+ var handleParsingAllValues = /* @__PURE__ */ __name((form, key, value) => {
3589
+ if (form[key] !== void 0) {
3590
+ if (Array.isArray(form[key])) {
3591
+ ;
3592
+ form[key].push(value);
3593
+ } else {
3594
+ form[key] = [form[key], value];
3595
+ }
3596
+ } else {
3597
+ form[key] = value;
3598
+ }
3599
+ }, "handleParsingAllValues");
3600
+ var handleParsingNestedValues = /* @__PURE__ */ __name((form, key, value) => {
3601
+ let nestedForm = form;
3602
+ const keys = key.split(".");
3603
+ keys.forEach((key2, index) => {
3604
+ if (index === keys.length - 1) {
3605
+ nestedForm[key2] = value;
3606
+ } else {
3607
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
3608
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
3609
+ }
3610
+ nestedForm = nestedForm[key2];
3611
+ }
3612
+ });
3613
+ }, "handleParsingNestedValues");
3614
+
3615
+ // ../../node_modules/.pnpm/hono@4.6.3/node_modules/hono/dist/utils/url.js
3616
+ var splitPath = /* @__PURE__ */ __name((path) => {
3617
+ const paths = path.split("/");
3618
+ if (paths[0] === "") {
3619
+ paths.shift();
3620
+ }
3621
+ return paths;
3622
+ }, "splitPath");
3623
+ var splitRoutingPath = /* @__PURE__ */ __name((routePath) => {
3624
+ const { groups, path } = extractGroupsFromPath(routePath);
3625
+ const paths = splitPath(path);
3626
+ return replaceGroupMarks(paths, groups);
3627
+ }, "splitRoutingPath");
3628
+ var extractGroupsFromPath = /* @__PURE__ */ __name((path) => {
3629
+ const groups = [];
3630
+ path = path.replace(/\{[^}]+\}/g, (match, index) => {
3631
+ const mark = `@${index}`;
3632
+ groups.push([mark, match]);
3633
+ return mark;
3634
+ });
3635
+ return { groups, path };
3636
+ }, "extractGroupsFromPath");
3637
+ var replaceGroupMarks = /* @__PURE__ */ __name((paths, groups) => {
3638
+ for (let i = groups.length - 1; i >= 0; i--) {
3639
+ const [mark] = groups[i];
3640
+ for (let j = paths.length - 1; j >= 0; j--) {
3641
+ if (paths[j].includes(mark)) {
3642
+ paths[j] = paths[j].replace(mark, groups[i][1]);
3643
+ break;
3644
+ }
3645
+ }
3646
+ }
3647
+ return paths;
3648
+ }, "replaceGroupMarks");
3649
+ var patternCache = {};
3650
+ var getPattern = /* @__PURE__ */ __name((label) => {
3651
+ if (label === "*") {
3652
+ return "*";
3653
+ }
3654
+ const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
3655
+ if (match) {
3656
+ if (!patternCache[label]) {
3657
+ if (match[2]) {
3658
+ patternCache[label] = [label, match[1], new RegExp("^" + match[2] + "$")];
3659
+ } else {
3660
+ patternCache[label] = [label, match[1], true];
3661
+ }
3662
+ }
3663
+ return patternCache[label];
3664
+ }
3665
+ return null;
3666
+ }, "getPattern");
3667
+ var tryDecodeURI = /* @__PURE__ */ __name((str) => {
3668
+ try {
3669
+ return decodeURI(str);
3670
+ } catch {
3671
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
3672
+ try {
3673
+ return decodeURI(match);
3674
+ } catch {
3675
+ return match;
3676
+ }
3677
+ });
3678
+ }
3679
+ }, "tryDecodeURI");
3680
+ var getPath = /* @__PURE__ */ __name((request) => {
3681
+ const url = request.url;
3682
+ const start = url.indexOf("/", 8);
3683
+ let i = start;
3684
+ for (; i < url.length; i++) {
3685
+ const charCode = url.charCodeAt(i);
3686
+ if (charCode === 37) {
3687
+ const queryIndex = url.indexOf("?", i);
3688
+ const path = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
3689
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
3690
+ } else if (charCode === 63) {
3691
+ break;
3692
+ }
3693
+ }
3694
+ return url.slice(start, i);
3695
+ }, "getPath");
3696
+ var getPathNoStrict = /* @__PURE__ */ __name((request) => {
3697
+ const result = getPath(request);
3698
+ return result.length > 1 && result[result.length - 1] === "/" ? result.slice(0, -1) : result;
3699
+ }, "getPathNoStrict");
3700
+ var mergePath = /* @__PURE__ */ __name((...paths) => {
3701
+ let p = "";
3702
+ let endsWithSlash = false;
3703
+ for (let path of paths) {
3704
+ if (p[p.length - 1] === "/") {
3705
+ p = p.slice(0, -1);
3706
+ endsWithSlash = true;
3707
+ }
3708
+ if (path[0] !== "/") {
3709
+ path = `/${path}`;
3710
+ }
3711
+ if (path === "/" && endsWithSlash) {
3712
+ p = `${p}/`;
3713
+ } else if (path !== "/") {
3714
+ p = `${p}${path}`;
3715
+ }
3716
+ if (path === "/" && p === "") {
3717
+ p = "/";
3718
+ }
3719
+ }
3720
+ return p;
3721
+ }, "mergePath");
3722
+ var checkOptionalParameter = /* @__PURE__ */ __name((path) => {
3723
+ if (!path.match(/\:.+\?$/)) {
3724
+ return null;
3725
+ }
3726
+ const segments = path.split("/");
3727
+ const results = [];
3728
+ let basePath = "";
3729
+ segments.forEach((segment) => {
3730
+ if (segment !== "" && !/\:/.test(segment)) {
3731
+ basePath += "/" + segment;
3732
+ } else if (/\:/.test(segment)) {
3733
+ if (/\?/.test(segment)) {
3734
+ if (results.length === 0 && basePath === "") {
3735
+ results.push("/");
3736
+ } else {
3737
+ results.push(basePath);
3738
+ }
3739
+ const optionalSegment = segment.replace("?", "");
3740
+ basePath += "/" + optionalSegment;
3741
+ results.push(basePath);
3742
+ } else {
3743
+ basePath += "/" + segment;
3744
+ }
3745
+ }
3746
+ });
3747
+ return results.filter((v, i, a) => a.indexOf(v) === i);
3748
+ }, "checkOptionalParameter");
3749
+ var _decodeURI = /* @__PURE__ */ __name((value) => {
3750
+ if (!/[%+]/.test(value)) {
3751
+ return value;
3752
+ }
3753
+ if (value.indexOf("+") !== -1) {
3754
+ value = value.replace(/\+/g, " ");
3755
+ }
3756
+ return /%/.test(value) ? decodeURIComponent_(value) : value;
3757
+ }, "_decodeURI");
3758
+ var _getQueryParam = /* @__PURE__ */ __name((url, key, multiple) => {
3759
+ let encoded;
3760
+ if (!multiple && key && !/[%+]/.test(key)) {
3761
+ let keyIndex2 = url.indexOf(`?${key}`, 8);
3762
+ if (keyIndex2 === -1) {
3763
+ keyIndex2 = url.indexOf(`&${key}`, 8);
3764
+ }
3765
+ while (keyIndex2 !== -1) {
3766
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
3767
+ if (trailingKeyCode === 61) {
3768
+ const valueIndex = keyIndex2 + key.length + 2;
3769
+ const endIndex = url.indexOf("&", valueIndex);
3770
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
3771
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
3772
+ return "";
3773
+ }
3774
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
3775
+ }
3776
+ encoded = /[%+]/.test(url);
3777
+ if (!encoded) {
3778
+ return void 0;
3779
+ }
3780
+ }
3781
+ const results = {};
3782
+ encoded ??= /[%+]/.test(url);
3783
+ let keyIndex = url.indexOf("?", 8);
3784
+ while (keyIndex !== -1) {
3785
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
3786
+ let valueIndex = url.indexOf("=", keyIndex);
3787
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
3788
+ valueIndex = -1;
3789
+ }
3790
+ let name = url.slice(
3791
+ keyIndex + 1,
3792
+ valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
3793
+ );
3794
+ if (encoded) {
3795
+ name = _decodeURI(name);
3796
+ }
3797
+ keyIndex = nextKeyIndex;
3798
+ if (name === "") {
3799
+ continue;
3800
+ }
3801
+ let value;
3802
+ if (valueIndex === -1) {
3803
+ value = "";
3804
+ } else {
3805
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
3806
+ if (encoded) {
3807
+ value = _decodeURI(value);
3808
+ }
3809
+ }
3810
+ if (multiple) {
3811
+ if (!(results[name] && Array.isArray(results[name]))) {
3812
+ results[name] = [];
3813
+ }
3814
+ ;
3815
+ results[name].push(value);
3816
+ } else {
3817
+ results[name] ??= value;
3818
+ }
3819
+ }
3820
+ return key ? results[key] : results;
3821
+ }, "_getQueryParam");
3822
+ var getQueryParam = _getQueryParam;
3823
+ var getQueryParams = /* @__PURE__ */ __name((url, key) => {
3824
+ return _getQueryParam(url, key, true);
3825
+ }, "getQueryParams");
3826
+ var decodeURIComponent_ = decodeURIComponent;
3827
+
3828
+ // ../../node_modules/.pnpm/hono@4.6.3/node_modules/hono/dist/request.js
3829
+ var HonoRequest = class {
3830
+ static {
3831
+ __name(this, "HonoRequest");
3832
+ }
3833
+ raw;
3834
+ #validatedData;
3835
+ #matchResult;
3836
+ routeIndex = 0;
3837
+ path;
3838
+ bodyCache = {};
3839
+ constructor(request, path = "/", matchResult = [[]]) {
3840
+ this.raw = request;
3841
+ this.path = path;
3842
+ this.#matchResult = matchResult;
3843
+ this.#validatedData = {};
3844
+ }
3845
+ param(key) {
3846
+ return key ? this.getDecodedParam(key) : this.getAllDecodedParams();
3847
+ }
3848
+ getDecodedParam(key) {
3849
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
3850
+ const param = this.getParamValue(paramKey);
3851
+ return param ? /\%/.test(param) ? decodeURIComponent_(param) : param : void 0;
3852
+ }
3853
+ getAllDecodedParams() {
3854
+ const decoded = {};
3855
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
3856
+ for (const key of keys) {
3857
+ const value = this.getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
3858
+ if (value && typeof value === "string") {
3859
+ decoded[key] = /\%/.test(value) ? decodeURIComponent_(value) : value;
3860
+ }
3861
+ }
3862
+ return decoded;
3863
+ }
3864
+ getParamValue(paramKey) {
3865
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
3866
+ }
3867
+ query(key) {
3868
+ return getQueryParam(this.url, key);
3869
+ }
3870
+ queries(key) {
3871
+ return getQueryParams(this.url, key);
3872
+ }
3873
+ header(name) {
3874
+ if (name) {
3875
+ return this.raw.headers.get(name.toLowerCase()) ?? void 0;
3876
+ }
3877
+ const headerData = {};
3878
+ this.raw.headers.forEach((value, key) => {
3879
+ headerData[key] = value;
3880
+ });
3881
+ return headerData;
3882
+ }
3883
+ async parseBody(options) {
3884
+ return this.bodyCache.parsedBody ??= await parseBody(this, options);
3885
+ }
3886
+ cachedBody = /* @__PURE__ */ __name((key) => {
3887
+ const { bodyCache, raw: raw2 } = this;
3888
+ const cachedBody = bodyCache[key];
3889
+ if (cachedBody) {
3890
+ return cachedBody;
3891
+ }
3892
+ const anyCachedKey = Object.keys(bodyCache)[0];
3893
+ if (anyCachedKey) {
3894
+ return bodyCache[anyCachedKey].then((body) => {
3895
+ if (anyCachedKey === "json") {
3896
+ body = JSON.stringify(body);
3897
+ }
3898
+ return new Response(body)[key]();
3899
+ });
3900
+ }
3901
+ return bodyCache[key] = raw2[key]();
3902
+ }, "cachedBody");
3903
+ json() {
3904
+ return this.cachedBody("json");
3905
+ }
3906
+ text() {
3907
+ return this.cachedBody("text");
3908
+ }
3909
+ arrayBuffer() {
3910
+ return this.cachedBody("arrayBuffer");
3911
+ }
3912
+ blob() {
3913
+ return this.cachedBody("blob");
3914
+ }
3915
+ formData() {
3916
+ return this.cachedBody("formData");
3917
+ }
3918
+ addValidatedData(target, data) {
3919
+ this.#validatedData[target] = data;
3920
+ }
3921
+ valid(target) {
3922
+ return this.#validatedData[target];
3923
+ }
3924
+ get url() {
3925
+ return this.raw.url;
3926
+ }
3927
+ get method() {
3928
+ return this.raw.method;
3929
+ }
3930
+ get matchedRoutes() {
3931
+ return this.#matchResult[0].map(([[, route]]) => route);
3932
+ }
3933
+ get routePath() {
3934
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
3935
+ }
3936
+ };
3937
+
3938
+ // ../../node_modules/.pnpm/hono@4.6.3/node_modules/hono/dist/utils/html.js
3939
+ var HtmlEscapedCallbackPhase = {
3940
+ Stringify: 1,
3941
+ BeforeStream: 2,
3942
+ Stream: 3
3943
+ };
3944
+ var raw = /* @__PURE__ */ __name((value, callbacks) => {
3945
+ const escapedString = new String(value);
3946
+ escapedString.isEscaped = true;
3947
+ escapedString.callbacks = callbacks;
3948
+ return escapedString;
3949
+ }, "raw");
3950
+ var resolveCallback = /* @__PURE__ */ __name(async (str, phase, preserveCallbacks, context2, buffer) => {
3951
+ if (typeof str === "object" && !(str instanceof String)) {
3952
+ if (!(str instanceof Promise)) {
3953
+ str = str.toString();
3954
+ }
3955
+ if (str instanceof Promise) {
3956
+ str = await str;
3957
+ }
3958
+ }
3959
+ const callbacks = str.callbacks;
3960
+ if (!callbacks?.length) {
3961
+ return Promise.resolve(str);
3962
+ }
3963
+ if (buffer) {
3964
+ buffer[0] += str;
3965
+ } else {
3966
+ buffer = [str];
3967
+ }
3968
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context: context2 }))).then(
3969
+ (res) => Promise.all(
3970
+ res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context2, buffer))
3971
+ ).then(() => buffer[0])
3972
+ );
3973
+ if (preserveCallbacks) {
3974
+ return raw(await resStr, callbacks);
3975
+ } else {
3976
+ return resStr;
3977
+ }
3978
+ }, "resolveCallback");
3979
+
3980
+ // ../../node_modules/.pnpm/hono@4.6.3/node_modules/hono/dist/context.js
3981
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
3982
+ var setHeaders = /* @__PURE__ */ __name((headers, map = {}) => {
3983
+ Object.entries(map).forEach(([key, value]) => headers.set(key, value));
3984
+ return headers;
3985
+ }, "setHeaders");
3986
+ var Context = class {
3987
+ static {
3988
+ __name(this, "Context");
3989
+ }
3990
+ #rawRequest;
3991
+ #req;
3992
+ env = {};
3993
+ #var;
3994
+ finalized = false;
3995
+ error;
3996
+ #status = 200;
3997
+ #executionCtx;
3998
+ #headers;
3999
+ #preparedHeaders;
4000
+ #res;
4001
+ #isFresh = true;
4002
+ #layout;
4003
+ #renderer;
4004
+ #notFoundHandler;
4005
+ #matchResult;
4006
+ #path;
4007
+ constructor(req, options) {
4008
+ this.#rawRequest = req;
4009
+ if (options) {
4010
+ this.#executionCtx = options.executionCtx;
4011
+ this.env = options.env;
4012
+ this.#notFoundHandler = options.notFoundHandler;
4013
+ this.#path = options.path;
4014
+ this.#matchResult = options.matchResult;
4015
+ }
4016
+ }
4017
+ get req() {
4018
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
4019
+ return this.#req;
4020
+ }
4021
+ get event() {
4022
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
4023
+ return this.#executionCtx;
4024
+ } else {
4025
+ throw Error("This context has no FetchEvent");
4026
+ }
4027
+ }
4028
+ get executionCtx() {
4029
+ if (this.#executionCtx) {
4030
+ return this.#executionCtx;
4031
+ } else {
4032
+ throw Error("This context has no ExecutionContext");
4033
+ }
4034
+ }
4035
+ get res() {
4036
+ this.#isFresh = false;
4037
+ return this.#res ||= new Response("404 Not Found", { status: 404 });
4038
+ }
4039
+ set res(_res) {
4040
+ this.#isFresh = false;
4041
+ if (this.#res && _res) {
4042
+ try {
4043
+ for (const [k, v] of this.#res.headers.entries()) {
4044
+ if (k === "content-type") {
4045
+ continue;
4046
+ }
4047
+ if (k === "set-cookie") {
4048
+ const cookies = this.#res.headers.getSetCookie();
4049
+ _res.headers.delete("set-cookie");
4050
+ for (const cookie of cookies) {
4051
+ _res.headers.append("set-cookie", cookie);
4052
+ }
4053
+ } else {
4054
+ _res.headers.set(k, v);
4055
+ }
4056
+ }
4057
+ } catch (e) {
4058
+ if (e instanceof TypeError && e.message.includes("immutable")) {
4059
+ this.res = new Response(_res.body, {
4060
+ headers: _res.headers,
4061
+ status: _res.status
4062
+ });
4063
+ return;
4064
+ } else {
4065
+ throw e;
4066
+ }
4067
+ }
4068
+ }
4069
+ this.#res = _res;
4070
+ this.finalized = true;
4071
+ }
4072
+ render = /* @__PURE__ */ __name((...args) => {
4073
+ this.#renderer ??= (content) => this.html(content);
4074
+ return this.#renderer(...args);
4075
+ }, "render");
4076
+ setLayout = /* @__PURE__ */ __name((layout) => this.#layout = layout, "setLayout");
4077
+ getLayout = /* @__PURE__ */ __name(() => this.#layout, "getLayout");
4078
+ setRenderer = /* @__PURE__ */ __name((renderer) => {
4079
+ this.#renderer = renderer;
4080
+ }, "setRenderer");
4081
+ header = /* @__PURE__ */ __name((name, value, options) => {
4082
+ if (value === void 0) {
4083
+ if (this.#headers) {
4084
+ this.#headers.delete(name);
4085
+ } else if (this.#preparedHeaders) {
4086
+ delete this.#preparedHeaders[name.toLocaleLowerCase()];
4087
+ }
4088
+ if (this.finalized) {
4089
+ this.res.headers.delete(name);
4090
+ }
4091
+ return;
4092
+ }
4093
+ if (options?.append) {
4094
+ if (!this.#headers) {
4095
+ this.#isFresh = false;
4096
+ this.#headers = new Headers(this.#preparedHeaders);
4097
+ this.#preparedHeaders = {};
4098
+ }
4099
+ this.#headers.append(name, value);
4100
+ } else {
4101
+ if (this.#headers) {
4102
+ this.#headers.set(name, value);
4103
+ } else {
4104
+ this.#preparedHeaders ??= {};
4105
+ this.#preparedHeaders[name.toLowerCase()] = value;
4106
+ }
4107
+ }
4108
+ if (this.finalized) {
4109
+ if (options?.append) {
4110
+ this.res.headers.append(name, value);
4111
+ } else {
4112
+ this.res.headers.set(name, value);
4113
+ }
4114
+ }
4115
+ }, "header");
4116
+ status = /* @__PURE__ */ __name((status) => {
4117
+ this.#isFresh = false;
4118
+ this.#status = status;
4119
+ }, "status");
4120
+ set = /* @__PURE__ */ __name((key, value) => {
4121
+ this.#var ??= /* @__PURE__ */ new Map();
4122
+ this.#var.set(key, value);
4123
+ }, "set");
4124
+ get = /* @__PURE__ */ __name((key) => {
4125
+ return this.#var ? this.#var.get(key) : void 0;
4126
+ }, "get");
4127
+ get var() {
4128
+ if (!this.#var) {
4129
+ return {};
4130
+ }
4131
+ return Object.fromEntries(this.#var);
4132
+ }
4133
+ newResponse = /* @__PURE__ */ __name((data, arg, headers) => {
4134
+ if (this.#isFresh && !headers && !arg && this.#status === 200) {
4135
+ return new Response(data, {
4136
+ headers: this.#preparedHeaders
4137
+ });
4138
+ }
4139
+ if (arg && typeof arg !== "number") {
4140
+ const header = new Headers(arg.headers);
4141
+ if (this.#headers) {
4142
+ this.#headers.forEach((v, k) => {
4143
+ if (k === "set-cookie") {
4144
+ header.append(k, v);
4145
+ } else {
4146
+ header.set(k, v);
4147
+ }
4148
+ });
4149
+ }
4150
+ const headers2 = setHeaders(header, this.#preparedHeaders);
4151
+ return new Response(data, {
4152
+ headers: headers2,
4153
+ status: arg.status ?? this.#status
4154
+ });
4155
+ }
4156
+ const status = typeof arg === "number" ? arg : this.#status;
4157
+ this.#preparedHeaders ??= {};
4158
+ this.#headers ??= new Headers();
4159
+ setHeaders(this.#headers, this.#preparedHeaders);
4160
+ if (this.#res) {
4161
+ this.#res.headers.forEach((v, k) => {
4162
+ if (k === "set-cookie") {
4163
+ this.#headers?.append(k, v);
4164
+ } else {
4165
+ this.#headers?.set(k, v);
4166
+ }
4167
+ });
4168
+ setHeaders(this.#headers, this.#preparedHeaders);
4169
+ }
4170
+ headers ??= {};
4171
+ for (const [k, v] of Object.entries(headers)) {
4172
+ if (typeof v === "string") {
4173
+ this.#headers.set(k, v);
4174
+ } else {
4175
+ this.#headers.delete(k);
4176
+ for (const v2 of v) {
4177
+ this.#headers.append(k, v2);
4178
+ }
4179
+ }
4180
+ }
4181
+ return new Response(data, {
4182
+ status,
4183
+ headers: this.#headers
4184
+ });
4185
+ }, "newResponse");
4186
+ body = /* @__PURE__ */ __name((data, arg, headers) => {
4187
+ return typeof arg === "number" ? this.newResponse(data, arg, headers) : this.newResponse(data, arg);
4188
+ }, "body");
4189
+ text = /* @__PURE__ */ __name((text, arg, headers) => {
4190
+ if (!this.#preparedHeaders) {
4191
+ if (this.#isFresh && !headers && !arg) {
4192
+ return new Response(text);
4193
+ }
4194
+ this.#preparedHeaders = {};
4195
+ }
4196
+ this.#preparedHeaders["content-type"] = TEXT_PLAIN;
4197
+ return typeof arg === "number" ? this.newResponse(text, arg, headers) : this.newResponse(text, arg);
4198
+ }, "text");
4199
+ json = /* @__PURE__ */ __name((object, arg, headers) => {
4200
+ const body = JSON.stringify(object);
4201
+ this.#preparedHeaders ??= {};
4202
+ this.#preparedHeaders["content-type"] = "application/json; charset=UTF-8";
4203
+ return typeof arg === "number" ? this.newResponse(body, arg, headers) : this.newResponse(body, arg);
4204
+ }, "json");
4205
+ html = /* @__PURE__ */ __name((html, arg, headers) => {
4206
+ this.#preparedHeaders ??= {};
4207
+ this.#preparedHeaders["content-type"] = "text/html; charset=UTF-8";
4208
+ if (typeof html === "object") {
4209
+ return resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then((html2) => {
4210
+ return typeof arg === "number" ? this.newResponse(html2, arg, headers) : this.newResponse(html2, arg);
4211
+ });
4212
+ }
4213
+ return typeof arg === "number" ? this.newResponse(html, arg, headers) : this.newResponse(html, arg);
4214
+ }, "html");
4215
+ redirect = /* @__PURE__ */ __name((location, status) => {
4216
+ this.#headers ??= new Headers();
4217
+ this.#headers.set("Location", location);
4218
+ return this.newResponse(null, status ?? 302);
4219
+ }, "redirect");
4220
+ notFound = /* @__PURE__ */ __name(() => {
4221
+ this.#notFoundHandler ??= () => new Response();
4222
+ return this.#notFoundHandler(this);
4223
+ }, "notFound");
4224
+ };
4225
+
4226
+ // ../../node_modules/.pnpm/hono@4.6.3/node_modules/hono/dist/compose.js
4227
+ var compose = /* @__PURE__ */ __name((middleware, onError, onNotFound) => {
4228
+ return (context2, next) => {
4229
+ let index = -1;
4230
+ return dispatch(0);
4231
+ async function dispatch(i) {
4232
+ if (i <= index) {
4233
+ throw new Error("next() called multiple times");
4234
+ }
4235
+ index = i;
4236
+ let res;
4237
+ let isError = false;
4238
+ let handler;
4239
+ if (middleware[i]) {
4240
+ handler = middleware[i][0][0];
4241
+ if (context2 instanceof Context) {
4242
+ context2.req.routeIndex = i;
4243
+ }
4244
+ } else {
4245
+ handler = i === middleware.length && next || void 0;
4246
+ }
4247
+ if (!handler) {
4248
+ if (context2 instanceof Context && context2.finalized === false && onNotFound) {
4249
+ res = await onNotFound(context2);
4250
+ }
4251
+ } else {
4252
+ try {
4253
+ res = await handler(context2, () => {
4254
+ return dispatch(i + 1);
4255
+ });
4256
+ } catch (err) {
4257
+ if (err instanceof Error && context2 instanceof Context && onError) {
4258
+ context2.error = err;
4259
+ res = await onError(err, context2);
4260
+ isError = true;
4261
+ } else {
4262
+ throw err;
4263
+ }
4264
+ }
4265
+ }
4266
+ if (res && (context2.finalized === false || isError)) {
4267
+ context2.res = res;
4268
+ }
4269
+ return context2;
4270
+ }
4271
+ __name(dispatch, "dispatch");
4272
+ };
4273
+ }, "compose");
4274
+
4275
+ // ../../node_modules/.pnpm/hono@4.6.3/node_modules/hono/dist/router.js
4276
+ var METHOD_NAME_ALL = "ALL";
4277
+ var METHOD_NAME_ALL_LOWERCASE = "all";
4278
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
4279
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
4280
+ var UnsupportedPathError = class extends Error {
4281
+ static {
4282
+ __name(this, "UnsupportedPathError");
4283
+ }
4284
+ };
4285
+
4286
+ // ../../node_modules/.pnpm/hono@4.6.3/node_modules/hono/dist/hono-base.js
4287
+ var COMPOSED_HANDLER = Symbol("composedHandler");
4288
+ var notFoundHandler = /* @__PURE__ */ __name((c) => {
4289
+ return c.text("404 Not Found", 404);
4290
+ }, "notFoundHandler");
4291
+ var errorHandler = /* @__PURE__ */ __name((err, c) => {
4292
+ if ("getResponse" in err) {
4293
+ return err.getResponse();
4294
+ }
4295
+ console.error(err);
4296
+ return c.text("Internal Server Error", 500);
4297
+ }, "errorHandler");
4298
+ var Hono = class {
4299
+ static {
4300
+ __name(this, "Hono");
4301
+ }
4302
+ get;
4303
+ post;
4304
+ put;
4305
+ delete;
4306
+ options;
4307
+ patch;
4308
+ all;
4309
+ on;
4310
+ use;
4311
+ router;
4312
+ getPath;
4313
+ _basePath = "/";
4314
+ #path = "/";
4315
+ routes = [];
4316
+ constructor(options = {}) {
4317
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
4318
+ allMethods.forEach((method) => {
4319
+ this[method] = (args1, ...args) => {
4320
+ if (typeof args1 === "string") {
4321
+ this.#path = args1;
4322
+ } else {
4323
+ this.addRoute(method, this.#path, args1);
4324
+ }
4325
+ args.forEach((handler) => {
4326
+ if (typeof handler !== "string") {
4327
+ this.addRoute(method, this.#path, handler);
4328
+ }
4329
+ });
4330
+ return this;
4331
+ };
4332
+ });
4333
+ this.on = (method, path, ...handlers) => {
4334
+ for (const p of [path].flat()) {
4335
+ this.#path = p;
4336
+ for (const m of [method].flat()) {
4337
+ handlers.map((handler) => {
4338
+ this.addRoute(m.toUpperCase(), this.#path, handler);
4339
+ });
4340
+ }
4341
+ }
4342
+ return this;
4343
+ };
4344
+ this.use = (arg1, ...handlers) => {
4345
+ if (typeof arg1 === "string") {
4346
+ this.#path = arg1;
4347
+ } else {
4348
+ this.#path = "*";
4349
+ handlers.unshift(arg1);
4350
+ }
4351
+ handlers.forEach((handler) => {
4352
+ this.addRoute(METHOD_NAME_ALL, this.#path, handler);
4353
+ });
4354
+ return this;
4355
+ };
4356
+ const strict = options.strict ?? true;
4357
+ delete options.strict;
4358
+ Object.assign(this, options);
4359
+ this.getPath = strict ? options.getPath ?? getPath : getPathNoStrict;
4360
+ }
4361
+ clone() {
4362
+ const clone = new Hono({
4363
+ router: this.router,
4364
+ getPath: this.getPath
4365
+ });
4366
+ clone.routes = this.routes;
4367
+ return clone;
4368
+ }
4369
+ notFoundHandler = notFoundHandler;
4370
+ errorHandler = errorHandler;
4371
+ route(path, app2) {
4372
+ const subApp = this.basePath(path);
4373
+ app2.routes.map((r) => {
4374
+ let handler;
4375
+ if (app2.errorHandler === errorHandler) {
4376
+ handler = r.handler;
4377
+ } else {
4378
+ handler = /* @__PURE__ */ __name(async (c, next) => (await compose([], app2.errorHandler)(c, () => r.handler(c, next))).res, "handler");
4379
+ handler[COMPOSED_HANDLER] = r.handler;
4380
+ }
4381
+ subApp.addRoute(r.method, r.path, handler);
4382
+ });
4383
+ return this;
4384
+ }
4385
+ basePath(path) {
4386
+ const subApp = this.clone();
4387
+ subApp._basePath = mergePath(this._basePath, path);
4388
+ return subApp;
4389
+ }
4390
+ onError = /* @__PURE__ */ __name((handler) => {
4391
+ this.errorHandler = handler;
4392
+ return this;
4393
+ }, "onError");
4394
+ notFound = /* @__PURE__ */ __name((handler) => {
4395
+ this.notFoundHandler = handler;
4396
+ return this;
4397
+ }, "notFound");
4398
+ mount(path, applicationHandler, options) {
4399
+ let replaceRequest;
4400
+ let optionHandler;
4401
+ if (options) {
4402
+ if (typeof options === "function") {
4403
+ optionHandler = options;
4404
+ } else {
4405
+ optionHandler = options.optionHandler;
4406
+ replaceRequest = options.replaceRequest;
4407
+ }
4408
+ }
4409
+ const getOptions = optionHandler ? (c) => {
4410
+ const options2 = optionHandler(c);
4411
+ return Array.isArray(options2) ? options2 : [options2];
4412
+ } : (c) => {
4413
+ let executionContext = void 0;
4414
+ try {
4415
+ executionContext = c.executionCtx;
4416
+ } catch {
4417
+ }
4418
+ return [c.env, executionContext];
4419
+ };
4420
+ replaceRequest ||= (() => {
4421
+ const mergedPath = mergePath(this._basePath, path);
4422
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
4423
+ return (request) => {
4424
+ const url = new URL(request.url);
4425
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
4426
+ return new Request(url, request);
4427
+ };
4428
+ })();
4429
+ const handler = /* @__PURE__ */ __name(async (c, next) => {
4430
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
4431
+ if (res) {
4432
+ return res;
4433
+ }
4434
+ await next();
4435
+ }, "handler");
4436
+ this.addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
4437
+ return this;
4438
+ }
4439
+ addRoute(method, path, handler) {
4440
+ method = method.toUpperCase();
4441
+ path = mergePath(this._basePath, path);
4442
+ const r = { path, method, handler };
4443
+ this.router.add(method, path, [handler, r]);
4444
+ this.routes.push(r);
4445
+ }
4446
+ matchRoute(method, path) {
4447
+ return this.router.match(method, path);
4448
+ }
4449
+ handleError(err, c) {
4450
+ if (err instanceof Error) {
4451
+ return this.errorHandler(err, c);
4452
+ }
4453
+ throw err;
4454
+ }
4455
+ dispatch(request, executionCtx, env2, method) {
4456
+ if (method === "HEAD") {
4457
+ return (async () => new Response(null, await this.dispatch(request, executionCtx, env2, "GET")))();
4458
+ }
4459
+ const path = this.getPath(request, { env: env2 });
4460
+ const matchResult = this.matchRoute(method, path);
4461
+ const c = new Context(request, {
4462
+ path,
4463
+ matchResult,
4464
+ env: env2,
4465
+ executionCtx,
4466
+ notFoundHandler: this.notFoundHandler
4467
+ });
4468
+ if (matchResult[0].length === 1) {
4469
+ let res;
4470
+ try {
4471
+ res = matchResult[0][0][0][0](c, async () => {
4472
+ c.res = await this.notFoundHandler(c);
4473
+ });
4474
+ } catch (err) {
4475
+ return this.handleError(err, c);
4476
+ }
4477
+ return res instanceof Promise ? res.then(
4478
+ (resolved) => resolved || (c.finalized ? c.res : this.notFoundHandler(c))
4479
+ ).catch((err) => this.handleError(err, c)) : res ?? this.notFoundHandler(c);
4480
+ }
4481
+ const composed = compose(matchResult[0], this.errorHandler, this.notFoundHandler);
4482
+ return (async () => {
4483
+ try {
4484
+ const context2 = await composed(c);
4485
+ if (!context2.finalized) {
4486
+ throw new Error(
4487
+ "Context is not finalized. Did you forget to return a Response object or `await next()`?"
4488
+ );
4489
+ }
4490
+ return context2.res;
4491
+ } catch (err) {
4492
+ return this.handleError(err, c);
4493
+ }
4494
+ })();
4495
+ }
4496
+ fetch = /* @__PURE__ */ __name((request, ...rest) => {
4497
+ return this.dispatch(request, rest[1], rest[0], request.method);
4498
+ }, "fetch");
4499
+ request = /* @__PURE__ */ __name((input, requestInit, Env, executionCtx) => {
4500
+ if (input instanceof Request) {
4501
+ if (requestInit !== void 0) {
4502
+ input = new Request(input, requestInit);
4503
+ }
4504
+ return this.fetch(input, Env, executionCtx);
4505
+ }
4506
+ input = input.toString();
4507
+ const path = /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`;
4508
+ const req = new Request(path, requestInit);
4509
+ return this.fetch(req, Env, executionCtx);
4510
+ }, "request");
4511
+ fire = /* @__PURE__ */ __name(() => {
4512
+ addEventListener("fetch", (event) => {
4513
+ event.respondWith(this.dispatch(event.request, event, void 0, event.request.method));
4514
+ });
4515
+ }, "fire");
4516
+ };
4517
+
4518
+ // ../../node_modules/.pnpm/hono@4.6.3/node_modules/hono/dist/router/reg-exp-router/node.js
4519
+ var LABEL_REG_EXP_STR = "[^/]+";
4520
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
4521
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
4522
+ var PATH_ERROR = Symbol();
4523
+ var regExpMetaChars = new Set(".\\+*[^]$()");
4524
+ function compareKey(a, b) {
4525
+ if (a.length === 1) {
4526
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
4527
+ }
4528
+ if (b.length === 1) {
4529
+ return 1;
4530
+ }
4531
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
4532
+ return 1;
4533
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
4534
+ return -1;
4535
+ }
4536
+ if (a === LABEL_REG_EXP_STR) {
4537
+ return 1;
4538
+ } else if (b === LABEL_REG_EXP_STR) {
4539
+ return -1;
4540
+ }
4541
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
4542
+ }
4543
+ __name(compareKey, "compareKey");
4544
+ var Node = class {
4545
+ static {
4546
+ __name(this, "Node");
4547
+ }
4548
+ index;
4549
+ varIndex;
4550
+ children = /* @__PURE__ */ Object.create(null);
4551
+ insert(tokens, index, paramMap, context2, pathErrorCheckOnly) {
4552
+ if (tokens.length === 0) {
4553
+ if (this.index !== void 0) {
4554
+ throw PATH_ERROR;
4555
+ }
4556
+ if (pathErrorCheckOnly) {
4557
+ return;
4558
+ }
4559
+ this.index = index;
4560
+ return;
4561
+ }
4562
+ const [token, ...restTokens] = tokens;
4563
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
4564
+ let node;
4565
+ if (pattern) {
4566
+ const name = pattern[1];
4567
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
4568
+ if (name && pattern[2]) {
4569
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
4570
+ if (/\((?!\?:)/.test(regexpStr)) {
4571
+ throw PATH_ERROR;
4572
+ }
4573
+ }
4574
+ node = this.children[regexpStr];
4575
+ if (!node) {
4576
+ if (Object.keys(this.children).some(
4577
+ (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
4578
+ )) {
4579
+ throw PATH_ERROR;
4580
+ }
4581
+ if (pathErrorCheckOnly) {
4582
+ return;
4583
+ }
4584
+ node = this.children[regexpStr] = new Node();
4585
+ if (name !== "") {
4586
+ node.varIndex = context2.varIndex++;
4587
+ }
4588
+ }
4589
+ if (!pathErrorCheckOnly && name !== "") {
4590
+ paramMap.push([name, node.varIndex]);
4591
+ }
4592
+ } else {
4593
+ node = this.children[token];
4594
+ if (!node) {
4595
+ if (Object.keys(this.children).some(
4596
+ (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
4597
+ )) {
4598
+ throw PATH_ERROR;
4599
+ }
4600
+ if (pathErrorCheckOnly) {
4601
+ return;
4602
+ }
4603
+ node = this.children[token] = new Node();
4604
+ }
4605
+ }
4606
+ node.insert(restTokens, index, paramMap, context2, pathErrorCheckOnly);
4607
+ }
4608
+ buildRegExpStr() {
4609
+ const childKeys = Object.keys(this.children).sort(compareKey);
4610
+ const strList = childKeys.map((k) => {
4611
+ const c = this.children[k];
4612
+ return (typeof c.varIndex === "number" ? `(${k})@${c.varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
4613
+ });
4614
+ if (typeof this.index === "number") {
4615
+ strList.unshift(`#${this.index}`);
4616
+ }
4617
+ if (strList.length === 0) {
4618
+ return "";
4619
+ }
4620
+ if (strList.length === 1) {
4621
+ return strList[0];
4622
+ }
4623
+ return "(?:" + strList.join("|") + ")";
4624
+ }
4625
+ };
4626
+
4627
+ // ../../node_modules/.pnpm/hono@4.6.3/node_modules/hono/dist/router/reg-exp-router/trie.js
4628
+ var Trie = class {
4629
+ static {
4630
+ __name(this, "Trie");
4631
+ }
4632
+ context = { varIndex: 0 };
4633
+ root = new Node();
4634
+ insert(path, index, pathErrorCheckOnly) {
4635
+ const paramAssoc = [];
4636
+ const groups = [];
4637
+ for (let i = 0; ; ) {
4638
+ let replaced = false;
4639
+ path = path.replace(/\{[^}]+\}/g, (m) => {
4640
+ const mark = `@\\${i}`;
4641
+ groups[i] = [mark, m];
4642
+ i++;
4643
+ replaced = true;
4644
+ return mark;
4645
+ });
4646
+ if (!replaced) {
4647
+ break;
4648
+ }
4649
+ }
4650
+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
4651
+ for (let i = groups.length - 1; i >= 0; i--) {
4652
+ const [mark] = groups[i];
4653
+ for (let j = tokens.length - 1; j >= 0; j--) {
4654
+ if (tokens[j].indexOf(mark) !== -1) {
4655
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
4656
+ break;
4657
+ }
4658
+ }
4659
+ }
4660
+ this.root.insert(tokens, index, paramAssoc, this.context, pathErrorCheckOnly);
4661
+ return paramAssoc;
4662
+ }
4663
+ buildRegExp() {
4664
+ let regexp = this.root.buildRegExpStr();
4665
+ if (regexp === "") {
4666
+ return [/^$/, [], []];
4667
+ }
4668
+ let captureIndex = 0;
4669
+ const indexReplacementMap = [];
4670
+ const paramReplacementMap = [];
4671
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
4672
+ if (typeof handlerIndex !== "undefined") {
4673
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
4674
+ return "$()";
4675
+ }
4676
+ if (typeof paramIndex !== "undefined") {
4677
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
4678
+ return "";
4679
+ }
4680
+ return "";
4681
+ });
4682
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
4683
+ }
4684
+ };
4685
+
4686
+ // ../../node_modules/.pnpm/hono@4.6.3/node_modules/hono/dist/router/reg-exp-router/router.js
4687
+ var emptyParam = [];
4688
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
4689
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
4690
+ function buildWildcardRegExp(path) {
4691
+ return wildcardRegExpCache[path] ??= new RegExp(
4692
+ path === "*" ? "" : `^${path.replace(
4693
+ /\/\*$|([.\\+*[^\]$()])/g,
4694
+ (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
4695
+ )}$`
4696
+ );
4697
+ }
4698
+ __name(buildWildcardRegExp, "buildWildcardRegExp");
4699
+ function clearWildcardRegExpCache() {
4700
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
4701
+ }
4702
+ __name(clearWildcardRegExpCache, "clearWildcardRegExpCache");
4703
+ function buildMatcherFromPreprocessedRoutes(routes) {
4704
+ const trie = new Trie();
4705
+ const handlerData = [];
4706
+ if (routes.length === 0) {
4707
+ return nullMatcher;
4708
+ }
4709
+ const routesWithStaticPathFlag = routes.map(
4710
+ (route) => [!/\*|\/:/.test(route[0]), ...route]
4711
+ ).sort(
4712
+ ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
4713
+ );
4714
+ const staticMap = /* @__PURE__ */ Object.create(null);
4715
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
4716
+ const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
4717
+ if (pathErrorCheckOnly) {
4718
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
4719
+ } else {
4720
+ j++;
4721
+ }
4722
+ let paramAssoc;
4723
+ try {
4724
+ paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
4725
+ } catch (e) {
4726
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
4727
+ }
4728
+ if (pathErrorCheckOnly) {
4729
+ continue;
4730
+ }
4731
+ handlerData[j] = handlers.map(([h, paramCount]) => {
4732
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
4733
+ paramCount -= 1;
4734
+ for (; paramCount >= 0; paramCount--) {
4735
+ const [key, value] = paramAssoc[paramCount];
4736
+ paramIndexMap[key] = value;
4737
+ }
4738
+ return [h, paramIndexMap];
4739
+ });
4740
+ }
4741
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
4742
+ for (let i = 0, len = handlerData.length; i < len; i++) {
4743
+ for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
4744
+ const map = handlerData[i][j]?.[1];
4745
+ if (!map) {
4746
+ continue;
4747
+ }
4748
+ const keys = Object.keys(map);
4749
+ for (let k = 0, len3 = keys.length; k < len3; k++) {
4750
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
4751
+ }
4752
+ }
4753
+ }
4754
+ const handlerMap = [];
4755
+ for (const i in indexReplacementMap) {
4756
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
4757
+ }
4758
+ return [regexp, handlerMap, staticMap];
4759
+ }
4760
+ __name(buildMatcherFromPreprocessedRoutes, "buildMatcherFromPreprocessedRoutes");
4761
+ function findMiddleware(middleware, path) {
4762
+ if (!middleware) {
4763
+ return void 0;
4764
+ }
4765
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
4766
+ if (buildWildcardRegExp(k).test(path)) {
4767
+ return [...middleware[k]];
4768
+ }
4769
+ }
4770
+ return void 0;
4771
+ }
4772
+ __name(findMiddleware, "findMiddleware");
4773
+ var RegExpRouter = class {
4774
+ static {
4775
+ __name(this, "RegExpRouter");
4776
+ }
4777
+ name = "RegExpRouter";
4778
+ middleware;
4779
+ routes;
4780
+ constructor() {
4781
+ this.middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
4782
+ this.routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
4783
+ }
4784
+ add(method, path, handler) {
4785
+ const { middleware, routes } = this;
4786
+ if (!middleware || !routes) {
4787
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
4788
+ }
4789
+ if (!middleware[method]) {
4790
+ ;
4791
+ [middleware, routes].forEach((handlerMap) => {
4792
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
4793
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
4794
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
4795
+ });
4796
+ });
4797
+ }
4798
+ if (path === "/*") {
4799
+ path = "*";
4800
+ }
4801
+ const paramCount = (path.match(/\/:/g) || []).length;
4802
+ if (/\*$/.test(path)) {
4803
+ const re = buildWildcardRegExp(path);
4804
+ if (method === METHOD_NAME_ALL) {
4805
+ Object.keys(middleware).forEach((m) => {
4806
+ middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
4807
+ });
4808
+ } else {
4809
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
4810
+ }
4811
+ Object.keys(middleware).forEach((m) => {
4812
+ if (method === METHOD_NAME_ALL || method === m) {
4813
+ Object.keys(middleware[m]).forEach((p) => {
4814
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
4815
+ });
4816
+ }
4817
+ });
4818
+ Object.keys(routes).forEach((m) => {
4819
+ if (method === METHOD_NAME_ALL || method === m) {
4820
+ Object.keys(routes[m]).forEach(
4821
+ (p) => re.test(p) && routes[m][p].push([handler, paramCount])
4822
+ );
4823
+ }
4824
+ });
4825
+ return;
4826
+ }
4827
+ const paths = checkOptionalParameter(path) || [path];
4828
+ for (let i = 0, len = paths.length; i < len; i++) {
4829
+ const path2 = paths[i];
4830
+ Object.keys(routes).forEach((m) => {
4831
+ if (method === METHOD_NAME_ALL || method === m) {
4832
+ routes[m][path2] ||= [
4833
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
4834
+ ];
4835
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
4836
+ }
4837
+ });
4838
+ }
4839
+ }
4840
+ match(method, path) {
4841
+ clearWildcardRegExpCache();
4842
+ const matchers = this.buildAllMatchers();
4843
+ this.match = (method2, path2) => {
4844
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
4845
+ const staticMatch = matcher[2][path2];
4846
+ if (staticMatch) {
4847
+ return staticMatch;
4848
+ }
4849
+ const match = path2.match(matcher[0]);
4850
+ if (!match) {
4851
+ return [[], emptyParam];
4852
+ }
4853
+ const index = match.indexOf("", 1);
4854
+ return [matcher[1][index], match];
4855
+ };
4856
+ return this.match(method, path);
4857
+ }
4858
+ buildAllMatchers() {
4859
+ const matchers = /* @__PURE__ */ Object.create(null);
4860
+ [...Object.keys(this.routes), ...Object.keys(this.middleware)].forEach((method) => {
4861
+ matchers[method] ||= this.buildMatcher(method);
4862
+ });
4863
+ this.middleware = this.routes = void 0;
4864
+ return matchers;
4865
+ }
4866
+ buildMatcher(method) {
4867
+ const routes = [];
4868
+ let hasOwnRoute = method === METHOD_NAME_ALL;
4869
+ [this.middleware, this.routes].forEach((r) => {
4870
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
4871
+ if (ownRoute.length !== 0) {
4872
+ hasOwnRoute ||= true;
4873
+ routes.push(...ownRoute);
4874
+ } else if (method !== METHOD_NAME_ALL) {
4875
+ routes.push(
4876
+ ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
4877
+ );
4878
+ }
4879
+ });
4880
+ if (!hasOwnRoute) {
4881
+ return null;
4882
+ } else {
4883
+ return buildMatcherFromPreprocessedRoutes(routes);
4884
+ }
4885
+ }
4886
+ };
4887
+
4888
+ // ../../node_modules/.pnpm/hono@4.6.3/node_modules/hono/dist/router/smart-router/router.js
4889
+ var SmartRouter = class {
4890
+ static {
4891
+ __name(this, "SmartRouter");
4892
+ }
4893
+ name = "SmartRouter";
4894
+ routers = [];
4895
+ routes = [];
4896
+ constructor(init) {
4897
+ Object.assign(this, init);
4898
+ }
4899
+ add(method, path, handler) {
4900
+ if (!this.routes) {
4901
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
4902
+ }
4903
+ this.routes.push([method, path, handler]);
4904
+ }
4905
+ match(method, path) {
4906
+ if (!this.routes) {
4907
+ throw new Error("Fatal error");
4908
+ }
4909
+ const { routers, routes } = this;
4910
+ const len = routers.length;
4911
+ let i = 0;
4912
+ let res;
4913
+ for (; i < len; i++) {
4914
+ const router = routers[i];
4915
+ try {
4916
+ routes.forEach((args) => {
4917
+ router.add(...args);
4918
+ });
4919
+ res = router.match(method, path);
4920
+ } catch (e) {
4921
+ if (e instanceof UnsupportedPathError) {
4922
+ continue;
4923
+ }
4924
+ throw e;
4925
+ }
4926
+ this.match = router.match.bind(router);
4927
+ this.routers = [router];
4928
+ this.routes = void 0;
4929
+ break;
4930
+ }
4931
+ if (i === len) {
4932
+ throw new Error("Fatal error");
4933
+ }
4934
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
4935
+ return res;
4936
+ }
4937
+ get activeRouter() {
4938
+ if (this.routes || this.routers.length !== 1) {
4939
+ throw new Error("No active router has been determined yet.");
4940
+ }
4941
+ return this.routers[0];
4942
+ }
4943
+ };
4944
+
4945
+ // ../../node_modules/.pnpm/hono@4.6.3/node_modules/hono/dist/router/trie-router/node.js
4946
+ var Node2 = class {
4947
+ static {
4948
+ __name(this, "Node");
4949
+ }
4950
+ methods;
4951
+ children;
4952
+ patterns;
4953
+ order = 0;
4954
+ name;
4955
+ params = /* @__PURE__ */ Object.create(null);
4956
+ constructor(method, handler, children) {
4957
+ this.children = children || /* @__PURE__ */ Object.create(null);
4958
+ this.methods = [];
4959
+ this.name = "";
4960
+ if (method && handler) {
4961
+ const m = /* @__PURE__ */ Object.create(null);
4962
+ m[method] = { handler, possibleKeys: [], score: 0, name: this.name };
4963
+ this.methods = [m];
4964
+ }
4965
+ this.patterns = [];
4966
+ }
4967
+ insert(method, path, handler) {
4968
+ this.name = `${method} ${path}`;
4969
+ this.order = ++this.order;
4970
+ let curNode = this;
4971
+ const parts = splitRoutingPath(path);
4972
+ const possibleKeys = [];
4973
+ for (let i = 0, len = parts.length; i < len; i++) {
4974
+ const p = parts[i];
4975
+ if (Object.keys(curNode.children).includes(p)) {
4976
+ curNode = curNode.children[p];
4977
+ const pattern2 = getPattern(p);
4978
+ if (pattern2) {
4979
+ possibleKeys.push(pattern2[1]);
4980
+ }
4981
+ continue;
4982
+ }
4983
+ curNode.children[p] = new Node2();
4984
+ const pattern = getPattern(p);
4985
+ if (pattern) {
4986
+ curNode.patterns.push(pattern);
4987
+ possibleKeys.push(pattern[1]);
4988
+ }
4989
+ curNode = curNode.children[p];
4990
+ }
4991
+ if (!curNode.methods.length) {
4992
+ curNode.methods = [];
4993
+ }
4994
+ const m = /* @__PURE__ */ Object.create(null);
4995
+ const handlerSet = {
4996
+ handler,
4997
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
4998
+ name: this.name,
4999
+ score: this.order
5000
+ };
5001
+ m[method] = handlerSet;
5002
+ curNode.methods.push(m);
5003
+ return curNode;
5004
+ }
5005
+ gHSets(node, method, nodeParams, params) {
5006
+ const handlerSets = [];
5007
+ for (let i = 0, len = node.methods.length; i < len; i++) {
5008
+ const m = node.methods[i];
5009
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
5010
+ const processedSet = /* @__PURE__ */ Object.create(null);
5011
+ if (handlerSet !== void 0) {
5012
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
5013
+ handlerSet.possibleKeys.forEach((key) => {
5014
+ const processed = processedSet[handlerSet.name];
5015
+ handlerSet.params[key] = params[key] && !processed ? params[key] : nodeParams[key] ?? params[key];
5016
+ processedSet[handlerSet.name] = true;
5017
+ });
5018
+ handlerSets.push(handlerSet);
5019
+ }
5020
+ }
5021
+ return handlerSets;
5022
+ }
5023
+ search(method, path) {
5024
+ const handlerSets = [];
5025
+ this.params = /* @__PURE__ */ Object.create(null);
5026
+ const curNode = this;
5027
+ let curNodes = [curNode];
5028
+ const parts = splitPath(path);
5029
+ for (let i = 0, len = parts.length; i < len; i++) {
5030
+ const part = parts[i];
5031
+ const isLast = i === len - 1;
5032
+ const tempNodes = [];
5033
+ for (let j = 0, len2 = curNodes.length; j < len2; j++) {
5034
+ const node = curNodes[j];
5035
+ const nextNode = node.children[part];
5036
+ if (nextNode) {
5037
+ nextNode.params = node.params;
5038
+ if (isLast === true) {
5039
+ if (nextNode.children["*"]) {
5040
+ handlerSets.push(
5041
+ ...this.gHSets(nextNode.children["*"], method, node.params, /* @__PURE__ */ Object.create(null))
5042
+ );
5043
+ }
5044
+ handlerSets.push(...this.gHSets(nextNode, method, node.params, /* @__PURE__ */ Object.create(null)));
5045
+ } else {
5046
+ tempNodes.push(nextNode);
5047
+ }
5048
+ }
5049
+ for (let k = 0, len3 = node.patterns.length; k < len3; k++) {
5050
+ const pattern = node.patterns[k];
5051
+ const params = { ...node.params };
5052
+ if (pattern === "*") {
5053
+ const astNode = node.children["*"];
5054
+ if (astNode) {
5055
+ handlerSets.push(...this.gHSets(astNode, method, node.params, /* @__PURE__ */ Object.create(null)));
5056
+ tempNodes.push(astNode);
5057
+ }
5058
+ continue;
5059
+ }
5060
+ if (part === "") {
5061
+ continue;
5062
+ }
5063
+ const [key, name, matcher] = pattern;
5064
+ const child = node.children[key];
5065
+ const restPathString = parts.slice(i).join("/");
5066
+ if (matcher instanceof RegExp && matcher.test(restPathString)) {
5067
+ params[name] = restPathString;
5068
+ handlerSets.push(...this.gHSets(child, method, node.params, params));
5069
+ continue;
5070
+ }
5071
+ if (matcher === true || matcher instanceof RegExp && matcher.test(part)) {
5072
+ if (typeof key === "string") {
5073
+ params[name] = part;
5074
+ if (isLast === true) {
5075
+ handlerSets.push(...this.gHSets(child, method, params, node.params));
5076
+ if (child.children["*"]) {
5077
+ handlerSets.push(...this.gHSets(child.children["*"], method, params, node.params));
5078
+ }
5079
+ } else {
5080
+ child.params = params;
5081
+ tempNodes.push(child);
5082
+ }
5083
+ }
5084
+ }
5085
+ }
5086
+ }
5087
+ curNodes = tempNodes;
5088
+ }
5089
+ const results = handlerSets.sort((a, b) => {
5090
+ return a.score - b.score;
5091
+ });
5092
+ return [results.map(({ handler, params }) => [handler, params])];
5093
+ }
5094
+ };
5095
+
5096
+ // ../../node_modules/.pnpm/hono@4.6.3/node_modules/hono/dist/router/trie-router/router.js
5097
+ var TrieRouter = class {
5098
+ static {
5099
+ __name(this, "TrieRouter");
5100
+ }
5101
+ name = "TrieRouter";
5102
+ node;
5103
+ constructor() {
5104
+ this.node = new Node2();
5105
+ }
5106
+ add(method, path, handler) {
5107
+ const results = checkOptionalParameter(path);
5108
+ if (results) {
5109
+ for (const p of results) {
5110
+ this.node.insert(method, p, handler);
5111
+ }
5112
+ return;
5113
+ }
5114
+ this.node.insert(method, path, handler);
5115
+ }
5116
+ match(method, path) {
5117
+ return this.node.search(method, path);
5118
+ }
5119
+ };
5120
+
5121
+ // ../../node_modules/.pnpm/hono@4.6.3/node_modules/hono/dist/hono.js
5122
+ var Hono2 = class extends Hono {
5123
+ static {
5124
+ __name(this, "Hono");
5125
+ }
5126
+ constructor(options = {}) {
5127
+ super(options);
5128
+ this.router = options.router ?? new SmartRouter({
5129
+ routers: [new RegExpRouter(), new TrieRouter()]
5130
+ });
5131
+ }
5132
+ };
5133
+
5134
+ // worker/src/getUpdateInfo.ts
5135
+ var getUpdateInfo = /* @__PURE__ */ __name(async (DB, {
5136
+ platform: platform2,
5137
+ appVersion,
5138
+ bundleId,
5139
+ minBundleId = NIL_UUID,
5140
+ channel: channel2 = "production"
5141
+ }) => {
5142
+ const appVersionList = await DB.prepare(
5143
+ /* sql */
5144
+ `
5145
+ SELECT
5146
+ target_app_version
5147
+ FROM bundles
5148
+ WHERE platform = ?
5149
+ GROUP BY target_app_version
5150
+ `
5151
+ ).bind(platform2).all();
5152
+ const targetAppVersionList = filterCompatibleAppVersions(
5153
+ appVersionList.results.map((group3) => group3.target_app_version),
5154
+ appVersion
5155
+ );
5156
+ const sql = (
5157
+ /* sql */
5158
+ `
5159
+ WITH input AS (
5160
+ SELECT
5161
+ ? AS app_platform,
5162
+ ? AS app_version,
5163
+ ? AS bundle_id,
5164
+ ? AS min_bundle_id,
5165
+ ? AS channel,
5166
+ '00000000-0000-0000-0000-000000000000' AS nil_uuid
5167
+ ),
5168
+ update_candidate AS (
5169
+ SELECT
5170
+ b.id,
5171
+ b.should_force_update,
5172
+ b.message,
5173
+ 'UPDATE' AS status
5174
+ FROM bundles b, input
5175
+ WHERE b.enabled = 1
5176
+ AND b.platform = input.app_platform
5177
+ AND b.id >= input.bundle_id
5178
+ AND b.id >= input.min_bundle_id
5179
+ AND b.channel = input.channel
5180
+ AND b.target_app_version IN (${targetAppVersionList.map((version2) => `'${version2}'`).join(",")})
5181
+ ORDER BY b.id DESC
5182
+ LIMIT 1
5183
+ ),
5184
+ rollback_candidate AS (
5185
+ SELECT
5186
+ b.id,
5187
+ 1 AS should_force_update,
5188
+ b.message,
5189
+ 'ROLLBACK' AS status
5190
+ FROM bundles b, input
5191
+ WHERE b.enabled = 1
5192
+ AND b.platform = input.app_platform
5193
+ AND b.id < input.bundle_id
5194
+ AND b.id >= input.min_bundle_id
5195
+ ORDER BY b.id DESC
5196
+ LIMIT 1
5197
+ ),
5198
+ final_result AS (
5199
+ SELECT * FROM update_candidate
5200
+ UNION ALL
5201
+ SELECT * FROM rollback_candidate
5202
+ WHERE NOT EXISTS (SELECT 1 FROM update_candidate)
5203
+ )
5204
+ SELECT id, should_force_update, message, status
5205
+ FROM final_result, input
5206
+ WHERE id <> bundle_id
5207
+
5208
+ UNION ALL
5209
+
5210
+ SELECT
5211
+ nil_uuid AS id,
5212
+ 1 AS should_force_update,
5213
+ NULL AS message,
5214
+ 'ROLLBACK' AS status
5215
+ FROM input
5216
+ WHERE (SELECT COUNT(*) FROM final_result) = 0
5217
+ AND bundle_id > min_bundle_id;
5218
+ `
5219
+ );
5220
+ const result = await DB.prepare(sql).bind(platform2, appVersion, bundleId, minBundleId, channel2).first();
5221
+ if (!result) {
5222
+ return null;
5223
+ }
5224
+ return {
5225
+ id: result.id,
5226
+ shouldForceUpdate: Boolean(result.should_force_update),
5227
+ status: result.status,
5228
+ message: result.message
5229
+ };
5230
+ }, "getUpdateInfo");
5231
+
5232
+ // worker/src/index.ts
5233
+ var app = new Hono2();
5234
+ app.get("/api/check-update", async (c) => {
5235
+ const bundleId = c.req.header("x-bundle-id");
5236
+ const appPlatform = c.req.header("x-app-platform");
5237
+ const appVersion = c.req.header("x-app-version");
5238
+ const minBundleId = c.req.header("x-min-bundle-id");
5239
+ const channel2 = c.req.header("x-channel");
5240
+ if (!bundleId || !appPlatform || !appVersion) {
5241
+ return c.json(
5242
+ { error: "Missing bundleId, appPlatform, or appVersion" },
5243
+ 400
5244
+ );
5245
+ }
5246
+ const updateInfo = await getUpdateInfo(c.env.DB, {
5247
+ appVersion,
5248
+ bundleId,
5249
+ platform: appPlatform,
5250
+ minBundleId: minBundleId || NIL_UUID,
5251
+ channel: channel2 || "production"
5252
+ });
5253
+ const appUpdateInfo = await withJwtSignedUrl({
5254
+ data: updateInfo,
5255
+ reqUrl: c.req.url,
5256
+ jwtSecret: c.env.JWT_SECRET
5257
+ });
5258
+ return c.json(appUpdateInfo, 200);
5259
+ });
5260
+ app.get("*", async (c) => {
5261
+ const result = await verifyJwtSignedUrl({
5262
+ path: c.req.path,
5263
+ token: c.req.query("token"),
5264
+ jwtSecret: c.env.JWT_SECRET,
5265
+ handler: /* @__PURE__ */ __name(async (key) => {
5266
+ const object = await c.env.BUCKET.get(key);
5267
+ if (!object) {
5268
+ return null;
5269
+ }
5270
+ return {
5271
+ body: object.body,
5272
+ contentType: object.httpMetadata?.contentType
5273
+ };
5274
+ }, "handler")
5275
+ });
5276
+ if (result.status !== 200) {
5277
+ return c.json({ error: result.error }, result.status);
5278
+ }
5279
+ return c.body(result.responseBody, 200, result.responseHeaders);
5280
+ });
5281
+ var index_default = app;
2393
5282
  export {
2394
5283
  index_default as default
2395
5284
  };