@concavejs/docstore-better-sqlite3 0.0.1-alpha.11 → 0.0.1-alpha.13

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.
Files changed (2) hide show
  1. package/dist/index.js +1438 -897
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,4 +1,3 @@
1
- import { createRequire } from "node:module";
2
1
  var __defProp = Object.defineProperty;
3
2
  var __returnValue = (v) => v;
4
3
  function __exportSetter(name, newValue) {
@@ -14,7 +13,6 @@ var __export = (target, all) => {
14
13
  });
15
14
  };
16
15
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
18
16
 
19
17
  // ../../node_modules/convex/dist/esm/values/base64.js
20
18
  function getLens(b64) {
@@ -802,6 +800,237 @@ var init_values = __esm(() => {
802
800
  init_errors();
803
801
  });
804
802
 
803
+ // ../core/dist/id-codec/base32.js
804
+ function base32Encode(data) {
805
+ if (data.length === 0)
806
+ return "";
807
+ let result = "";
808
+ let buffer = 0;
809
+ let bitsLeft = 0;
810
+ for (const byte of data) {
811
+ buffer = buffer << 8 | byte;
812
+ bitsLeft += 8;
813
+ while (bitsLeft >= 5) {
814
+ bitsLeft -= 5;
815
+ const index = buffer >> bitsLeft & 31;
816
+ result += ALPHABET[index];
817
+ }
818
+ }
819
+ if (bitsLeft > 0) {
820
+ const index = buffer << 5 - bitsLeft & 31;
821
+ result += ALPHABET[index];
822
+ }
823
+ return result;
824
+ }
825
+ function base32Decode(str) {
826
+ if (str.length === 0)
827
+ return new Uint8Array(0);
828
+ const outputLength = Math.floor(str.length * 5 / 8);
829
+ const result = new Uint8Array(outputLength);
830
+ let buffer = 0;
831
+ let bitsLeft = 0;
832
+ let outputIndex = 0;
833
+ for (const char of str) {
834
+ const value = ALPHABET_MAP.get(char);
835
+ if (value === undefined) {
836
+ throw new Error(`Invalid base32 character: ${char}`);
837
+ }
838
+ buffer = buffer << 5 | value;
839
+ bitsLeft += 5;
840
+ if (bitsLeft >= 8) {
841
+ bitsLeft -= 8;
842
+ result[outputIndex++] = buffer >> bitsLeft & 255;
843
+ }
844
+ }
845
+ return result;
846
+ }
847
+ function isValidBase32(str) {
848
+ for (const char of str) {
849
+ if (!ALPHABET_MAP.has(char)) {
850
+ return false;
851
+ }
852
+ }
853
+ return true;
854
+ }
855
+ var ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz", ALPHABET_MAP;
856
+ var init_base32 = __esm(() => {
857
+ ALPHABET_MAP = new Map;
858
+ for (let i2 = 0;i2 < ALPHABET.length; i2++) {
859
+ ALPHABET_MAP.set(ALPHABET[i2], i2);
860
+ ALPHABET_MAP.set(ALPHABET[i2].toUpperCase(), i2);
861
+ }
862
+ ALPHABET_MAP.set("i", 1);
863
+ ALPHABET_MAP.set("I", 1);
864
+ ALPHABET_MAP.set("l", 1);
865
+ ALPHABET_MAP.set("L", 1);
866
+ ALPHABET_MAP.set("o", 0);
867
+ ALPHABET_MAP.set("O", 0);
868
+ });
869
+
870
+ // ../core/dist/id-codec/vint.js
871
+ function vintEncode(value) {
872
+ if (value < 0) {
873
+ throw new Error("VInt cannot encode negative numbers");
874
+ }
875
+ if (value > 4294967295) {
876
+ throw new Error("VInt cannot encode values larger than 2^32-1");
877
+ }
878
+ value = value >>> 0;
879
+ if (value < 128) {
880
+ return new Uint8Array([value]);
881
+ }
882
+ if (value < 16512) {
883
+ const adjusted2 = value - 128;
884
+ return new Uint8Array([128 | adjusted2 >> 8 & 63, adjusted2 & 255]);
885
+ }
886
+ if (value < 2113664) {
887
+ const adjusted2 = value - 16512;
888
+ return new Uint8Array([192 | adjusted2 >> 16 & 31, adjusted2 >> 8 & 255, adjusted2 & 255]);
889
+ }
890
+ if (value < 270549120) {
891
+ const adjusted2 = value - 2113664;
892
+ return new Uint8Array([
893
+ 224 | adjusted2 >> 24 & 15,
894
+ adjusted2 >> 16 & 255,
895
+ adjusted2 >> 8 & 255,
896
+ adjusted2 & 255
897
+ ]);
898
+ }
899
+ const adjusted = value - 270549120;
900
+ return new Uint8Array([
901
+ 240 | adjusted >> 32 & 7,
902
+ adjusted >> 24 & 255,
903
+ adjusted >> 16 & 255,
904
+ adjusted >> 8 & 255,
905
+ adjusted & 255
906
+ ]);
907
+ }
908
+ function vintDecode(data, offset = 0) {
909
+ if (offset >= data.length) {
910
+ throw new Error("VInt decode: unexpected end of data");
911
+ }
912
+ const first = data[offset];
913
+ if ((first & 128) === 0) {
914
+ return { value: first, bytesRead: 1 };
915
+ }
916
+ if ((first & 192) === 128) {
917
+ if (offset + 1 >= data.length) {
918
+ throw new Error("VInt decode: truncated 2-byte encoding");
919
+ }
920
+ const value = 128 + ((first & 63) << 8 | data[offset + 1]);
921
+ return { value, bytesRead: 2 };
922
+ }
923
+ if ((first & 224) === 192) {
924
+ if (offset + 2 >= data.length) {
925
+ throw new Error("VInt decode: truncated 3-byte encoding");
926
+ }
927
+ const value = 16512 + ((first & 31) << 16 | data[offset + 1] << 8 | data[offset + 2]);
928
+ return { value, bytesRead: 3 };
929
+ }
930
+ if ((first & 240) === 224) {
931
+ if (offset + 3 >= data.length) {
932
+ throw new Error("VInt decode: truncated 4-byte encoding");
933
+ }
934
+ const value = 2113664 + ((first & 15) << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]);
935
+ return { value: value >>> 0, bytesRead: 4 };
936
+ }
937
+ if ((first & 248) === 240) {
938
+ if (offset + 4 >= data.length) {
939
+ throw new Error("VInt decode: truncated 5-byte encoding");
940
+ }
941
+ const high = first & 7;
942
+ const low = (data[offset + 1] << 24 | data[offset + 2] << 16 | data[offset + 3] << 8 | data[offset + 4]) >>> 0;
943
+ const value = 270549120 + high * 4294967296 + low;
944
+ return { value: value >>> 0, bytesRead: 5 };
945
+ }
946
+ throw new Error("VInt decode: invalid prefix");
947
+ }
948
+
949
+ // ../core/dist/id-codec/fletcher16.js
950
+ function fletcher16(data) {
951
+ let sum1 = 0;
952
+ let sum2 = 0;
953
+ for (const byte of data) {
954
+ sum1 = (sum1 + byte) % 255;
955
+ sum2 = (sum2 + sum1) % 255;
956
+ }
957
+ return new Uint8Array([sum1, sum2]);
958
+ }
959
+ function verifyFletcher16(data, checksum) {
960
+ if (checksum.length !== 2)
961
+ return false;
962
+ const computed = fletcher16(data);
963
+ return computed[0] === checksum[0] && computed[1] === checksum[1];
964
+ }
965
+
966
+ // ../core/dist/utils/crypto.js
967
+ var weakRandomState;
968
+ var init_crypto = __esm(() => {
969
+ weakRandomState = (Date.now() ^ 2654435769) >>> 0;
970
+ });
971
+
972
+ // ../core/dist/id-codec/document-id.js
973
+ function encodeDocumentId(tableNumber, internalId) {
974
+ if (internalId.length !== INTERNAL_ID_LENGTH) {
975
+ throw new Error(`Internal ID must be exactly ${INTERNAL_ID_LENGTH} bytes, got ${internalId.length}`);
976
+ }
977
+ if (tableNumber < 1 || tableNumber > 4294967295) {
978
+ throw new Error(`Table number must be between 1 and 2^32-1, got ${tableNumber}`);
979
+ }
980
+ const tableBytes = vintEncode(tableNumber);
981
+ const payload = new Uint8Array(tableBytes.length + INTERNAL_ID_LENGTH);
982
+ payload.set(tableBytes, 0);
983
+ payload.set(internalId, tableBytes.length);
984
+ const checksum = fletcher16(payload);
985
+ const final = new Uint8Array(payload.length + 2);
986
+ final.set(payload, 0);
987
+ final.set(checksum, payload.length);
988
+ return base32Encode(final);
989
+ }
990
+ function decodeDocumentId(encoded) {
991
+ if (encoded.length < MIN_ENCODED_LENGTH || encoded.length > MAX_ENCODED_LENGTH) {
992
+ throw new Error(`Invalid document ID length: ${encoded.length} (expected ${MIN_ENCODED_LENGTH}-${MAX_ENCODED_LENGTH})`);
993
+ }
994
+ if (!isValidBase32(encoded)) {
995
+ throw new Error("Invalid document ID: contains invalid base32 characters");
996
+ }
997
+ const bytes = base32Decode(encoded);
998
+ if (bytes.length < 19) {
999
+ throw new Error(`Invalid document ID: decoded to ${bytes.length} bytes (minimum 19)`);
1000
+ }
1001
+ const checksum = bytes.slice(bytes.length - 2);
1002
+ const payload = bytes.slice(0, bytes.length - 2);
1003
+ if (!verifyFletcher16(payload, checksum)) {
1004
+ throw new Error("Invalid document ID: checksum verification failed");
1005
+ }
1006
+ const { value: tableNumber, bytesRead } = vintDecode(payload, 0);
1007
+ const internalId = payload.slice(bytesRead, bytesRead + INTERNAL_ID_LENGTH);
1008
+ if (internalId.length !== INTERNAL_ID_LENGTH) {
1009
+ throw new Error(`Invalid document ID: internal ID is ${internalId.length} bytes (expected ${INTERNAL_ID_LENGTH})`);
1010
+ }
1011
+ return { tableNumber, internalId };
1012
+ }
1013
+ function isValidDocumentId(encoded) {
1014
+ try {
1015
+ decodeDocumentId(encoded);
1016
+ return true;
1017
+ } catch {
1018
+ return false;
1019
+ }
1020
+ }
1021
+ function internalIdToHex(internalId) {
1022
+ let hex = "";
1023
+ for (let i2 = 0;i2 < internalId.length; i2++) {
1024
+ hex += internalId[i2].toString(16).padStart(2, "0");
1025
+ }
1026
+ return hex;
1027
+ }
1028
+ var INTERNAL_ID_LENGTH = 16, MIN_ENCODED_LENGTH = 31, MAX_ENCODED_LENGTH = 37;
1029
+ var init_document_id = __esm(() => {
1030
+ init_base32();
1031
+ init_crypto();
1032
+ });
1033
+
805
1034
  // ../core/dist/utils/utils.js
806
1035
  function hexToArrayBuffer(hex) {
807
1036
  if (hex === "") {
@@ -840,9 +1069,15 @@ function deserializeDeveloperId(developerId) {
840
1069
  return null;
841
1070
  }
842
1071
  var DOC_ID_SEPARATOR = ":", LEGACY_DOC_ID_SEPARATOR = ";";
1072
+ var init_utils = __esm(() => {
1073
+ init_document_id();
1074
+ });
843
1075
 
844
1076
  // ../core/dist/tables/interface.js
845
1077
  function getFullTableName(tableName, componentPath) {
1078
+ if (isSystemTable(tableName)) {
1079
+ return tableName;
1080
+ }
846
1081
  if (!componentPath || componentPath === "") {
847
1082
  return tableName;
848
1083
  }
@@ -859,23 +1094,28 @@ function parseFullTableName(fullName) {
859
1094
  };
860
1095
  }
861
1096
  function isSystemTable(tableName) {
862
- return tableName.startsWith("_");
1097
+ return Object.hasOwn(SYSTEM_TABLE_NUMBERS, tableName);
863
1098
  }
864
- var SYSTEM_TABLE_NUMBERS, FIRST_USER_TABLE_NUMBER = 100;
1099
+ var SYSTEM_TABLE_NUMBERS, FIRST_USER_TABLE_NUMBER = 10001;
865
1100
  var init_interface = __esm(() => {
866
1101
  SYSTEM_TABLE_NUMBERS = {
867
1102
  _tables: 1,
868
1103
  _scheduled_functions: 2,
869
1104
  _storage: 3,
870
- _crons: 4
1105
+ _crons: 4,
1106
+ _indexes: 5,
1107
+ _schemas: 6,
1108
+ _components: 7,
1109
+ _component_definitions: 8,
1110
+ _schema_validation_progress: 9
871
1111
  };
872
1112
  });
873
1113
 
874
1114
  // ../core/dist/kernel/context-storage.js
875
- function resolveFromRequire(req) {
1115
+ function resolveFromModuleResolver(resolveModule) {
876
1116
  for (const specifier of ["node:async_hooks", "async_hooks"]) {
877
1117
  try {
878
- const mod = req(specifier);
1118
+ const mod = resolveModule(specifier);
879
1119
  if (mod?.AsyncLocalStorage) {
880
1120
  return mod.AsyncLocalStorage;
881
1121
  }
@@ -918,16 +1158,16 @@ var resolveAsyncLocalStorage = () => {
918
1158
  if (globalCtor) {
919
1159
  return globalCtor;
920
1160
  }
921
- const runtimeRequire = __require;
922
- if (runtimeRequire) {
923
- const ctor = resolveFromRequire(runtimeRequire);
1161
+ const getBuiltinModule = globalThis?.process?.getBuiltinModule;
1162
+ if (typeof getBuiltinModule === "function") {
1163
+ const ctor = resolveFromModuleResolver((specifier) => getBuiltinModule(specifier));
924
1164
  if (ctor) {
925
1165
  return ctor;
926
1166
  }
927
1167
  }
928
1168
  const globalRequire = globalThis?.require;
929
1169
  if (typeof globalRequire === "function") {
930
- return resolveFromRequire(globalRequire);
1170
+ return resolveFromModuleResolver(globalRequire);
931
1171
  }
932
1172
  return;
933
1173
  }, AsyncLocalStorageCtor;
@@ -2212,7 +2452,7 @@ async function listSystemFunctions(options = {}) {
2212
2452
  }
2213
2453
  for (const route of httpRoutes) {
2214
2454
  const method = route.route.method;
2215
- const routePath = route.route.path;
2455
+ const routePath = mountHttpRoutePath(route.route.path, owningComponent);
2216
2456
  results.push({
2217
2457
  name: `${method} ${routePath}`,
2218
2458
  module: listing.path,
@@ -2274,6 +2514,16 @@ async function loadAndAnalyzeModule(listing, componentPath) {
2274
2514
  function makeCacheKey(componentPath, modulePath) {
2275
2515
  return `${componentPath ?? ""}::${modulePath}`;
2276
2516
  }
2517
+ function mountHttpRoutePath(routePath, componentPath) {
2518
+ if (!componentPath) {
2519
+ return routePath;
2520
+ }
2521
+ const prefix = `/${componentPath}`;
2522
+ if (routePath === "/") {
2523
+ return prefix;
2524
+ }
2525
+ return `${prefix}${routePath}`;
2526
+ }
2277
2527
  function buildFallbackSourcePath(modulePath) {
2278
2528
  const trimmed = modulePath.replace(/\\/g, "/").replace(/^\//, "");
2279
2529
  const withConvex = trimmed.startsWith("convex/") ? trimmed : `convex/${trimmed}`;
@@ -2435,132 +2685,15 @@ var init_base64url = __esm(() => {
2435
2685
  init_buffer_utils();
2436
2686
  });
2437
2687
 
2438
- // ../../node_modules/jose/dist/webapi/util/errors.js
2439
- var exports_errors = {};
2440
- __export(exports_errors, {
2441
- JWTInvalid: () => JWTInvalid,
2442
- JWTExpired: () => JWTExpired,
2443
- JWTClaimValidationFailed: () => JWTClaimValidationFailed,
2444
- JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed,
2445
- JWSInvalid: () => JWSInvalid,
2446
- JWKSTimeout: () => JWKSTimeout,
2447
- JWKSNoMatchingKey: () => JWKSNoMatchingKey,
2448
- JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys,
2449
- JWKSInvalid: () => JWKSInvalid,
2450
- JWKInvalid: () => JWKInvalid,
2451
- JWEInvalid: () => JWEInvalid,
2452
- JWEDecryptionFailed: () => JWEDecryptionFailed,
2453
- JOSENotSupported: () => JOSENotSupported,
2454
- JOSEError: () => JOSEError,
2455
- JOSEAlgNotAllowed: () => JOSEAlgNotAllowed
2456
- });
2457
- var JOSEError, JWTClaimValidationFailed, JWTExpired, JOSEAlgNotAllowed, JOSENotSupported, JWEDecryptionFailed, JWEInvalid, JWSInvalid, JWTInvalid, JWKInvalid, JWKSInvalid, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, JWKSTimeout, JWSSignatureVerificationFailed;
2458
- var init_errors2 = __esm(() => {
2459
- JOSEError = class JOSEError extends Error {
2460
- static code = "ERR_JOSE_GENERIC";
2461
- code = "ERR_JOSE_GENERIC";
2462
- constructor(message, options) {
2463
- super(message, options);
2464
- this.name = this.constructor.name;
2465
- Error.captureStackTrace?.(this, this.constructor);
2466
- }
2467
- };
2468
- JWTClaimValidationFailed = class JWTClaimValidationFailed extends JOSEError {
2469
- static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
2470
- code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
2471
- claim;
2472
- reason;
2473
- payload;
2474
- constructor(message, payload, claim = "unspecified", reason = "unspecified") {
2475
- super(message, { cause: { claim, reason, payload } });
2476
- this.claim = claim;
2477
- this.reason = reason;
2478
- this.payload = payload;
2479
- }
2480
- };
2481
- JWTExpired = class JWTExpired extends JOSEError {
2482
- static code = "ERR_JWT_EXPIRED";
2483
- code = "ERR_JWT_EXPIRED";
2484
- claim;
2485
- reason;
2486
- payload;
2487
- constructor(message, payload, claim = "unspecified", reason = "unspecified") {
2488
- super(message, { cause: { claim, reason, payload } });
2489
- this.claim = claim;
2490
- this.reason = reason;
2491
- this.payload = payload;
2492
- }
2493
- };
2494
- JOSEAlgNotAllowed = class JOSEAlgNotAllowed extends JOSEError {
2495
- static code = "ERR_JOSE_ALG_NOT_ALLOWED";
2496
- code = "ERR_JOSE_ALG_NOT_ALLOWED";
2497
- };
2498
- JOSENotSupported = class JOSENotSupported extends JOSEError {
2499
- static code = "ERR_JOSE_NOT_SUPPORTED";
2500
- code = "ERR_JOSE_NOT_SUPPORTED";
2501
- };
2502
- JWEDecryptionFailed = class JWEDecryptionFailed extends JOSEError {
2503
- static code = "ERR_JWE_DECRYPTION_FAILED";
2504
- code = "ERR_JWE_DECRYPTION_FAILED";
2505
- constructor(message = "decryption operation failed", options) {
2506
- super(message, options);
2507
- }
2508
- };
2509
- JWEInvalid = class JWEInvalid extends JOSEError {
2510
- static code = "ERR_JWE_INVALID";
2511
- code = "ERR_JWE_INVALID";
2512
- };
2513
- JWSInvalid = class JWSInvalid extends JOSEError {
2514
- static code = "ERR_JWS_INVALID";
2515
- code = "ERR_JWS_INVALID";
2516
- };
2517
- JWTInvalid = class JWTInvalid extends JOSEError {
2518
- static code = "ERR_JWT_INVALID";
2519
- code = "ERR_JWT_INVALID";
2520
- };
2521
- JWKInvalid = class JWKInvalid extends JOSEError {
2522
- static code = "ERR_JWK_INVALID";
2523
- code = "ERR_JWK_INVALID";
2524
- };
2525
- JWKSInvalid = class JWKSInvalid extends JOSEError {
2526
- static code = "ERR_JWKS_INVALID";
2527
- code = "ERR_JWKS_INVALID";
2528
- };
2529
- JWKSNoMatchingKey = class JWKSNoMatchingKey extends JOSEError {
2530
- static code = "ERR_JWKS_NO_MATCHING_KEY";
2531
- code = "ERR_JWKS_NO_MATCHING_KEY";
2532
- constructor(message = "no applicable key found in the JSON Web Key Set", options) {
2533
- super(message, options);
2534
- }
2535
- };
2536
- JWKSMultipleMatchingKeys = class JWKSMultipleMatchingKeys extends JOSEError {
2537
- [Symbol.asyncIterator];
2538
- static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
2539
- code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
2540
- constructor(message = "multiple matching keys found in the JSON Web Key Set", options) {
2541
- super(message, options);
2542
- }
2543
- };
2544
- JWKSTimeout = class JWKSTimeout extends JOSEError {
2545
- static code = "ERR_JWKS_TIMEOUT";
2546
- code = "ERR_JWKS_TIMEOUT";
2547
- constructor(message = "request timed out", options) {
2548
- super(message, options);
2549
- }
2550
- };
2551
- JWSSignatureVerificationFailed = class JWSSignatureVerificationFailed extends JOSEError {
2552
- static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
2553
- code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
2554
- constructor(message = "signature verification failed", options) {
2555
- super(message, options);
2556
- }
2557
- };
2558
- });
2559
-
2560
2688
  // ../../node_modules/jose/dist/webapi/lib/crypto_key.js
2561
2689
  function getHashLength(hash) {
2562
2690
  return parseInt(hash.name.slice(4), 10);
2563
2691
  }
2692
+ function checkHashLength(algorithm, expected) {
2693
+ const actual = getHashLength(algorithm.hash);
2694
+ if (actual !== expected)
2695
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
2696
+ }
2564
2697
  function getNamedCurve(alg) {
2565
2698
  switch (alg) {
2566
2699
  case "ES256":
@@ -2585,10 +2718,7 @@ function checkSigCryptoKey(key, alg, usage) {
2585
2718
  case "HS512": {
2586
2719
  if (!isAlgorithm(key.algorithm, "HMAC"))
2587
2720
  throw unusable("HMAC");
2588
- const expected = parseInt(alg.slice(2), 10);
2589
- const actual = getHashLength(key.algorithm.hash);
2590
- if (actual !== expected)
2591
- throw unusable(`SHA-${expected}`, "algorithm.hash");
2721
+ checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
2592
2722
  break;
2593
2723
  }
2594
2724
  case "RS256":
@@ -2596,10 +2726,7 @@ function checkSigCryptoKey(key, alg, usage) {
2596
2726
  case "RS512": {
2597
2727
  if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
2598
2728
  throw unusable("RSASSA-PKCS1-v1_5");
2599
- const expected = parseInt(alg.slice(2), 10);
2600
- const actual = getHashLength(key.algorithm.hash);
2601
- if (actual !== expected)
2602
- throw unusable(`SHA-${expected}`, "algorithm.hash");
2729
+ checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
2603
2730
  break;
2604
2731
  }
2605
2732
  case "PS256":
@@ -2607,10 +2734,7 @@ function checkSigCryptoKey(key, alg, usage) {
2607
2734
  case "PS512": {
2608
2735
  if (!isAlgorithm(key.algorithm, "RSA-PSS"))
2609
2736
  throw unusable("RSA-PSS");
2610
- const expected = parseInt(alg.slice(2), 10);
2611
- const actual = getHashLength(key.algorithm.hash);
2612
- if (actual !== expected)
2613
- throw unusable(`SHA-${expected}`, "algorithm.hash");
2737
+ checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
2614
2738
  break;
2615
2739
  }
2616
2740
  case "Ed25519":
@@ -2668,6 +2792,128 @@ function message(msg, actual, ...types) {
2668
2792
  }
2669
2793
  var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types), withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
2670
2794
 
2795
+ // ../../node_modules/jose/dist/webapi/util/errors.js
2796
+ var exports_errors = {};
2797
+ __export(exports_errors, {
2798
+ JWTInvalid: () => JWTInvalid,
2799
+ JWTExpired: () => JWTExpired,
2800
+ JWTClaimValidationFailed: () => JWTClaimValidationFailed,
2801
+ JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed,
2802
+ JWSInvalid: () => JWSInvalid,
2803
+ JWKSTimeout: () => JWKSTimeout,
2804
+ JWKSNoMatchingKey: () => JWKSNoMatchingKey,
2805
+ JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys,
2806
+ JWKSInvalid: () => JWKSInvalid,
2807
+ JWKInvalid: () => JWKInvalid,
2808
+ JWEInvalid: () => JWEInvalid,
2809
+ JWEDecryptionFailed: () => JWEDecryptionFailed,
2810
+ JOSENotSupported: () => JOSENotSupported,
2811
+ JOSEError: () => JOSEError,
2812
+ JOSEAlgNotAllowed: () => JOSEAlgNotAllowed
2813
+ });
2814
+ var JOSEError, JWTClaimValidationFailed, JWTExpired, JOSEAlgNotAllowed, JOSENotSupported, JWEDecryptionFailed, JWEInvalid, JWSInvalid, JWTInvalid, JWKInvalid, JWKSInvalid, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, JWKSTimeout, JWSSignatureVerificationFailed;
2815
+ var init_errors2 = __esm(() => {
2816
+ JOSEError = class JOSEError extends Error {
2817
+ static code = "ERR_JOSE_GENERIC";
2818
+ code = "ERR_JOSE_GENERIC";
2819
+ constructor(message2, options) {
2820
+ super(message2, options);
2821
+ this.name = this.constructor.name;
2822
+ Error.captureStackTrace?.(this, this.constructor);
2823
+ }
2824
+ };
2825
+ JWTClaimValidationFailed = class JWTClaimValidationFailed extends JOSEError {
2826
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
2827
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
2828
+ claim;
2829
+ reason;
2830
+ payload;
2831
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
2832
+ super(message2, { cause: { claim, reason, payload } });
2833
+ this.claim = claim;
2834
+ this.reason = reason;
2835
+ this.payload = payload;
2836
+ }
2837
+ };
2838
+ JWTExpired = class JWTExpired extends JOSEError {
2839
+ static code = "ERR_JWT_EXPIRED";
2840
+ code = "ERR_JWT_EXPIRED";
2841
+ claim;
2842
+ reason;
2843
+ payload;
2844
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
2845
+ super(message2, { cause: { claim, reason, payload } });
2846
+ this.claim = claim;
2847
+ this.reason = reason;
2848
+ this.payload = payload;
2849
+ }
2850
+ };
2851
+ JOSEAlgNotAllowed = class JOSEAlgNotAllowed extends JOSEError {
2852
+ static code = "ERR_JOSE_ALG_NOT_ALLOWED";
2853
+ code = "ERR_JOSE_ALG_NOT_ALLOWED";
2854
+ };
2855
+ JOSENotSupported = class JOSENotSupported extends JOSEError {
2856
+ static code = "ERR_JOSE_NOT_SUPPORTED";
2857
+ code = "ERR_JOSE_NOT_SUPPORTED";
2858
+ };
2859
+ JWEDecryptionFailed = class JWEDecryptionFailed extends JOSEError {
2860
+ static code = "ERR_JWE_DECRYPTION_FAILED";
2861
+ code = "ERR_JWE_DECRYPTION_FAILED";
2862
+ constructor(message2 = "decryption operation failed", options) {
2863
+ super(message2, options);
2864
+ }
2865
+ };
2866
+ JWEInvalid = class JWEInvalid extends JOSEError {
2867
+ static code = "ERR_JWE_INVALID";
2868
+ code = "ERR_JWE_INVALID";
2869
+ };
2870
+ JWSInvalid = class JWSInvalid extends JOSEError {
2871
+ static code = "ERR_JWS_INVALID";
2872
+ code = "ERR_JWS_INVALID";
2873
+ };
2874
+ JWTInvalid = class JWTInvalid extends JOSEError {
2875
+ static code = "ERR_JWT_INVALID";
2876
+ code = "ERR_JWT_INVALID";
2877
+ };
2878
+ JWKInvalid = class JWKInvalid extends JOSEError {
2879
+ static code = "ERR_JWK_INVALID";
2880
+ code = "ERR_JWK_INVALID";
2881
+ };
2882
+ JWKSInvalid = class JWKSInvalid extends JOSEError {
2883
+ static code = "ERR_JWKS_INVALID";
2884
+ code = "ERR_JWKS_INVALID";
2885
+ };
2886
+ JWKSNoMatchingKey = class JWKSNoMatchingKey extends JOSEError {
2887
+ static code = "ERR_JWKS_NO_MATCHING_KEY";
2888
+ code = "ERR_JWKS_NO_MATCHING_KEY";
2889
+ constructor(message2 = "no applicable key found in the JSON Web Key Set", options) {
2890
+ super(message2, options);
2891
+ }
2892
+ };
2893
+ JWKSMultipleMatchingKeys = class JWKSMultipleMatchingKeys extends JOSEError {
2894
+ [Symbol.asyncIterator];
2895
+ static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
2896
+ code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
2897
+ constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) {
2898
+ super(message2, options);
2899
+ }
2900
+ };
2901
+ JWKSTimeout = class JWKSTimeout extends JOSEError {
2902
+ static code = "ERR_JWKS_TIMEOUT";
2903
+ code = "ERR_JWKS_TIMEOUT";
2904
+ constructor(message2 = "request timed out", options) {
2905
+ super(message2, options);
2906
+ }
2907
+ };
2908
+ JWSSignatureVerificationFailed = class JWSSignatureVerificationFailed extends JOSEError {
2909
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
2910
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
2911
+ constructor(message2 = "signature verification failed", options) {
2912
+ super(message2, options);
2913
+ }
2914
+ };
2915
+ });
2916
+
2671
2917
  // ../../node_modules/jose/dist/webapi/lib/is_key_like.js
2672
2918
  var isCryptoKey = (key) => {
2673
2919
  if (key?.[Symbol.toStringTag] === "CryptoKey")
@@ -2679,7 +2925,34 @@ var isCryptoKey = (key) => {
2679
2925
  }
2680
2926
  }, isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject", isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
2681
2927
 
2682
- // ../../node_modules/jose/dist/webapi/lib/is_disjoint.js
2928
+ // ../../node_modules/jose/dist/webapi/lib/helpers.js
2929
+ function decodeBase64url(value, label, ErrorClass) {
2930
+ try {
2931
+ return decode(value);
2932
+ } catch {
2933
+ throw new ErrorClass(`Failed to base64url decode the ${label}`);
2934
+ }
2935
+ }
2936
+ var unprotected;
2937
+ var init_helpers = __esm(() => {
2938
+ init_base64url();
2939
+ unprotected = Symbol();
2940
+ });
2941
+
2942
+ // ../../node_modules/jose/dist/webapi/lib/type_checks.js
2943
+ function isObject(input) {
2944
+ if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
2945
+ return false;
2946
+ }
2947
+ if (Object.getPrototypeOf(input) === null) {
2948
+ return true;
2949
+ }
2950
+ let proto = input;
2951
+ while (Object.getPrototypeOf(proto) !== null) {
2952
+ proto = Object.getPrototypeOf(proto);
2953
+ }
2954
+ return Object.getPrototypeOf(input) === proto;
2955
+ }
2683
2956
  function isDisjoint(...headers) {
2684
2957
  const sources = headers.filter(Boolean);
2685
2958
  if (sources.length === 0 || sources.length === 1) {
@@ -2701,24 +2974,9 @@ function isDisjoint(...headers) {
2701
2974
  }
2702
2975
  return true;
2703
2976
  }
2977
+ var isObjectLike = (value) => typeof value === "object" && value !== null, isJWK = (key) => isObject(key) && typeof key.kty === "string", isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string"), isPublicJWK = (key) => key.kty !== "oct" && key.d === undefined && key.priv === undefined, isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
2704
2978
 
2705
- // ../../node_modules/jose/dist/webapi/lib/is_object.js
2706
- function isObject(input) {
2707
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
2708
- return false;
2709
- }
2710
- if (Object.getPrototypeOf(input) === null) {
2711
- return true;
2712
- }
2713
- let proto = input;
2714
- while (Object.getPrototypeOf(proto) !== null) {
2715
- proto = Object.getPrototypeOf(proto);
2716
- }
2717
- return Object.getPrototypeOf(input) === proto;
2718
- }
2719
- var isObjectLike = (value) => typeof value === "object" && value !== null;
2720
-
2721
- // ../../node_modules/jose/dist/webapi/lib/check_key_length.js
2979
+ // ../../node_modules/jose/dist/webapi/lib/signing.js
2722
2980
  function checkKeyLength(alg, key) {
2723
2981
  if (alg.startsWith("RS") || alg.startsWith("PS")) {
2724
2982
  const { modulusLength } = key.algorithm;
@@ -2727,31 +2985,84 @@ function checkKeyLength(alg, key) {
2727
2985
  }
2728
2986
  }
2729
2987
  }
2730
-
2731
- // ../../node_modules/jose/dist/webapi/lib/jwk_to_key.js
2732
- function subtleMapping(jwk) {
2733
- let algorithm;
2734
- let keyUsages;
2735
- switch (jwk.kty) {
2736
- case "AKP": {
2737
- switch (jwk.alg) {
2738
- case "ML-DSA-44":
2739
- case "ML-DSA-65":
2740
- case "ML-DSA-87":
2741
- algorithm = { name: jwk.alg };
2742
- keyUsages = jwk.priv ? ["sign"] : ["verify"];
2743
- break;
2744
- default:
2745
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
2746
- }
2747
- break;
2748
- }
2749
- case "RSA": {
2750
- switch (jwk.alg) {
2751
- case "PS256":
2752
- case "PS384":
2753
- case "PS512":
2754
- algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
2988
+ function subtleAlgorithm(alg, algorithm) {
2989
+ const hash = `SHA-${alg.slice(-3)}`;
2990
+ switch (alg) {
2991
+ case "HS256":
2992
+ case "HS384":
2993
+ case "HS512":
2994
+ return { hash, name: "HMAC" };
2995
+ case "PS256":
2996
+ case "PS384":
2997
+ case "PS512":
2998
+ return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
2999
+ case "RS256":
3000
+ case "RS384":
3001
+ case "RS512":
3002
+ return { hash, name: "RSASSA-PKCS1-v1_5" };
3003
+ case "ES256":
3004
+ case "ES384":
3005
+ case "ES512":
3006
+ return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
3007
+ case "Ed25519":
3008
+ case "EdDSA":
3009
+ return { name: "Ed25519" };
3010
+ case "ML-DSA-44":
3011
+ case "ML-DSA-65":
3012
+ case "ML-DSA-87":
3013
+ return { name: alg };
3014
+ default:
3015
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
3016
+ }
3017
+ }
3018
+ async function getSigKey(alg, key, usage) {
3019
+ if (key instanceof Uint8Array) {
3020
+ if (!alg.startsWith("HS")) {
3021
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
3022
+ }
3023
+ return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]);
3024
+ }
3025
+ checkSigCryptoKey(key, alg, usage);
3026
+ return key;
3027
+ }
3028
+ async function verify(alg, key, signature, data) {
3029
+ const cryptoKey = await getSigKey(alg, key, "verify");
3030
+ checkKeyLength(alg, cryptoKey);
3031
+ const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
3032
+ try {
3033
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
3034
+ } catch {
3035
+ return false;
3036
+ }
3037
+ }
3038
+ var init_signing = __esm(() => {
3039
+ init_errors2();
3040
+ });
3041
+
3042
+ // ../../node_modules/jose/dist/webapi/lib/jwk_to_key.js
3043
+ function subtleMapping(jwk) {
3044
+ let algorithm;
3045
+ let keyUsages;
3046
+ switch (jwk.kty) {
3047
+ case "AKP": {
3048
+ switch (jwk.alg) {
3049
+ case "ML-DSA-44":
3050
+ case "ML-DSA-65":
3051
+ case "ML-DSA-87":
3052
+ algorithm = { name: jwk.alg };
3053
+ keyUsages = jwk.priv ? ["sign"] : ["verify"];
3054
+ break;
3055
+ default:
3056
+ throw new JOSENotSupported(unsupportedAlg);
3057
+ }
3058
+ break;
3059
+ }
3060
+ case "RSA": {
3061
+ switch (jwk.alg) {
3062
+ case "PS256":
3063
+ case "PS384":
3064
+ case "PS512":
3065
+ algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
2755
3066
  keyUsages = jwk.d ? ["sign"] : ["verify"];
2756
3067
  break;
2757
3068
  case "RS256":
@@ -2771,22 +3082,19 @@ function subtleMapping(jwk) {
2771
3082
  keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
2772
3083
  break;
2773
3084
  default:
2774
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
3085
+ throw new JOSENotSupported(unsupportedAlg);
2775
3086
  }
2776
3087
  break;
2777
3088
  }
2778
3089
  case "EC": {
2779
3090
  switch (jwk.alg) {
2780
3091
  case "ES256":
2781
- algorithm = { name: "ECDSA", namedCurve: "P-256" };
2782
- keyUsages = jwk.d ? ["sign"] : ["verify"];
2783
- break;
2784
3092
  case "ES384":
2785
- algorithm = { name: "ECDSA", namedCurve: "P-384" };
2786
- keyUsages = jwk.d ? ["sign"] : ["verify"];
2787
- break;
2788
3093
  case "ES512":
2789
- algorithm = { name: "ECDSA", namedCurve: "P-521" };
3094
+ algorithm = {
3095
+ name: "ECDSA",
3096
+ namedCurve: { ES256: "P-256", ES384: "P-384", ES512: "P-521" }[jwk.alg]
3097
+ };
2790
3098
  keyUsages = jwk.d ? ["sign"] : ["verify"];
2791
3099
  break;
2792
3100
  case "ECDH-ES":
@@ -2797,7 +3105,7 @@ function subtleMapping(jwk) {
2797
3105
  keyUsages = jwk.d ? ["deriveBits"] : [];
2798
3106
  break;
2799
3107
  default:
2800
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
3108
+ throw new JOSENotSupported(unsupportedAlg);
2801
3109
  }
2802
3110
  break;
2803
3111
  }
@@ -2816,7 +3124,7 @@ function subtleMapping(jwk) {
2816
3124
  keyUsages = jwk.d ? ["deriveBits"] : [];
2817
3125
  break;
2818
3126
  default:
2819
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
3127
+ throw new JOSENotSupported(unsupportedAlg);
2820
3128
  }
2821
3129
  break;
2822
3130
  }
@@ -2837,100 +3145,11 @@ async function jwkToKey(jwk) {
2837
3145
  delete keyData.use;
2838
3146
  return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
2839
3147
  }
3148
+ var unsupportedAlg = 'Invalid or unsupported JWK "alg" (Algorithm) Parameter value';
2840
3149
  var init_jwk_to_key = __esm(() => {
2841
3150
  init_errors2();
2842
3151
  });
2843
3152
 
2844
- // ../../node_modules/jose/dist/webapi/key/import.js
2845
- async function importJWK(jwk, alg, options) {
2846
- if (!isObject(jwk)) {
2847
- throw new TypeError("JWK must be an object");
2848
- }
2849
- let ext;
2850
- alg ??= jwk.alg;
2851
- ext ??= options?.extractable ?? jwk.ext;
2852
- switch (jwk.kty) {
2853
- case "oct":
2854
- if (typeof jwk.k !== "string" || !jwk.k) {
2855
- throw new TypeError('missing "k" (Key Value) Parameter value');
2856
- }
2857
- return decode(jwk.k);
2858
- case "RSA":
2859
- if ("oth" in jwk && jwk.oth !== undefined) {
2860
- throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
2861
- }
2862
- return jwkToKey({ ...jwk, alg, ext });
2863
- case "AKP": {
2864
- if (typeof jwk.alg !== "string" || !jwk.alg) {
2865
- throw new TypeError('missing "alg" (Algorithm) Parameter value');
2866
- }
2867
- if (alg !== undefined && alg !== jwk.alg) {
2868
- throw new TypeError("JWK alg and alg option value mismatch");
2869
- }
2870
- return jwkToKey({ ...jwk, ext });
2871
- }
2872
- case "EC":
2873
- case "OKP":
2874
- return jwkToKey({ ...jwk, alg, ext });
2875
- default:
2876
- throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
2877
- }
2878
- }
2879
- var init_import = __esm(() => {
2880
- init_base64url();
2881
- init_jwk_to_key();
2882
- init_errors2();
2883
- });
2884
-
2885
- // ../../node_modules/jose/dist/webapi/lib/validate_crit.js
2886
- function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
2887
- if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
2888
- throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
2889
- }
2890
- if (!protectedHeader || protectedHeader.crit === undefined) {
2891
- return new Set;
2892
- }
2893
- if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
2894
- throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
2895
- }
2896
- let recognized;
2897
- if (recognizedOption !== undefined) {
2898
- recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
2899
- } else {
2900
- recognized = recognizedDefault;
2901
- }
2902
- for (const parameter of protectedHeader.crit) {
2903
- if (!recognized.has(parameter)) {
2904
- throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
2905
- }
2906
- if (joseHeader[parameter] === undefined) {
2907
- throw new Err(`Extension Header Parameter "${parameter}" is missing`);
2908
- }
2909
- if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {
2910
- throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
2911
- }
2912
- }
2913
- return new Set(protectedHeader.crit);
2914
- }
2915
- var init_validate_crit = __esm(() => {
2916
- init_errors2();
2917
- });
2918
-
2919
- // ../../node_modules/jose/dist/webapi/lib/validate_algorithms.js
2920
- function validateAlgorithms(option, algorithms) {
2921
- if (algorithms !== undefined && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
2922
- throw new TypeError(`"${option}" option must be an array of strings`);
2923
- }
2924
- if (!algorithms) {
2925
- return;
2926
- }
2927
- return new Set(algorithms);
2928
- }
2929
-
2930
- // ../../node_modules/jose/dist/webapi/lib/is_jwk.js
2931
- var isJWK = (key) => isObject(key) && typeof key.kty === "string", isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string"), isPublicJWK = (key) => key.kty !== "oct" && key.d === undefined && key.priv === undefined, isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
2932
- var init_is_jwk = () => {};
2933
-
2934
3153
  // ../../node_modules/jose/dist/webapi/lib/normalize_key.js
2935
3154
  async function normalizeKey(key, alg) {
2936
3155
  if (key instanceof Uint8Array) {
@@ -2963,7 +3182,7 @@ async function normalizeKey(key, alg) {
2963
3182
  }
2964
3183
  throw new Error("unreachable");
2965
3184
  }
2966
- var cache, handleJWK = async (key, jwk, alg, freeze = false) => {
3185
+ var unusableForAlg = "given KeyObject instance cannot be used for this algorithm", cache, handleJWK = async (key, jwk, alg, freeze = false) => {
2967
3186
  cache ||= new WeakMap;
2968
3187
  let cached = cache.get(key);
2969
3188
  if (cached?.[alg]) {
@@ -2995,13 +3214,13 @@ var cache, handleJWK = async (key, jwk, alg, freeze = false) => {
2995
3214
  case "ECDH-ES+A256KW":
2996
3215
  break;
2997
3216
  default:
2998
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
3217
+ throw new TypeError(unusableForAlg);
2999
3218
  }
3000
3219
  cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
3001
3220
  }
3002
3221
  if (keyObject.asymmetricKeyType === "ed25519") {
3003
3222
  if (alg !== "EdDSA" && alg !== "Ed25519") {
3004
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
3223
+ throw new TypeError(unusableForAlg);
3005
3224
  }
3006
3225
  cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
3007
3226
  isPublic ? "verify" : "sign"
@@ -3012,7 +3231,7 @@ var cache, handleJWK = async (key, jwk, alg, freeze = false) => {
3012
3231
  case "ml-dsa-65":
3013
3232
  case "ml-dsa-87": {
3014
3233
  if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {
3015
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
3234
+ throw new TypeError(unusableForAlg);
3016
3235
  }
3017
3236
  cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
3018
3237
  isPublic ? "verify" : "sign"
@@ -3041,7 +3260,7 @@ var cache, handleJWK = async (key, jwk, alg, freeze = false) => {
3041
3260
  hash = "SHA-512";
3042
3261
  break;
3043
3262
  default:
3044
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
3263
+ throw new TypeError(unusableForAlg);
3045
3264
  }
3046
3265
  if (alg.startsWith("RSA-OAEP")) {
3047
3266
  return keyObject.toCryptoKey({
@@ -3062,21 +3281,10 @@ var cache, handleJWK = async (key, jwk, alg, freeze = false) => {
3062
3281
  ]);
3063
3282
  const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
3064
3283
  if (!namedCurve) {
3065
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
3066
- }
3067
- if (alg === "ES256" && namedCurve === "P-256") {
3068
- cryptoKey = keyObject.toCryptoKey({
3069
- name: "ECDSA",
3070
- namedCurve
3071
- }, extractable, [isPublic ? "verify" : "sign"]);
3072
- }
3073
- if (alg === "ES384" && namedCurve === "P-384") {
3074
- cryptoKey = keyObject.toCryptoKey({
3075
- name: "ECDSA",
3076
- namedCurve
3077
- }, extractable, [isPublic ? "verify" : "sign"]);
3284
+ throw new TypeError(unusableForAlg);
3078
3285
  }
3079
- if (alg === "ES512" && namedCurve === "P-521") {
3286
+ const expectedCurve = { ES256: "P-256", ES384: "P-384", ES512: "P-521" };
3287
+ if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) {
3080
3288
  cryptoKey = keyObject.toCryptoKey({
3081
3289
  name: "ECDSA",
3082
3290
  namedCurve
@@ -3090,7 +3298,7 @@ var cache, handleJWK = async (key, jwk, alg, freeze = false) => {
3090
3298
  }
3091
3299
  }
3092
3300
  if (!cryptoKey) {
3093
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
3301
+ throw new TypeError(unusableForAlg);
3094
3302
  }
3095
3303
  if (!cached) {
3096
3304
  cache.set(keyObject, { [alg]: cryptoKey });
@@ -3100,49 +3308,134 @@ var cache, handleJWK = async (key, jwk, alg, freeze = false) => {
3100
3308
  return cryptoKey;
3101
3309
  };
3102
3310
  var init_normalize_key = __esm(() => {
3103
- init_is_jwk();
3104
3311
  init_base64url();
3105
3312
  init_jwk_to_key();
3106
3313
  });
3107
3314
 
3108
- // ../../node_modules/jose/dist/webapi/lib/check_key_type.js
3109
- function checkKeyType(alg, key, usage) {
3110
- switch (alg.substring(0, 2)) {
3111
- case "A1":
3112
- case "A2":
3113
- case "di":
3114
- case "HS":
3115
- case "PB":
3116
- symmetricTypeCheck(alg, key, usage);
3117
- break;
3315
+ // ../../node_modules/jose/dist/webapi/key/import.js
3316
+ async function importJWK(jwk, alg, options) {
3317
+ if (!isObject(jwk)) {
3318
+ throw new TypeError("JWK must be an object");
3319
+ }
3320
+ let ext;
3321
+ alg ??= jwk.alg;
3322
+ ext ??= options?.extractable ?? jwk.ext;
3323
+ switch (jwk.kty) {
3324
+ case "oct":
3325
+ if (typeof jwk.k !== "string" || !jwk.k) {
3326
+ throw new TypeError('missing "k" (Key Value) Parameter value');
3327
+ }
3328
+ return decode(jwk.k);
3329
+ case "RSA":
3330
+ if ("oth" in jwk && jwk.oth !== undefined) {
3331
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
3332
+ }
3333
+ return jwkToKey({ ...jwk, alg, ext });
3334
+ case "AKP": {
3335
+ if (typeof jwk.alg !== "string" || !jwk.alg) {
3336
+ throw new TypeError('missing "alg" (Algorithm) Parameter value');
3337
+ }
3338
+ if (alg !== undefined && alg !== jwk.alg) {
3339
+ throw new TypeError("JWK alg and alg option value mismatch");
3340
+ }
3341
+ return jwkToKey({ ...jwk, ext });
3342
+ }
3343
+ case "EC":
3344
+ case "OKP":
3345
+ return jwkToKey({ ...jwk, alg, ext });
3118
3346
  default:
3119
- asymmetricTypeCheck(alg, key, usage);
3347
+ throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
3120
3348
  }
3121
3349
  }
3122
- var tag = (key) => key?.[Symbol.toStringTag], jwkMatchesOp = (alg, key, usage) => {
3123
- if (key.use !== undefined) {
3124
- let expected;
3125
- switch (usage) {
3126
- case "sign":
3127
- case "verify":
3128
- expected = "sig";
3129
- break;
3130
- case "encrypt":
3131
- case "decrypt":
3132
- expected = "enc";
3133
- break;
3134
- }
3135
- if (key.use !== expected) {
3136
- throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
3137
- }
3350
+ var init_import = __esm(() => {
3351
+ init_base64url();
3352
+ init_jwk_to_key();
3353
+ init_errors2();
3354
+ });
3355
+
3356
+ // ../../node_modules/jose/dist/webapi/lib/validate_crit.js
3357
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
3358
+ if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
3359
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
3138
3360
  }
3139
- if (key.alg !== undefined && key.alg !== alg) {
3140
- throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
3361
+ if (!protectedHeader || protectedHeader.crit === undefined) {
3362
+ return new Set;
3141
3363
  }
3142
- if (Array.isArray(key.key_ops)) {
3143
- let expectedKeyOp;
3144
- switch (true) {
3145
- case (usage === "sign" || usage === "verify"):
3364
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
3365
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
3366
+ }
3367
+ let recognized;
3368
+ if (recognizedOption !== undefined) {
3369
+ recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
3370
+ } else {
3371
+ recognized = recognizedDefault;
3372
+ }
3373
+ for (const parameter of protectedHeader.crit) {
3374
+ if (!recognized.has(parameter)) {
3375
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
3376
+ }
3377
+ if (joseHeader[parameter] === undefined) {
3378
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
3379
+ }
3380
+ if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {
3381
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
3382
+ }
3383
+ }
3384
+ return new Set(protectedHeader.crit);
3385
+ }
3386
+ var init_validate_crit = __esm(() => {
3387
+ init_errors2();
3388
+ });
3389
+
3390
+ // ../../node_modules/jose/dist/webapi/lib/validate_algorithms.js
3391
+ function validateAlgorithms(option, algorithms) {
3392
+ if (algorithms !== undefined && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
3393
+ throw new TypeError(`"${option}" option must be an array of strings`);
3394
+ }
3395
+ if (!algorithms) {
3396
+ return;
3397
+ }
3398
+ return new Set(algorithms);
3399
+ }
3400
+
3401
+ // ../../node_modules/jose/dist/webapi/lib/check_key_type.js
3402
+ function checkKeyType(alg, key, usage) {
3403
+ switch (alg.substring(0, 2)) {
3404
+ case "A1":
3405
+ case "A2":
3406
+ case "di":
3407
+ case "HS":
3408
+ case "PB":
3409
+ symmetricTypeCheck(alg, key, usage);
3410
+ break;
3411
+ default:
3412
+ asymmetricTypeCheck(alg, key, usage);
3413
+ }
3414
+ }
3415
+ var tag = (key) => key?.[Symbol.toStringTag], jwkMatchesOp = (alg, key, usage) => {
3416
+ if (key.use !== undefined) {
3417
+ let expected;
3418
+ switch (usage) {
3419
+ case "sign":
3420
+ case "verify":
3421
+ expected = "sig";
3422
+ break;
3423
+ case "encrypt":
3424
+ case "decrypt":
3425
+ expected = "enc";
3426
+ break;
3427
+ }
3428
+ if (key.use !== expected) {
3429
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
3430
+ }
3431
+ }
3432
+ if (key.alg !== undefined && key.alg !== alg) {
3433
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
3434
+ }
3435
+ if (Array.isArray(key.key_ops)) {
3436
+ let expectedKeyOp;
3437
+ switch (true) {
3438
+ case (usage === "sign" || usage === "verify"):
3146
3439
  case alg === "dir":
3147
3440
  case alg.includes("CBC-HS"):
3148
3441
  expectedKeyOp = usage;
@@ -3221,73 +3514,7 @@ var tag = (key) => key?.[Symbol.toStringTag], jwkMatchesOp = (alg, key, usage) =
3221
3514
  }
3222
3515
  }
3223
3516
  };
3224
- var init_check_key_type = __esm(() => {
3225
- init_is_jwk();
3226
- });
3227
-
3228
- // ../../node_modules/jose/dist/webapi/lib/subtle_dsa.js
3229
- function subtleAlgorithm(alg, algorithm) {
3230
- const hash = `SHA-${alg.slice(-3)}`;
3231
- switch (alg) {
3232
- case "HS256":
3233
- case "HS384":
3234
- case "HS512":
3235
- return { hash, name: "HMAC" };
3236
- case "PS256":
3237
- case "PS384":
3238
- case "PS512":
3239
- return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
3240
- case "RS256":
3241
- case "RS384":
3242
- case "RS512":
3243
- return { hash, name: "RSASSA-PKCS1-v1_5" };
3244
- case "ES256":
3245
- case "ES384":
3246
- case "ES512":
3247
- return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
3248
- case "Ed25519":
3249
- case "EdDSA":
3250
- return { name: "Ed25519" };
3251
- case "ML-DSA-44":
3252
- case "ML-DSA-65":
3253
- case "ML-DSA-87":
3254
- return { name: alg };
3255
- default:
3256
- throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
3257
- }
3258
- }
3259
- var init_subtle_dsa = __esm(() => {
3260
- init_errors2();
3261
- });
3262
-
3263
- // ../../node_modules/jose/dist/webapi/lib/get_sign_verify_key.js
3264
- async function getSigKey(alg, key, usage) {
3265
- if (key instanceof Uint8Array) {
3266
- if (!alg.startsWith("HS")) {
3267
- throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
3268
- }
3269
- return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]);
3270
- }
3271
- checkSigCryptoKey(key, alg, usage);
3272
- return key;
3273
- }
3274
- var init_get_sign_verify_key = () => {};
3275
-
3276
- // ../../node_modules/jose/dist/webapi/lib/verify.js
3277
- async function verify(alg, key, signature, data) {
3278
- const cryptoKey = await getSigKey(alg, key, "verify");
3279
- checkKeyLength(alg, cryptoKey);
3280
- const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
3281
- try {
3282
- return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
3283
- } catch {
3284
- return false;
3285
- }
3286
- }
3287
- var init_verify = __esm(() => {
3288
- init_subtle_dsa();
3289
- init_get_sign_verify_key();
3290
- });
3517
+ var init_check_key_type = () => {};
3291
3518
 
3292
3519
  // ../../node_modules/jose/dist/webapi/jws/flattened/verify.js
3293
3520
  async function flattenedVerify(jws, key, options) {
@@ -3355,12 +3582,7 @@ async function flattenedVerify(jws, key, options) {
3355
3582
  }
3356
3583
  checkKeyType(alg, key, "verify");
3357
3584
  const data = concat(jws.protected !== undefined ? encode(jws.protected) : new Uint8Array, encode("."), typeof jws.payload === "string" ? b64 ? encode(jws.payload) : encoder.encode(jws.payload) : jws.payload);
3358
- let signature;
3359
- try {
3360
- signature = decode(jws.signature);
3361
- } catch {
3362
- throw new JWSInvalid("Failed to base64url decode the signature");
3363
- }
3585
+ const signature = decodeBase64url(jws.signature, "signature", JWSInvalid);
3364
3586
  const k = await normalizeKey(key, alg);
3365
3587
  const verified = await verify(alg, k, signature, data);
3366
3588
  if (!verified) {
@@ -3368,11 +3590,7 @@ async function flattenedVerify(jws, key, options) {
3368
3590
  }
3369
3591
  let payload;
3370
3592
  if (b64) {
3371
- try {
3372
- payload = decode(jws.payload);
3373
- } catch {
3374
- throw new JWSInvalid("Failed to base64url decode the payload");
3375
- }
3593
+ payload = decodeBase64url(jws.payload, "payload", JWSInvalid);
3376
3594
  } else if (typeof jws.payload === "string") {
3377
3595
  payload = encoder.encode(jws.payload);
3378
3596
  } else {
@@ -3390,11 +3608,12 @@ async function flattenedVerify(jws, key, options) {
3390
3608
  }
3391
3609
  return result;
3392
3610
  }
3393
- var init_verify2 = __esm(() => {
3611
+ var init_verify = __esm(() => {
3394
3612
  init_base64url();
3395
- init_verify();
3613
+ init_signing();
3396
3614
  init_errors2();
3397
3615
  init_buffer_utils();
3616
+ init_helpers();
3398
3617
  init_check_key_type();
3399
3618
  init_validate_crit();
3400
3619
  init_normalize_key();
@@ -3419,8 +3638,8 @@ async function compactVerify(jws, key, options) {
3419
3638
  }
3420
3639
  return result;
3421
3640
  }
3422
- var init_verify3 = __esm(() => {
3423
- init_verify2();
3641
+ var init_verify2 = __esm(() => {
3642
+ init_verify();
3424
3643
  init_errors2();
3425
3644
  init_buffer_utils();
3426
3645
  });
@@ -3664,8 +3883,8 @@ async function jwtVerify(jwt, key, options) {
3664
3883
  }
3665
3884
  return result;
3666
3885
  }
3667
- var init_verify4 = __esm(() => {
3668
- init_verify3();
3886
+ var init_verify3 = __esm(() => {
3887
+ init_verify2();
3669
3888
  init_jwt_claims_set();
3670
3889
  init_errors2();
3671
3890
  });
@@ -3950,7 +4169,7 @@ var init_remote = __esm(() => {
3950
4169
  init_local();
3951
4170
  if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
3952
4171
  const NAME = "jose";
3953
- const VERSION = "v6.1.3";
4172
+ const VERSION = "v6.2.1";
3954
4173
  USER_AGENT = `${NAME}/${VERSION}`;
3955
4174
  }
3956
4175
  customFetch = Symbol();
@@ -3959,7 +4178,8 @@ var init_remote = __esm(() => {
3959
4178
 
3960
4179
  // ../../node_modules/jose/dist/webapi/index.js
3961
4180
  var init_webapi = __esm(() => {
3962
- init_verify4();
4181
+ init_verify3();
4182
+ init_local();
3963
4183
  init_remote();
3964
4184
  init_errors2();
3965
4185
  });
@@ -4164,7 +4384,7 @@ function getRemoteJwks(jwksUrl, config) {
4164
4384
  if (cached) {
4165
4385
  JWKS_CACHE.delete(jwksUrl);
4166
4386
  }
4167
- const jwks = createRemoteJWKSet(new URL(jwksUrl));
4387
+ const jwks = jwksUrl.startsWith("data:") ? createLocalJWKSet(parseDataUriJson(jwksUrl)) : createRemoteJWKSet(new URL(jwksUrl));
4168
4388
  const configuredTtl = config?.jwksCacheTtlMs;
4169
4389
  const ttlMs = resolveJwksCacheTtlMs(configuredTtl);
4170
4390
  JWKS_CACHE.set(jwksUrl, {
@@ -4173,6 +4393,24 @@ function getRemoteJwks(jwksUrl, config) {
4173
4393
  });
4174
4394
  return jwks;
4175
4395
  }
4396
+ function parseDataUriJson(dataUri) {
4397
+ const match = /^data:([^;,]+)?(?:;charset=[^;,]+)?(;base64)?,(.*)$/i.exec(dataUri);
4398
+ if (!match) {
4399
+ throw new JWTValidationError("INVALID_TOKEN", "Invalid JWKS data URI");
4400
+ }
4401
+ const [, , isBase64, payload] = match;
4402
+ const jsonText = isBase64 ? decodeBase642(payload) : decodeURIComponent(payload);
4403
+ return JSON.parse(jsonText);
4404
+ }
4405
+ function decodeBase642(value) {
4406
+ if (typeof Buffer !== "undefined") {
4407
+ return Buffer.from(value, "base64").toString("utf8");
4408
+ }
4409
+ if (typeof atob === "function") {
4410
+ return new TextDecoder().decode(Uint8Array.from(atob(value), (char) => char.charCodeAt(0)));
4411
+ }
4412
+ throw new JWTValidationError("INVALID_TOKEN", "Base64 decoding is unavailable");
4413
+ }
4176
4414
  function resolveJwksCacheTtlMs(configuredTtl) {
4177
4415
  if (configuredTtl === undefined) {
4178
4416
  return DEFAULT_JWKS_CACHE_TTL_MS;
@@ -4207,6 +4445,7 @@ async function verifyJwt(token, config) {
4207
4445
  const options = {
4208
4446
  issuer: effectiveConfig.issuer,
4209
4447
  audience: effectiveConfig.audience,
4448
+ algorithms: effectiveConfig.algorithms,
4210
4449
  clockTolerance: effectiveConfig.clockTolerance ?? DEFAULT_CLOCK_TOLERANCE_SECONDS
4211
4450
  };
4212
4451
  let payload;
@@ -4764,6 +5003,207 @@ var init_auth = __esm(() => {
4764
5003
  init_auth_config_service();
4765
5004
  });
4766
5005
 
5006
+ // ../core/dist/components/manifest.js
5007
+ var COMPONENT_MANIFEST_SYMBOL;
5008
+ var init_manifest = __esm(() => {
5009
+ COMPONENT_MANIFEST_SYMBOL = Symbol.for("concave.componentManifest");
5010
+ });
5011
+
5012
+ // ../core/dist/id-codec/index.js
5013
+ var init_id_codec = __esm(() => {
5014
+ init_base32();
5015
+ init_document_id();
5016
+ });
5017
+
5018
+ // ../core/dist/system/system-tables.js
5019
+ function getSystemTableDefinition(name) {
5020
+ return SYSTEM_TABLE_DEFINITIONS.find((definition) => definition.name === name) ?? null;
5021
+ }
5022
+ function isPublicSystemTable(name) {
5023
+ return getSystemTableDefinition(name)?.visibility === "public";
5024
+ }
5025
+ function createTableInfo(name, tableNumber, componentPath = "", options = {}) {
5026
+ const fullName = getFullTableName(name, componentPath);
5027
+ return {
5028
+ tableNumber,
5029
+ name,
5030
+ componentPath: isSystemTableName(name) ? "" : componentPath,
5031
+ fullName,
5032
+ isSystem: options.isSystem ?? isSystemTableName(name),
5033
+ visibility: options.visibility ?? (isPublicSystemTable(name) ? "public" : "private"),
5034
+ state: "active",
5035
+ createdAt: options.createdAt ?? Date.now()
5036
+ };
5037
+ }
5038
+ function getReservedSystemTables() {
5039
+ return SYSTEM_TABLE_DEFINITIONS.map((definition) => createTableInfo(definition.name, SYSTEM_TABLE_NUMBERS[definition.name], "", {
5040
+ isSystem: true,
5041
+ visibility: definition.visibility
5042
+ }));
5043
+ }
5044
+ function tableInfoFromStoredDocument(value) {
5045
+ if (!value) {
5046
+ return null;
5047
+ }
5048
+ const name = typeof value.name === "string" ? value.name : null;
5049
+ const tableNumber = typeof value.tableNumber === "number" ? value.tableNumber : null;
5050
+ if (!name || !tableNumber) {
5051
+ return null;
5052
+ }
5053
+ const componentPath = typeof value.componentPath === "string" ? value.componentPath : "";
5054
+ const fullName = typeof value.fullName === "string" ? value.fullName : getFullTableName(name, componentPath);
5055
+ return {
5056
+ tableNumber,
5057
+ name,
5058
+ componentPath,
5059
+ fullName,
5060
+ isSystem: value.isSystem === true,
5061
+ visibility: value.visibility === "private" ? "private" : "public",
5062
+ state: "active",
5063
+ createdAt: typeof value.createdAt === "number" ? value.createdAt : Date.now()
5064
+ };
5065
+ }
5066
+ function nextUserTableNumber(tables) {
5067
+ let next = FIRST_USER_TABLE_NUMBER;
5068
+ for (const table of tables) {
5069
+ if (table.tableNumber >= next) {
5070
+ next = table.tableNumber + 1;
5071
+ }
5072
+ }
5073
+ return next;
5074
+ }
5075
+ function createSystemMetadata(partial) {
5076
+ const now = partial?.updatedAt ?? Date.now();
5077
+ return {
5078
+ version: 1,
5079
+ bootstrapped: true,
5080
+ tableIdStrategy: "registry_u32",
5081
+ developerIdCodec: "convex_base32",
5082
+ nextUserTableNumber: partial?.nextUserTableNumber ?? FIRST_USER_TABLE_NUMBER,
5083
+ registryVersion: partial?.registryVersion ?? now,
5084
+ runtimeMetadataVersion: partial?.runtimeMetadataVersion,
5085
+ bootstrappedAt: partial?.bootstrappedAt ?? now,
5086
+ updatedAt: now
5087
+ };
5088
+ }
5089
+ async function readSystemMetadata(docstore) {
5090
+ const metadata = await docstore.getGlobal(SYSTEM_METADATA_GLOBAL_KEY);
5091
+ if (!metadata || metadata.bootstrapped !== true || metadata.version !== 1) {
5092
+ return null;
5093
+ }
5094
+ return createSystemMetadata({
5095
+ nextUserTableNumber: metadata.nextUserTableNumber,
5096
+ registryVersion: metadata.registryVersion ?? metadata.updatedAt,
5097
+ runtimeMetadataVersion: metadata.runtimeMetadataVersion,
5098
+ bootstrappedAt: metadata.bootstrappedAt,
5099
+ updatedAt: metadata.updatedAt
5100
+ });
5101
+ }
5102
+ function createTableNumberReservationKey(tableNumber) {
5103
+ return `${TABLE_NUMBER_RESERVATION_GLOBAL_PREFIX}${tableNumber}`;
5104
+ }
5105
+ async function ensureSystemTablesBootstrapped(docstore) {
5106
+ const existingMetadata = await readSystemMetadata(docstore);
5107
+ if (existingMetadata?.version === 1 && existingMetadata.bootstrapped) {
5108
+ return;
5109
+ }
5110
+ const now = Date.now();
5111
+ const tableInfos = getReservedSystemTables();
5112
+ const existingEntries = await docstore.scan(stringToHex("_tables"));
5113
+ const existingByName = new Map;
5114
+ for (const entry of existingEntries) {
5115
+ const info = tableInfoFromStoredDocument(entry.value.value);
5116
+ if (info) {
5117
+ existingByName.set(info.fullName, info);
5118
+ }
5119
+ }
5120
+ const docs = [];
5121
+ const oracle = docstore.timestampOracle;
5122
+ const allocateTimestamp = oracle?.allocateTimestamp?.bind(oracle) ?? (() => BigInt(Date.now()));
5123
+ for (const table of tableInfos) {
5124
+ const existing = existingByName.get(table.fullName);
5125
+ const createdAt = existing?.createdAt ?? now;
5126
+ docs.push(createTableMetadataEntry(table, allocateTimestamp(), createdAt));
5127
+ }
5128
+ if (docs.length > 0) {
5129
+ await docstore.write(docs, new Set, "Overwrite");
5130
+ }
5131
+ const metadata = createSystemMetadata({
5132
+ nextUserTableNumber: nextUserTableNumber([...tableInfos, ...existingByName.values()]),
5133
+ registryVersion: now,
5134
+ bootstrappedAt: existingMetadata?.bootstrappedAt ?? now,
5135
+ updatedAt: now
5136
+ });
5137
+ await docstore.writeGlobal(SYSTEM_METADATA_GLOBAL_KEY, metadata);
5138
+ }
5139
+ function createTableMetadataEntryForUserTable(table, timestamp2) {
5140
+ return createTableMetadataEntry(table, timestamp2, table.createdAt);
5141
+ }
5142
+ function createTableMetadataEntry(table, timestamp2, createdAt) {
5143
+ const docId = createTableMetadataDocumentId(table.fullName);
5144
+ const developerId = encodeDocumentId(SYSTEM_TABLE_NUMBERS._tables, stableMetadataInternalIdBytes(table.fullName));
5145
+ const storedTable = {
5146
+ _id: developerId,
5147
+ _creationTime: Number(timestamp2),
5148
+ name: table.name,
5149
+ componentPath: table.componentPath,
5150
+ fullName: table.fullName,
5151
+ tableNumber: table.tableNumber,
5152
+ isSystem: table.isSystem,
5153
+ visibility: table.visibility,
5154
+ state: table.state,
5155
+ createdAt
5156
+ };
5157
+ return {
5158
+ ts: timestamp2,
5159
+ id: docId,
5160
+ value: {
5161
+ id: docId,
5162
+ value: storedTable
5163
+ },
5164
+ prev_ts: null
5165
+ };
5166
+ }
5167
+ function createTableMetadataDocumentId(fullTableName) {
5168
+ const internalIdBytes = stableMetadataInternalIdBytes(fullTableName);
5169
+ return {
5170
+ table: stringToHex("_tables"),
5171
+ internalId: internalIdToHex(internalIdBytes),
5172
+ tableNumber: SYSTEM_TABLE_NUMBERS._tables
5173
+ };
5174
+ }
5175
+ function stableMetadataInternalIdBytes(fullTableName) {
5176
+ const bytes = new Uint8Array(16);
5177
+ const input = new TextEncoder().encode(`table:${fullTableName}`);
5178
+ for (let i2 = 0;i2 < input.length; i2 += 1) {
5179
+ const target = i2 % 16;
5180
+ bytes[target] = bytes[target] * 33 + input[i2] & 255;
5181
+ }
5182
+ return bytes;
5183
+ }
5184
+ function isSystemTableName(name) {
5185
+ return Object.hasOwn(SYSTEM_TABLE_NUMBERS, name);
5186
+ }
5187
+ var SYSTEM_METADATA_GLOBAL_KEY = "concave:system_metadata:v1", TABLE_NUMBER_RESERVATION_GLOBAL_PREFIX = "concave:table_number:", SYSTEM_TABLE_DEFINITIONS;
5188
+ var init_system_tables = __esm(() => {
5189
+ init_manifest();
5190
+ init_id_codec();
5191
+ init_interface();
5192
+ init_utils();
5193
+ init_module_loader();
5194
+ SYSTEM_TABLE_DEFINITIONS = [
5195
+ { name: "_tables", visibility: "public" },
5196
+ { name: "_scheduled_functions", visibility: "public" },
5197
+ { name: "_storage", visibility: "public" },
5198
+ { name: "_crons", visibility: "public" },
5199
+ { name: "_indexes", visibility: "private" },
5200
+ { name: "_schemas", visibility: "private" },
5201
+ { name: "_components", visibility: "private" },
5202
+ { name: "_component_definitions", visibility: "private" },
5203
+ { name: "_schema_validation_progress", visibility: "private" }
5204
+ ];
5205
+ });
5206
+
4767
5207
  // ../core/dist/system/internal.js
4768
5208
  function requireSystemCapability(capability) {
4769
5209
  const principal2 = getPrincipal();
@@ -4777,34 +5217,17 @@ function createSystemFunctions(deps) {
4777
5217
  return {
4778
5218
  systemListComponents: query({
4779
5219
  args: {},
4780
- handler: async (_ctx) => {
5220
+ handler: async (ctx) => {
4781
5221
  requireSystemCapability("components:read");
4782
- const modules = await listRegisteredModules();
4783
- const componentPaths = new Set;
4784
- componentPaths.add("");
4785
- for (const module of modules) {
4786
- if (module.componentPath) {
4787
- componentPaths.add(module.componentPath);
4788
- }
4789
- }
4790
- const components = [];
4791
- for (const path of componentPaths) {
4792
- const componentModules = modules.filter((m) => path === "" ? !m.componentPath || m.componentPath === "" : m.componentPath === path);
4793
- const functions = await listSystemFunctions({ componentPath: path || undefined });
4794
- components.push({
4795
- path: path || "(root)",
4796
- isRoot: path === "",
4797
- moduleCount: componentModules.length,
5222
+ const components = await loadComponentRows(ctx);
5223
+ const withFunctionCounts = await Promise.all(components.map(async (component) => {
5224
+ const functions = await listSystemFunctions({ componentPath: component.componentPath || undefined });
5225
+ return {
5226
+ ...component,
4798
5227
  functionCount: functions.length
4799
- });
4800
- }
4801
- return components.sort((a, b) => {
4802
- if (a.isRoot)
4803
- return -1;
4804
- if (b.isRoot)
4805
- return 1;
4806
- return a.path.localeCompare(b.path);
4807
- });
5228
+ };
5229
+ }));
5230
+ return sortComponentRows(withFunctionCounts);
4808
5231
  }
4809
5232
  }),
4810
5233
  systemListTables: query({
@@ -4813,25 +5236,40 @@ function createSystemFunctions(deps) {
4813
5236
  requireSystemCapability("tables:read");
4814
5237
  const targetComponent = componentPath ?? "";
4815
5238
  const schema2 = await loadSchemaDefinition(targetComponent);
4816
- let tableEntries = [];
5239
+ const schemaTables = new Map;
4817
5240
  if (schema2?.tables) {
4818
- tableEntries = extractTablesFromSchema(schema2);
4819
- } else {
4820
- try {
4821
- const systemTables = await ctx.db.system.query("_tables").collect();
4822
- tableEntries = systemTables.map((table) => ({
4823
- name: table.name,
4824
- exported: {
4825
- indexes: table.indexes || [],
4826
- searchIndexes: table.searchIndexes || [],
4827
- vectorIndexes: table.vectorIndexes || [],
4828
- documentType: null
4829
- }
4830
- }));
4831
- } catch {
4832
- tableEntries = [];
5241
+ for (const table of extractTablesFromSchema(schema2)) {
5242
+ schemaTables.set(table.name, table);
4833
5243
  }
4834
5244
  }
5245
+ const discoveredTables = new Map;
5246
+ for (const name of schemaTables.keys()) {
5247
+ discoveredTables.set(name, {
5248
+ name,
5249
+ isSystem: isSystemTable(name),
5250
+ visibility: getDefaultSystemTableVisibility(name)
5251
+ });
5252
+ }
5253
+ try {
5254
+ const systemTables = await ctx.db.system.query("_tables").collect();
5255
+ discoveredTables.clear();
5256
+ for (const table of systemTables.filter((entry) => (entry.componentPath ?? "") === targetComponent)) {
5257
+ discoveredTables.set(table.name, {
5258
+ name: table.name,
5259
+ isSystem: table.isSystem === true || isSystemTable(table.name),
5260
+ visibility: table.visibility === "private" ? "private" : "public"
5261
+ });
5262
+ }
5263
+ } catch {}
5264
+ const tableEntries = Array.from(discoveredTables.values()).map((metadata) => ({
5265
+ ...metadata,
5266
+ exported: schemaTables.get(metadata.name)?.exported ?? {
5267
+ indexes: [],
5268
+ searchIndexes: [],
5269
+ vectorIndexes: [],
5270
+ documentType: null
5271
+ }
5272
+ }));
4835
5273
  const tableInfo = await Promise.all(tableEntries.map(async (table) => {
4836
5274
  const fullName = getFullTableName(table.name, targetComponent);
4837
5275
  const documentCount = await countDocuments(ctx, fullName);
@@ -4842,6 +5280,8 @@ function createSystemFunctions(deps) {
4842
5280
  name: table.name,
4843
5281
  fullName,
4844
5282
  componentPath: targetComponent || undefined,
5283
+ isSystem: table.isSystem,
5284
+ visibility: table.visibility,
4845
5285
  documentCount,
4846
5286
  indexes: buildIndexList(exported?.indexes),
4847
5287
  searchIndexes: searchIndexes.map((idx) => typeof idx === "string" ? idx : idx.indexDescriptor),
@@ -4875,7 +5315,7 @@ function createSystemFunctions(deps) {
4875
5315
  }
4876
5316
  try {
4877
5317
  const fullName = getFullTableName(tableName, targetComponent);
4878
- const sampleDoc = await ctx.db.query(fullName).first();
5318
+ const sampleDoc = await getTableQuery(ctx, fullName).first();
4879
5319
  const fields = sampleDoc ? Object.keys(sampleDoc).map((key) => ({
4880
5320
  name: key,
4881
5321
  type: typeof sampleDoc[key],
@@ -4910,7 +5350,7 @@ function createSystemFunctions(deps) {
4910
5350
  handler: async (ctx, args) => {
4911
5351
  requireSystemCapability("documents:read");
4912
5352
  const fullName = getFullTableName(args.tableName, args.componentPath ?? "");
4913
- let query2 = ctx.db.query(fullName);
5353
+ let query2 = getTableQuery(ctx, fullName);
4914
5354
  if (args.orderBy && args.orderBy !== "_creationTime") {
4915
5355
  const allDocs2 = await query2.collect();
4916
5356
  const sorted = allDocs2.sort((a, b) => {
@@ -4961,7 +5401,7 @@ function createSystemFunctions(deps) {
4961
5401
  handler: async (ctx, args) => {
4962
5402
  requireSystemCapability("documents:write");
4963
5403
  const fullName = getFullTableName(args.tableName, args.componentPath ?? "");
4964
- const docs = await ctx.db.query(fullName).collect();
5404
+ const docs = await getTableQuery(ctx, fullName).collect();
4965
5405
  for (const doc of docs) {
4966
5406
  await ctx.db.delete(doc._id);
4967
5407
  }
@@ -5257,6 +5697,83 @@ function resolveFunctionReference(functionPath, componentPath) {
5257
5697
  }
5258
5698
  return functionPath;
5259
5699
  }
5700
+ async function loadComponentRows(ctx) {
5701
+ try {
5702
+ const rows = await ctx.db.system.query("_components").collect();
5703
+ if (rows.length > 0) {
5704
+ return rows.map((row) => normalizeStoredComponentRow(row));
5705
+ }
5706
+ } catch {}
5707
+ const modules = await listRegisteredModules();
5708
+ const moduleCountByComponent = new Map;
5709
+ const hasHttpByComponent = new Map;
5710
+ const componentPaths = new Set([""]);
5711
+ for (const module of modules) {
5712
+ const componentPath = module.componentPath ?? "";
5713
+ componentPaths.add(componentPath);
5714
+ moduleCountByComponent.set(componentPath, (moduleCountByComponent.get(componentPath) ?? 0) + 1);
5715
+ if (module.path === "http") {
5716
+ hasHttpByComponent.set(componentPath, true);
5717
+ }
5718
+ }
5719
+ return Array.from(componentPaths).map((componentPath) => ({
5720
+ componentPath,
5721
+ path: componentPath || "(root)",
5722
+ isRoot: componentPath === "",
5723
+ parentPath: componentPath === "" ? null : componentPath.includes("/") ? componentPath.split("/").slice(0, -1).join("/") : "",
5724
+ depth: componentPath === "" ? 0 : componentPath.split("/").length,
5725
+ moduleCount: moduleCountByComponent.get(componentPath) ?? 0,
5726
+ childCount: 0,
5727
+ functionCount: 0,
5728
+ sourceType: "local",
5729
+ hasHttp: hasHttpByComponent.get(componentPath) === true
5730
+ }));
5731
+ }
5732
+ function normalizeStoredComponentRow(row) {
5733
+ const componentPath = typeof row.componentPath === "string" ? row.componentPath : "";
5734
+ return {
5735
+ componentPath,
5736
+ path: typeof row.displayPath === "string" ? row.displayPath : typeof row.path === "string" && row.path.length > 0 ? row.path : componentPath || "(root)",
5737
+ isRoot: row.isRoot === true || componentPath === "",
5738
+ parentPath: row.parentPath === null ? null : typeof row.parentPath === "string" ? row.parentPath : componentPath === "" ? null : "",
5739
+ depth: typeof row.depth === "number" ? row.depth : componentPath === "" ? 0 : componentPath.split("/").length,
5740
+ moduleCount: typeof row.moduleCount === "number" ? row.moduleCount : 0,
5741
+ childCount: typeof row.childCount === "number" ? row.childCount : 0,
5742
+ functionCount: 0,
5743
+ sourceType: row.sourceType === "npm" ? "npm" : row.sourceType === "local" ? "local" : undefined,
5744
+ sourcePath: typeof row.sourcePath === "string" ? row.sourcePath : undefined,
5745
+ packageName: typeof row.packageName === "string" ? row.packageName : undefined,
5746
+ packageVersion: typeof row.packageVersion === "string" ? row.packageVersion : undefined,
5747
+ hasHttp: row.hasHttp === true
5748
+ };
5749
+ }
5750
+ function sortComponentRows(rows) {
5751
+ const childrenByParent = new Map;
5752
+ for (const row of rows) {
5753
+ const parentKey = row.parentPath ?? null;
5754
+ const siblings = childrenByParent.get(parentKey) ?? [];
5755
+ siblings.push(row);
5756
+ childrenByParent.set(parentKey, siblings);
5757
+ }
5758
+ for (const siblings of childrenByParent.values()) {
5759
+ siblings.sort((a, b) => {
5760
+ if (a.isRoot)
5761
+ return -1;
5762
+ if (b.isRoot)
5763
+ return 1;
5764
+ return a.componentPath.localeCompare(b.componentPath);
5765
+ });
5766
+ }
5767
+ const ordered = [];
5768
+ const visit = (parentPath) => {
5769
+ for (const row of childrenByParent.get(parentPath) ?? []) {
5770
+ ordered.push(row);
5771
+ visit(row.componentPath);
5772
+ }
5773
+ };
5774
+ visit(null);
5775
+ return ordered;
5776
+ }
5260
5777
  async function loadSchemaDefinition(componentPath) {
5261
5778
  try {
5262
5779
  const module = await loadConvexModule("schema", {
@@ -5290,15 +5807,28 @@ function extractTableMetadata(schema2, tableName) {
5290
5807
  }
5291
5808
  async function countDocuments(ctx, tableName) {
5292
5809
  try {
5293
- const documents = await ctx.db.query(tableName).collect();
5810
+ const documents = await getTableQuery(ctx, tableName).collect();
5294
5811
  return documents.length;
5295
5812
  } catch (error) {
5296
5813
  console.warn(`Failed to count documents for table ${tableName}:`, error);
5297
5814
  return 0;
5298
5815
  }
5299
5816
  }
5300
- function buildIndexList(indexes) {
5301
- const base = ["by_id", "by_creation_time"];
5817
+ function getTableQuery(ctx, fullTableName) {
5818
+ const { tableName } = parseFullTableName(fullTableName);
5819
+ if (isSystemTable(tableName)) {
5820
+ return ctx.db.system.query(tableName);
5821
+ }
5822
+ return ctx.db.query(fullTableName);
5823
+ }
5824
+ function getDefaultSystemTableVisibility(tableName) {
5825
+ if (!isSystemTable(tableName)) {
5826
+ return "public";
5827
+ }
5828
+ return isPublicSystemTable(tableName) ? "public" : "private";
5829
+ }
5830
+ function buildIndexList(indexes) {
5831
+ const base = ["by_id", "by_creation_time"];
5302
5832
  if (!indexes || indexes.length === 0) {
5303
5833
  return base;
5304
5834
  }
@@ -5398,6 +5928,7 @@ var init_internal = __esm(() => {
5398
5928
  init_interface();
5399
5929
  init_execution_log();
5400
5930
  init_auth();
5931
+ init_system_tables();
5401
5932
  });
5402
5933
 
5403
5934
  // ../core/dist/system/system-functions-module.js
@@ -5555,8 +6086,9 @@ class ModuleRegistry {
5555
6086
  const normalized = normalizeModuleListing(listing);
5556
6087
  if (!normalized)
5557
6088
  continue;
5558
- if (!results.has(normalized.path)) {
5559
- results.set(normalized.path, {
6089
+ const resultKey = `${normalized.componentPath ?? scope ?? ""}:${normalized.path}`;
6090
+ if (!results.has(resultKey)) {
6091
+ results.set(resultKey, {
5560
6092
  ...normalized,
5561
6093
  scope: scope || undefined,
5562
6094
  componentPath: normalized.componentPath ?? (scope || undefined)
@@ -5875,8 +6407,10 @@ var init_module_loader = __esm(() => {
5875
6407
  class SchemaValidator {
5876
6408
  schemaCache = new Map;
5877
6409
  componentPath;
5878
- constructor(componentPath) {
6410
+ tableRegistry;
6411
+ constructor(componentPath, tableRegistry) {
5879
6412
  this.componentPath = componentPath;
6413
+ this.tableRegistry = tableRegistry;
5880
6414
  }
5881
6415
  async loadTableSchema(tableName) {
5882
6416
  if (this.schemaCache.has(tableName)) {
@@ -5919,8 +6453,11 @@ class SchemaValidator {
5919
6453
  return;
5920
6454
  }
5921
6455
  try {
6456
+ const tableNumberToName = this.tableRegistry ? new Map((await this.tableRegistry.listTables()).map((table) => [table.tableNumber, table.fullName])) : undefined;
5922
6457
  validateValidator(tableSchema, omit(document, ["_id", "_creationTime"]), "", {
5923
- componentPath: this.componentPath ?? ""
6458
+ componentPath: this.componentPath ?? "",
6459
+ tableRegistry: this.tableRegistry,
6460
+ tableNumberToName
5924
6461
  });
5925
6462
  } catch (error) {
5926
6463
  throw new ValidatorError(`Failed to insert or update a document in table "${tableName}" because it does not match the schema: ${error.message}`);
@@ -6018,6 +6555,16 @@ Path: ${formatPath(path)}
6018
6555
  Value: ${formatValue(value)}
6019
6556
  Validator: v.id("${validator2.tableName}")`);
6020
6557
  }
6558
+ if (isValidDocumentId(value)) {
6559
+ const tableName2 = tableNameFromConvexId(value, options);
6560
+ if (!tableName2 || !isMatchingValidatorTable(tableName2, validator2.tableName, options.componentPath)) {
6561
+ throw new Error(`Value does not match validator.
6562
+ Path: ${formatPath(path)}
6563
+ Value: ${formatValue(value)}
6564
+ Validator: v.id("${validator2.tableName}")`);
6565
+ }
6566
+ return;
6567
+ }
6021
6568
  const tableName = tableNameFromId(value);
6022
6569
  if (!tableName || !isMatchingValidatorTable(tableName, validator2.tableName, options.componentPath)) {
6023
6570
  throw new Error(`Value does not match validator.
@@ -6079,289 +6626,72 @@ Validator: v.object({...})`);
6079
6626
  }
6080
6627
  } else {
6081
6628
  const fieldPath = path ? `${path}.${k}` : `.${k}`;
6082
- validateValidator(fieldType, value[k], fieldPath, options);
6083
- }
6084
- }
6085
- for (const k of Object.keys(value)) {
6086
- if (validator2.value[k] === undefined) {
6087
- throw new Error(`Object contains extra field \`${k}\` that is not in the validator.
6088
-
6089
- Object: ${JSON.stringify(value)}
6090
- Validator: v.object({...})`);
6091
- }
6092
- }
6093
- return;
6094
- }
6095
- }
6096
- }
6097
- function tableNameFromId(id) {
6098
- const parts = deserializeDeveloperId(id);
6099
- if (!parts) {
6100
- return null;
6101
- }
6102
- return hexToString(parts.table);
6103
- }
6104
- function isMatchingValidatorTable(idTableName, validatorTableName, componentPath) {
6105
- if (idTableName === validatorTableName) {
6106
- return true;
6107
- }
6108
- const { tableName: validatorBareName } = parseFullTableName(validatorTableName);
6109
- const { tableName: idBareName } = parseFullTableName(idTableName);
6110
- if (componentPath !== undefined) {
6111
- const expectedFullName = getFullTableName(validatorBareName, componentPath);
6112
- return idTableName === expectedFullName;
6113
- }
6114
- return idBareName === validatorBareName;
6115
- }
6116
- function isSimpleObject2(value) {
6117
- const isObject2 = typeof value === "object";
6118
- const prototype = Object.getPrototypeOf(value);
6119
- const isSimple = prototype === null || prototype === Object.prototype || prototype?.constructor?.name === "Object";
6120
- return isObject2 && isSimple;
6121
- }
6122
- var ValidatorError;
6123
- var init_validator2 = __esm(() => {
6124
- init_interface();
6125
- init_module_loader();
6126
- ValidatorError = class ValidatorError extends Error {
6127
- path;
6128
- constructor(message2, path = "") {
6129
- super(message2);
6130
- this.path = path;
6131
- this.name = "ValidatorError";
6132
- }
6133
- };
6134
- });
6135
-
6136
- // ../core/dist/id-codec/base32.js
6137
- function base32Encode(data) {
6138
- if (data.length === 0)
6139
- return "";
6140
- let result = "";
6141
- let buffer = 0;
6142
- let bitsLeft = 0;
6143
- for (const byte of data) {
6144
- buffer = buffer << 8 | byte;
6145
- bitsLeft += 8;
6146
- while (bitsLeft >= 5) {
6147
- bitsLeft -= 5;
6148
- const index = buffer >> bitsLeft & 31;
6149
- result += ALPHABET[index];
6150
- }
6151
- }
6152
- if (bitsLeft > 0) {
6153
- const index = buffer << 5 - bitsLeft & 31;
6154
- result += ALPHABET[index];
6155
- }
6156
- return result;
6157
- }
6158
- function base32Decode(str) {
6159
- if (str.length === 0)
6160
- return new Uint8Array(0);
6161
- const outputLength = Math.floor(str.length * 5 / 8);
6162
- const result = new Uint8Array(outputLength);
6163
- let buffer = 0;
6164
- let bitsLeft = 0;
6165
- let outputIndex = 0;
6166
- for (const char of str) {
6167
- const value = ALPHABET_MAP.get(char);
6168
- if (value === undefined) {
6169
- throw new Error(`Invalid base32 character: ${char}`);
6170
- }
6171
- buffer = buffer << 5 | value;
6172
- bitsLeft += 5;
6173
- if (bitsLeft >= 8) {
6174
- bitsLeft -= 8;
6175
- result[outputIndex++] = buffer >> bitsLeft & 255;
6176
- }
6177
- }
6178
- return result;
6179
- }
6180
- function isValidBase32(str) {
6181
- for (const char of str) {
6182
- if (!ALPHABET_MAP.has(char)) {
6183
- return false;
6184
- }
6185
- }
6186
- return true;
6187
- }
6188
- var ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz", ALPHABET_MAP;
6189
- var init_base32 = __esm(() => {
6190
- ALPHABET_MAP = new Map;
6191
- for (let i2 = 0;i2 < ALPHABET.length; i2++) {
6192
- ALPHABET_MAP.set(ALPHABET[i2], i2);
6193
- ALPHABET_MAP.set(ALPHABET[i2].toUpperCase(), i2);
6194
- }
6195
- ALPHABET_MAP.set("i", 1);
6196
- ALPHABET_MAP.set("I", 1);
6197
- ALPHABET_MAP.set("l", 1);
6198
- ALPHABET_MAP.set("L", 1);
6199
- ALPHABET_MAP.set("o", 0);
6200
- ALPHABET_MAP.set("O", 0);
6201
- });
6202
-
6203
- // ../core/dist/id-codec/vint.js
6204
- function vintEncode(value) {
6205
- if (value < 0) {
6206
- throw new Error("VInt cannot encode negative numbers");
6207
- }
6208
- if (value > 4294967295) {
6209
- throw new Error("VInt cannot encode values larger than 2^32-1");
6210
- }
6211
- value = value >>> 0;
6212
- if (value < 128) {
6213
- return new Uint8Array([value]);
6214
- }
6215
- if (value < 16512) {
6216
- const adjusted2 = value - 128;
6217
- return new Uint8Array([128 | adjusted2 >> 8 & 63, adjusted2 & 255]);
6218
- }
6219
- if (value < 2113664) {
6220
- const adjusted2 = value - 16512;
6221
- return new Uint8Array([192 | adjusted2 >> 16 & 31, adjusted2 >> 8 & 255, adjusted2 & 255]);
6222
- }
6223
- if (value < 270549120) {
6224
- const adjusted2 = value - 2113664;
6225
- return new Uint8Array([
6226
- 224 | adjusted2 >> 24 & 15,
6227
- adjusted2 >> 16 & 255,
6228
- adjusted2 >> 8 & 255,
6229
- adjusted2 & 255
6230
- ]);
6231
- }
6232
- const adjusted = value - 270549120;
6233
- return new Uint8Array([
6234
- 240 | adjusted >> 32 & 7,
6235
- adjusted >> 24 & 255,
6236
- adjusted >> 16 & 255,
6237
- adjusted >> 8 & 255,
6238
- adjusted & 255
6239
- ]);
6240
- }
6241
- function vintDecode(data, offset = 0) {
6242
- if (offset >= data.length) {
6243
- throw new Error("VInt decode: unexpected end of data");
6244
- }
6245
- const first = data[offset];
6246
- if ((first & 128) === 0) {
6247
- return { value: first, bytesRead: 1 };
6248
- }
6249
- if ((first & 192) === 128) {
6250
- if (offset + 1 >= data.length) {
6251
- throw new Error("VInt decode: truncated 2-byte encoding");
6252
- }
6253
- const value = 128 + ((first & 63) << 8 | data[offset + 1]);
6254
- return { value, bytesRead: 2 };
6255
- }
6256
- if ((first & 224) === 192) {
6257
- if (offset + 2 >= data.length) {
6258
- throw new Error("VInt decode: truncated 3-byte encoding");
6259
- }
6260
- const value = 16512 + ((first & 31) << 16 | data[offset + 1] << 8 | data[offset + 2]);
6261
- return { value, bytesRead: 3 };
6262
- }
6263
- if ((first & 240) === 224) {
6264
- if (offset + 3 >= data.length) {
6265
- throw new Error("VInt decode: truncated 4-byte encoding");
6266
- }
6267
- const value = 2113664 + ((first & 15) << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]);
6268
- return { value: value >>> 0, bytesRead: 4 };
6269
- }
6270
- if ((first & 248) === 240) {
6271
- if (offset + 4 >= data.length) {
6272
- throw new Error("VInt decode: truncated 5-byte encoding");
6273
- }
6274
- const high = first & 7;
6275
- const low = (data[offset + 1] << 24 | data[offset + 2] << 16 | data[offset + 3] << 8 | data[offset + 4]) >>> 0;
6276
- const value = 270549120 + high * 4294967296 + low;
6277
- return { value: value >>> 0, bytesRead: 5 };
6278
- }
6279
- throw new Error("VInt decode: invalid prefix");
6280
- }
6281
-
6282
- // ../core/dist/id-codec/fletcher16.js
6283
- function fletcher16(data) {
6284
- let sum1 = 0;
6285
- let sum2 = 0;
6286
- for (const byte of data) {
6287
- sum1 = (sum1 + byte) % 255;
6288
- sum2 = (sum2 + sum1) % 255;
6289
- }
6290
- return new Uint8Array([sum1, sum2]);
6291
- }
6292
- function verifyFletcher16(data, checksum) {
6293
- if (checksum.length !== 2)
6294
- return false;
6295
- const computed = fletcher16(data);
6296
- return computed[0] === checksum[0] && computed[1] === checksum[1];
6297
- }
6298
-
6299
- // ../core/dist/utils/crypto.js
6300
- var weakRandomState;
6301
- var init_crypto = __esm(() => {
6302
- weakRandomState = (Date.now() ^ 2654435769) >>> 0;
6303
- });
6304
-
6305
- // ../core/dist/id-codec/document-id.js
6306
- function encodeDocumentId(tableNumber, internalId) {
6307
- if (internalId.length !== INTERNAL_ID_LENGTH) {
6308
- throw new Error(`Internal ID must be exactly ${INTERNAL_ID_LENGTH} bytes, got ${internalId.length}`);
6309
- }
6310
- if (tableNumber < 1 || tableNumber > 4294967295) {
6311
- throw new Error(`Table number must be between 1 and 2^32-1, got ${tableNumber}`);
6312
- }
6313
- const tableBytes = vintEncode(tableNumber);
6314
- const payload = new Uint8Array(tableBytes.length + INTERNAL_ID_LENGTH);
6315
- payload.set(tableBytes, 0);
6316
- payload.set(internalId, tableBytes.length);
6317
- const checksum = fletcher16(payload);
6318
- const final = new Uint8Array(payload.length + 2);
6319
- final.set(payload, 0);
6320
- final.set(checksum, payload.length);
6321
- return base32Encode(final);
6322
- }
6323
- function decodeDocumentId(encoded) {
6324
- if (encoded.length < MIN_ENCODED_LENGTH || encoded.length > MAX_ENCODED_LENGTH) {
6325
- throw new Error(`Invalid document ID length: ${encoded.length} (expected ${MIN_ENCODED_LENGTH}-${MAX_ENCODED_LENGTH})`);
6326
- }
6327
- if (!isValidBase32(encoded)) {
6328
- throw new Error("Invalid document ID: contains invalid base32 characters");
6329
- }
6330
- const bytes = base32Decode(encoded);
6331
- if (bytes.length < 19) {
6332
- throw new Error(`Invalid document ID: decoded to ${bytes.length} bytes (minimum 19)`);
6333
- }
6334
- const checksum = bytes.slice(bytes.length - 2);
6335
- const payload = bytes.slice(0, bytes.length - 2);
6336
- if (!verifyFletcher16(payload, checksum)) {
6337
- throw new Error("Invalid document ID: checksum verification failed");
6629
+ validateValidator(fieldType, value[k], fieldPath, options);
6630
+ }
6631
+ }
6632
+ for (const k of Object.keys(value)) {
6633
+ if (validator2.value[k] === undefined) {
6634
+ throw new Error(`Object contains extra field \`${k}\` that is not in the validator.
6635
+
6636
+ Object: ${JSON.stringify(value)}
6637
+ Validator: v.object({...})`);
6638
+ }
6639
+ }
6640
+ return;
6641
+ }
6338
6642
  }
6339
- const { value: tableNumber, bytesRead } = vintDecode(payload, 0);
6340
- const internalId = payload.slice(bytesRead, bytesRead + INTERNAL_ID_LENGTH);
6341
- if (internalId.length !== INTERNAL_ID_LENGTH) {
6342
- throw new Error(`Invalid document ID: internal ID is ${internalId.length} bytes (expected ${INTERNAL_ID_LENGTH})`);
6643
+ }
6644
+ function tableNameFromId(id) {
6645
+ const parts = deserializeDeveloperId(id);
6646
+ if (!parts) {
6647
+ return null;
6343
6648
  }
6344
- return { tableNumber, internalId };
6649
+ return hexToString(parts.table);
6345
6650
  }
6346
- function isValidDocumentId(encoded) {
6651
+ function tableNameFromConvexId(id, options) {
6347
6652
  try {
6348
- decodeDocumentId(encoded);
6349
- return true;
6653
+ const decoded = decodeDocumentId(id);
6654
+ const fromMap = options.tableNumberToName?.get(decoded.tableNumber);
6655
+ if (fromMap) {
6656
+ return fromMap;
6657
+ }
6658
+ return null;
6350
6659
  } catch {
6351
- return false;
6660
+ return null;
6352
6661
  }
6353
6662
  }
6354
- function internalIdToHex(internalId) {
6355
- let hex = "";
6356
- for (let i2 = 0;i2 < internalId.length; i2++) {
6357
- hex += internalId[i2].toString(16).padStart(2, "0");
6663
+ function isMatchingValidatorTable(idTableName, validatorTableName, componentPath) {
6664
+ if (idTableName === validatorTableName) {
6665
+ return true;
6358
6666
  }
6359
- return hex;
6667
+ const { tableName: validatorBareName } = parseFullTableName(validatorTableName);
6668
+ const { tableName: idBareName } = parseFullTableName(idTableName);
6669
+ if (componentPath !== undefined) {
6670
+ const expectedFullName = getFullTableName(validatorBareName, componentPath);
6671
+ return idTableName === expectedFullName;
6672
+ }
6673
+ return idBareName === validatorBareName;
6360
6674
  }
6361
- var INTERNAL_ID_LENGTH = 16, MIN_ENCODED_LENGTH = 31, MAX_ENCODED_LENGTH = 37;
6362
- var init_document_id = __esm(() => {
6363
- init_base32();
6364
- init_crypto();
6675
+ function isSimpleObject2(value) {
6676
+ const isObject2 = typeof value === "object";
6677
+ const prototype = Object.getPrototypeOf(value);
6678
+ const isSimple = prototype === null || prototype === Object.prototype || prototype?.constructor?.name === "Object";
6679
+ return isObject2 && isSimple;
6680
+ }
6681
+ var ValidatorError;
6682
+ var init_validator2 = __esm(() => {
6683
+ init_utils();
6684
+ init_interface();
6685
+ init_module_loader();
6686
+ init_id_codec();
6687
+ ValidatorError = class ValidatorError extends Error {
6688
+ path;
6689
+ constructor(message2, path = "") {
6690
+ super(message2);
6691
+ this.path = path;
6692
+ this.name = "ValidatorError";
6693
+ }
6694
+ };
6365
6695
  });
6366
6696
 
6367
6697
  // src/sqlite-docstore.ts
@@ -6372,7 +6702,10 @@ init_values();
6372
6702
 
6373
6703
  // ../core/dist/docstore/interface.js
6374
6704
  function documentIdKey(id) {
6375
- const tableKey = id.table && id.table.length > 0 ? id.table : id.tableNumber !== undefined && Number.isInteger(id.tableNumber) && id.tableNumber > 0 ? `#${id.tableNumber}` : id.table;
6705
+ const tableKey = id.table && id.table.length > 0 ? id.table : id.tableNumber !== undefined && Number.isInteger(id.tableNumber) && id.tableNumber > 0 ? `#${id.tableNumber}` : null;
6706
+ if (!tableKey) {
6707
+ throw new Error("Invalid document ID: missing table and tableNumber");
6708
+ }
6376
6709
  return `${tableKey}:${id.internalId}`;
6377
6710
  }
6378
6711
  var Order;
@@ -6579,6 +6912,7 @@ class TimestampOracle {
6579
6912
  }
6580
6913
  }
6581
6914
  // ../core/dist/utils/keyspace.js
6915
+ init_utils();
6582
6916
  var TABLE_PREFIX = "table";
6583
6917
  var INDEX_PREFIX = "index";
6584
6918
  function encodeComponent(component) {
@@ -6619,6 +6953,13 @@ function decodeIndexId(indexId) {
6619
6953
  index: decoded.slice(separatorIndex + 1)
6620
6954
  };
6621
6955
  }
6956
+
6957
+ // ../core/dist/utils/index.js
6958
+ init_utils();
6959
+
6960
+ // ../core/dist/queryengine/indexing/index-manager.js
6961
+ init_utils();
6962
+
6622
6963
  // ../core/dist/queryengine/indexing/index-key-codec.js
6623
6964
  var TypeTag;
6624
6965
  (function(TypeTag2) {
@@ -6668,8 +7009,9 @@ function encodeBigInt(n) {
6668
7009
  return bytes;
6669
7010
  }
6670
7011
  function encodeString(s) {
6671
- const encoder = new TextEncoder;
6672
- const raw = encoder.encode(s);
7012
+ return encodeEscapedBytes(new TextEncoder().encode(s));
7013
+ }
7014
+ function encodeEscapedBytes(raw) {
6673
7015
  let nullCount = 0;
6674
7016
  for (const byte of raw) {
6675
7017
  if (byte === 0)
@@ -6733,11 +7075,10 @@ function encodeValue(value) {
6733
7075
  }
6734
7076
  if (value instanceof ArrayBuffer || value instanceof Uint8Array) {
6735
7077
  const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);
6736
- const result = new Uint8Array(1 + bytes.length + 2);
7078
+ const encoded = encodeEscapedBytes(bytes);
7079
+ const result = new Uint8Array(1 + encoded.length);
6737
7080
  result[0] = TypeTag.Bytes;
6738
- result.set(bytes, 1);
6739
- result[result.length - 2] = 0;
6740
- result[result.length - 1] = 0;
7081
+ result.set(encoded, 1);
6741
7082
  return result;
6742
7083
  }
6743
7084
  throw new Error(`Cannot encode value of type ${typeof value} in index key`);
@@ -6854,9 +7195,11 @@ class SchemaService {
6854
7195
  tableCache = new Map;
6855
7196
  schemaValidator;
6856
7197
  componentPath;
6857
- constructor(componentPath) {
7198
+ tableRegistry;
7199
+ constructor(componentPath, tableRegistry) {
6858
7200
  this.componentPath = componentPath;
6859
- this.schemaValidator = new SchemaValidator(componentPath);
7201
+ this.tableRegistry = tableRegistry;
7202
+ this.schemaValidator = new SchemaValidator(componentPath, tableRegistry);
6860
7203
  }
6861
7204
  async validate(tableName, document) {
6862
7205
  try {
@@ -6981,6 +7324,10 @@ class SchemaService {
6981
7324
  return this.cachedSchemaDefinition;
6982
7325
  }
6983
7326
  }
7327
+
7328
+ // ../core/dist/queryengine/index-query.js
7329
+ init_utils();
7330
+
6984
7331
  // ../core/dist/observability/udf-trace.js
6985
7332
  init_context_storage();
6986
7333
  var TRACE_CONTEXT = new ContextStorage;
@@ -7224,11 +7571,10 @@ function evaluateFieldPath(fieldPath, document) {
7224
7571
  }
7225
7572
  return current;
7226
7573
  }
7227
- // ../core/dist/id-codec/index.js
7228
- init_base32();
7229
- init_document_id();
7230
7574
 
7231
7575
  // ../core/dist/queryengine/developer-id.js
7576
+ init_utils();
7577
+ init_id_codec();
7232
7578
  function parseDeveloperId(developerId) {
7233
7579
  if (isValidDocumentId(developerId)) {
7234
7580
  try {
@@ -7246,6 +7592,25 @@ function parseDeveloperId(developerId) {
7246
7592
  }
7247
7593
  return { table: parts.table, internalId: parts.internalId };
7248
7594
  }
7595
+ async function parseDeveloperIdWithTableRegistry(developerId, tableRegistry) {
7596
+ if (isValidDocumentId(developerId)) {
7597
+ try {
7598
+ const decoded = decodeDocumentId(developerId);
7599
+ const tableInfo = await tableRegistry.getTableInfo(decoded.tableNumber);
7600
+ if (!tableInfo) {
7601
+ return null;
7602
+ }
7603
+ return {
7604
+ table: stringToHex(tableInfo.fullName),
7605
+ internalId: internalIdToHex(decoded.internalId),
7606
+ tableNumber: decoded.tableNumber
7607
+ };
7608
+ } catch {
7609
+ return null;
7610
+ }
7611
+ }
7612
+ return parseDeveloperId(developerId);
7613
+ }
7249
7614
  function parseStorageId(storageId) {
7250
7615
  const parsed = parseDeveloperId(storageId);
7251
7616
  if (parsed) {
@@ -7262,12 +7627,21 @@ function parseStorageId(storageId) {
7262
7627
  function isTablePlaceholder(table) {
7263
7628
  return table.startsWith("#");
7264
7629
  }
7630
+
7631
+ // ../core/dist/query/query-runtime.js
7632
+ init_utils();
7633
+
7265
7634
  // ../core/dist/query/planner.js
7266
7635
  init_interface();
7636
+ init_utils();
7637
+
7267
7638
  // ../core/dist/query/actions.js
7639
+ init_utils();
7268
7640
  init_interface();
7269
7641
 
7270
7642
  // ../core/dist/queryengine/indexing/read-write-set.js
7643
+ init_utils();
7644
+
7271
7645
  class RangeSet {
7272
7646
  ranges = new Map;
7273
7647
  addDocument(docId) {
@@ -7378,6 +7752,8 @@ function deserializeKeyRange(serialized) {
7378
7752
  }
7379
7753
 
7380
7754
  // ../core/dist/kernel/access-log.js
7755
+ init_utils();
7756
+
7381
7757
  class AccessLog {
7382
7758
  ranges = new RangeSet;
7383
7759
  addDocument(docId) {
@@ -7402,104 +7778,9 @@ class AccessLog {
7402
7778
  }
7403
7779
  }
7404
7780
 
7405
- // ../core/dist/tables/memory-table-registry.js
7781
+ // ../core/dist/kernel/kernel-context.js
7406
7782
  init_interface();
7407
7783
 
7408
- class MemoryTableRegistry {
7409
- tablesByName = new Map;
7410
- tablesByNumber = new Map;
7411
- nextTableNumber = FIRST_USER_TABLE_NUMBER;
7412
- constructor() {
7413
- this.registerSystemTables();
7414
- }
7415
- registerSystemTables() {
7416
- for (const [name, number] of Object.entries(SYSTEM_TABLE_NUMBERS)) {
7417
- const info = {
7418
- tableNumber: number,
7419
- name,
7420
- componentPath: "",
7421
- fullName: name,
7422
- isSystem: true,
7423
- createdAt: Date.now()
7424
- };
7425
- this.tablesByName.set(name, info);
7426
- this.tablesByNumber.set(number, info);
7427
- }
7428
- }
7429
- async getOrAllocateTableNumber(tableName, componentPath = "") {
7430
- const fullName = getFullTableName(tableName, componentPath);
7431
- const existing = this.tablesByName.get(fullName);
7432
- if (existing) {
7433
- return existing.tableNumber;
7434
- }
7435
- if (isSystemTable(tableName) && componentPath === "") {
7436
- const systemNumber = SYSTEM_TABLE_NUMBERS[tableName];
7437
- if (systemNumber !== undefined) {
7438
- return systemNumber;
7439
- }
7440
- }
7441
- const tableNumber = this.nextTableNumber++;
7442
- const info = {
7443
- tableNumber,
7444
- name: tableName,
7445
- componentPath,
7446
- fullName,
7447
- isSystem: false,
7448
- createdAt: Date.now()
7449
- };
7450
- this.tablesByName.set(fullName, info);
7451
- this.tablesByNumber.set(tableNumber, info);
7452
- return tableNumber;
7453
- }
7454
- async getTableInfo(tableNumber) {
7455
- return this.tablesByNumber.get(tableNumber) ?? null;
7456
- }
7457
- async getTableInfoByName(tableName, componentPath = "") {
7458
- const fullName = getFullTableName(tableName, componentPath);
7459
- return this.tablesByName.get(fullName) ?? null;
7460
- }
7461
- async listTables(componentPath) {
7462
- const tables = Array.from(this.tablesByNumber.values());
7463
- if (componentPath === undefined) {
7464
- return tables;
7465
- }
7466
- return tables.filter((t) => t.componentPath === componentPath);
7467
- }
7468
- async hasAccess(tableNumber, componentPath) {
7469
- const info = await this.getTableInfo(tableNumber);
7470
- if (!info) {
7471
- return false;
7472
- }
7473
- if (info.isSystem) {
7474
- return true;
7475
- }
7476
- return info.componentPath === componentPath;
7477
- }
7478
- getSystemTableNumber(systemTableName) {
7479
- return SYSTEM_TABLE_NUMBERS[systemTableName];
7480
- }
7481
- reset() {
7482
- this.tablesByName.clear();
7483
- this.tablesByNumber.clear();
7484
- this.nextTableNumber = FIRST_USER_TABLE_NUMBER;
7485
- this.registerSystemTables();
7486
- }
7487
- getState() {
7488
- return {
7489
- tableCount: this.tablesByNumber.size,
7490
- nextNumber: this.nextTableNumber
7491
- };
7492
- }
7493
- }
7494
- var globalRegistry = null;
7495
- function getGlobalTableRegistry() {
7496
- if (!globalRegistry) {
7497
- globalRegistry = new MemoryTableRegistry;
7498
- }
7499
- return globalRegistry;
7500
- }
7501
-
7502
- // ../core/dist/kernel/kernel-context.js
7503
7784
  class KernelContext {
7504
7785
  authContext;
7505
7786
  componentPath;
@@ -7516,11 +7797,14 @@ class KernelContext {
7516
7797
  this.authContext = options.authContext;
7517
7798
  this.componentPath = options.componentPath ?? "";
7518
7799
  this.mutationTransaction = options.mutationTransaction;
7519
- this.tableRegistry = options.tableRegistry ?? getGlobalTableRegistry();
7520
- this.useConvexIdFormat = options.useConvexIdFormat ?? false;
7800
+ if (!options.tableRegistry) {
7801
+ throw new Error("KernelContext requires an explicit tableRegistry");
7802
+ }
7803
+ this.tableRegistry = options.tableRegistry;
7804
+ this.useConvexIdFormat = options.useConvexIdFormat ?? true;
7521
7805
  }
7522
7806
  async getTableNumber(tableName) {
7523
- return this.tableRegistry.getOrAllocateTableNumber(tableName, this.componentPath);
7807
+ return this.tableRegistry.getOrAllocateTableNumber(tableName, isSystemTable(tableName) ? "" : this.componentPath);
7524
7808
  }
7525
7809
  nextSubrequestId(prefix, udfPath) {
7526
7810
  return `${prefix}:${udfPath}:${Date.now()}:${Math.random()}:${this.subrequestCounter++}`;
@@ -7565,7 +7849,7 @@ class KernelContext {
7565
7849
  this.writeLog.addDocument(docId);
7566
7850
  }
7567
7851
  recordLocalWrite(developerId, tableName, value, docId) {
7568
- this.localWrites.set(developerId, { table: tableName, value });
7852
+ this.localWrites.set(developerId, { table: tableName, value, docId });
7569
7853
  if (docId) {
7570
7854
  this.recordDocumentWrite(docId);
7571
7855
  return;
@@ -7607,7 +7891,13 @@ class KernelContext {
7607
7891
  }
7608
7892
  }
7609
7893
 
7894
+ // ../core/dist/kernel/udf-kernel.js
7895
+ init_id_codec();
7896
+
7610
7897
  // ../core/dist/kernel/blob-store-gateway.js
7898
+ init_id_codec();
7899
+ init_utils();
7900
+
7611
7901
  class BlobStoreGateway {
7612
7902
  context;
7613
7903
  docStore;
@@ -7656,7 +7946,7 @@ class BlobStoreGateway {
7656
7946
  if (!this.storage) {
7657
7947
  return null;
7658
7948
  }
7659
- const docId = parseStorageId(storageId);
7949
+ const docId = await parseDeveloperIdWithTableRegistry(storageId, this.context.tableRegistry) ?? parseStorageId(storageId);
7660
7950
  if (!docId) {
7661
7951
  console.debug(`[BlobStoreGateway] Failed to parse storage ID: ${storageId}`);
7662
7952
  return null;
@@ -7677,7 +7967,7 @@ class BlobStoreGateway {
7677
7967
  if (!this.storage) {
7678
7968
  return null;
7679
7969
  }
7680
- const docId = parseStorageId(storageId);
7970
+ const docId = await parseDeveloperIdWithTableRegistry(storageId, this.context.tableRegistry) ?? parseStorageId(storageId);
7681
7971
  if (!docId) {
7682
7972
  return null;
7683
7973
  }
@@ -7690,7 +7980,7 @@ class BlobStoreGateway {
7690
7980
  }
7691
7981
  async delete(storageId) {
7692
7982
  const storage2 = this.requireStorage();
7693
- const docId = parseStorageId(storageId);
7983
+ const docId = await parseDeveloperIdWithTableRegistry(storageId, this.context.tableRegistry) ?? parseStorageId(storageId);
7694
7984
  if (!docId) {
7695
7985
  return;
7696
7986
  }
@@ -7715,13 +8005,17 @@ class BlobStoreGateway {
7715
8005
 
7716
8006
  // ../core/dist/kernel/scheduler-gateway.js
7717
8007
  init_values();
8008
+ init_id_codec();
8009
+ init_utils();
8010
+
7718
8011
  // ../core/dist/kernel/syscalls/utils.js
7719
8012
  init_values();
8013
+ init_utils();
7720
8014
  async function resolveTableName(docId, tableRegistry) {
7721
8015
  if (docId.tableNumber !== undefined) {
7722
8016
  const info = await tableRegistry.getTableInfo(docId.tableNumber);
7723
8017
  if (info) {
7724
- return info.name;
8018
+ return info.fullName;
7725
8019
  }
7726
8020
  if (!isTablePlaceholder(docId.table)) {
7727
8021
  return hexToString(docId.table);
@@ -7902,7 +8196,7 @@ class SchedulerGateway {
7902
8196
  return developerId;
7903
8197
  }
7904
8198
  async cancel(id, state) {
7905
- const docId = parseDeveloperId(id);
8199
+ const docId = await parseDeveloperIdWithTableRegistry(id, this.context.tableRegistry);
7906
8200
  if (!docId) {
7907
8201
  throw new Error(`Scheduled job with id ${id} not found.`);
7908
8202
  }
@@ -8027,6 +8321,8 @@ class ActionSyscalls {
8027
8321
 
8028
8322
  // ../core/dist/kernel/syscalls/database-syscalls.js
8029
8323
  init_values();
8324
+ init_id_codec();
8325
+ init_utils();
8030
8326
  init_interface();
8031
8327
 
8032
8328
  class DatabaseSyscalls {
@@ -8063,7 +8359,8 @@ class DatabaseSyscalls {
8063
8359
  if (docId.tableNumber !== undefined) {
8064
8360
  return { id: idString };
8065
8361
  }
8066
- if (docId.table === stringToHex(tableName)) {
8362
+ const expectedFullTableName = getFullTableName(tableName, isSystemTable(tableName) ? "" : this.context.componentPath);
8363
+ if (docId.table === stringToHex(expectedFullTableName)) {
8067
8364
  return { id: idString };
8068
8365
  }
8069
8366
  return { id: null };
@@ -8122,29 +8419,28 @@ class DatabaseSyscalls {
8122
8419
  return { _id: developerId };
8123
8420
  }
8124
8421
  async handleGet(args) {
8125
- const { id } = args;
8422
+ const { id, table } = args;
8126
8423
  if (typeof id !== "string") {
8127
8424
  throw new Error("`id` argument for `get` must be a string.");
8128
8425
  }
8129
- const internalId = parseDeveloperId(id);
8130
- if (!internalId) {
8426
+ const resolved = await this.resolveDocumentTarget(id, table, "get");
8427
+ if (!resolved) {
8131
8428
  return null;
8132
8429
  }
8133
- this.context.recordDocumentRead(internalId);
8134
- const doc = await this.queryRuntime.getVisibleDocumentById(id, internalId);
8430
+ this.context.recordDocumentRead(resolved.docId);
8431
+ const doc = await this.queryRuntime.getVisibleDocumentById(id, resolved.docId);
8135
8432
  return doc ?? null;
8136
8433
  }
8137
8434
  async handleRemove(args) {
8138
- const { id } = args;
8435
+ const { id, table } = args;
8139
8436
  if (typeof id !== "string") {
8140
8437
  throw new Error("`id` argument for `remove` must be a string.");
8141
8438
  }
8142
- const docId = parseDeveloperId(id);
8143
- if (!docId) {
8439
+ const resolved = await this.resolveDocumentTarget(id, table, "remove", true);
8440
+ if (!resolved) {
8144
8441
  throw new Error(`Document with id ${id} not found.`);
8145
8442
  }
8146
- const fullTableName = await resolveTableName(docId, this.context.tableRegistry);
8147
- const { tableName: bareTableName } = parseFullTableName(fullTableName);
8443
+ const { docId, fullTableName, bareTableName } = resolved;
8148
8444
  const latest = await this.docStore.fetchLatestDocument(docId, this.context.snapshotTimestamp);
8149
8445
  if (!latest) {
8150
8446
  throw new Error(`Document with id ${id} not found.`);
@@ -8160,16 +8456,15 @@ class DatabaseSyscalls {
8160
8456
  return {};
8161
8457
  }
8162
8458
  async handleShallowMerge(args) {
8163
- const { id, value } = args;
8459
+ const { id, table, value } = args;
8164
8460
  if (typeof id !== "string") {
8165
8461
  throw new Error("`id` argument for `shallowMerge` must be a string.");
8166
8462
  }
8167
- const docId = parseDeveloperId(id);
8168
- if (!docId) {
8463
+ const resolved = await this.resolveDocumentTarget(id, table, "patch", true);
8464
+ if (!resolved) {
8169
8465
  throw new Error(`Document with id ${id} not found.`);
8170
8466
  }
8171
- const fullTableName = await resolveTableName(docId, this.context.tableRegistry);
8172
- const { tableName: bareTableName } = parseFullTableName(fullTableName);
8467
+ const { docId, fullTableName, bareTableName } = resolved;
8173
8468
  if (value && typeof value === "object") {
8174
8469
  if ("_id" in value) {
8175
8470
  throw new Error("System field `_id` cannot be modified in a patch operation.");
@@ -8220,16 +8515,15 @@ class DatabaseSyscalls {
8220
8515
  return {};
8221
8516
  }
8222
8517
  async handleReplace(args) {
8223
- const { id, value } = args;
8518
+ const { id, table, value } = args;
8224
8519
  if (typeof id !== "string") {
8225
8520
  throw new Error("`id` argument for `replace` must be a string.");
8226
8521
  }
8227
- const docId = parseDeveloperId(id);
8228
- if (!docId) {
8522
+ const resolved = await this.resolveDocumentTarget(id, table, "replace", true);
8523
+ if (!resolved) {
8229
8524
  throw new Error(`Document with id ${id} not found.`);
8230
8525
  }
8231
- const fullTableName = await resolveTableName(docId, this.context.tableRegistry);
8232
- const { tableName: bareTableName } = parseFullTableName(fullTableName);
8526
+ const { docId, fullTableName, bareTableName } = resolved;
8233
8527
  const replaceValue = jsonToConvex(value);
8234
8528
  if (typeof replaceValue !== "object" || replaceValue === null || Array.isArray(replaceValue)) {
8235
8529
  throw new Error("The replacement value for `replace` must be an object.");
@@ -8252,6 +8546,27 @@ class DatabaseSyscalls {
8252
8546
  this.context.recordLocalWrite(id, fullTableName, newValue, canonicalDocId);
8253
8547
  return {};
8254
8548
  }
8549
+ async resolveDocumentTarget(id, table, operation, throwOnMismatch = false) {
8550
+ if (table !== undefined && typeof table !== "string") {
8551
+ throw new Error(`\`table\` argument for \`${operation}\` must be a string.`);
8552
+ }
8553
+ const docId = await parseDeveloperIdWithTableRegistry(id, this.context.tableRegistry);
8554
+ if (!docId) {
8555
+ return null;
8556
+ }
8557
+ const fullTableName = await resolveTableName(docId, this.context.tableRegistry);
8558
+ if (typeof table === "string") {
8559
+ const expectedFullTableName = getFullTableName(table, isSystemTable(table) ? "" : this.context.componentPath);
8560
+ if (fullTableName !== expectedFullTableName) {
8561
+ if (throwOnMismatch) {
8562
+ throw new Error(`Document with id ${id} does not belong to table ${table}.`);
8563
+ }
8564
+ return null;
8565
+ }
8566
+ }
8567
+ const { tableName: bareTableName } = parseFullTableName(fullTableName);
8568
+ return { docId, fullTableName, bareTableName };
8569
+ }
8255
8570
  }
8256
8571
 
8257
8572
  // ../core/dist/kernel/syscalls/identity-syscalls.js
@@ -8567,11 +8882,203 @@ class KernelSyscalls {
8567
8882
  return this.jsRouter.dispatch(op, args);
8568
8883
  }
8569
8884
  }
8885
+
8886
+ // ../core/dist/tables/docstore-table-registry.js
8887
+ init_system_tables();
8888
+ init_utils();
8889
+ init_interface();
8890
+
8891
+ class DocStoreTableRegistry {
8892
+ docstore;
8893
+ tablesByNumber = new Map;
8894
+ tablesByName = new Map;
8895
+ loadPromise = null;
8896
+ cachedRegistryVersion = 0;
8897
+ constructor(docstore) {
8898
+ this.docstore = docstore;
8899
+ }
8900
+ async getOrAllocateTableNumber(tableName, componentPath = "") {
8901
+ await this.ensureLoaded();
8902
+ await this.ensureFresh();
8903
+ const normalizedComponent = isSystemTable(tableName) ? "" : componentPath;
8904
+ const fullName = getFullTableName(tableName, normalizedComponent);
8905
+ let existing = this.tablesByName.get(fullName);
8906
+ if (existing) {
8907
+ return existing.tableNumber;
8908
+ }
8909
+ await this.reloadTables();
8910
+ existing = this.tablesByName.get(fullName);
8911
+ if (existing) {
8912
+ return existing.tableNumber;
8913
+ }
8914
+ const oracle = this.docstore.timestampOracle;
8915
+ for (;; ) {
8916
+ const metadata = await readSystemMetadata(this.docstore) ?? createSystemMetadata({
8917
+ nextUserTableNumber: Math.max(FIRST_USER_TABLE_NUMBER, nextUserTableNumber(this.tablesByNumber.values()))
8918
+ });
8919
+ const candidate = Math.max(metadata.nextUserTableNumber, nextUserTableNumber(this.tablesByNumber.values()));
8920
+ const reserved = await this.docstore.writeGlobalIfAbsent(createTableNumberReservationKey(candidate), {
8921
+ fullName,
8922
+ reservedAt: Date.now()
8923
+ });
8924
+ if (!reserved) {
8925
+ await this.reloadTables();
8926
+ const raced = this.tablesByName.get(fullName);
8927
+ if (raced) {
8928
+ return raced.tableNumber;
8929
+ }
8930
+ continue;
8931
+ }
8932
+ const createdAt = Date.now();
8933
+ const info = createTableInfo(tableName, candidate, normalizedComponent, { createdAt, visibility: "public" });
8934
+ const timestamp2 = oracle?.allocateTimestamp?.() ?? BigInt(createdAt);
8935
+ const entry = createTableMetadataEntryForUserTable(info, timestamp2);
8936
+ try {
8937
+ await this.docstore.write([entry], new Set, "Error");
8938
+ } catch {
8939
+ await this.reloadTables();
8940
+ const raced = this.tablesByName.get(fullName);
8941
+ if (raced) {
8942
+ return raced.tableNumber;
8943
+ }
8944
+ throw new Error(`Failed to allocate table number for ${fullName}`);
8945
+ }
8946
+ const registryVersion = Number(timestamp2 > BigInt(Number.MAX_SAFE_INTEGER) ? BigInt(Date.now()) : timestamp2);
8947
+ await this.docstore.writeGlobal(SYSTEM_METADATA_GLOBAL_KEY, createSystemMetadata({
8948
+ nextUserTableNumber: candidate + 1,
8949
+ registryVersion,
8950
+ bootstrappedAt: metadata.bootstrappedAt,
8951
+ updatedAt: registryVersion
8952
+ }));
8953
+ this.cachedRegistryVersion = registryVersion;
8954
+ this.tablesByName.set(fullName, info);
8955
+ this.tablesByNumber.set(candidate, info);
8956
+ return candidate;
8957
+ }
8958
+ }
8959
+ async getTableInfo(tableNumber) {
8960
+ await this.ensureLoaded();
8961
+ await this.ensureFresh();
8962
+ const existing = this.tablesByNumber.get(tableNumber);
8963
+ if (existing) {
8964
+ return existing;
8965
+ }
8966
+ await this.reloadTables();
8967
+ return this.tablesByNumber.get(tableNumber) ?? null;
8968
+ }
8969
+ async getTableInfoByName(tableName, componentPath = "") {
8970
+ await this.ensureLoaded();
8971
+ await this.ensureFresh();
8972
+ const fullName = getFullTableName(tableName, isSystemTable(tableName) ? "" : componentPath);
8973
+ const existing = this.tablesByName.get(fullName);
8974
+ if (existing) {
8975
+ return existing;
8976
+ }
8977
+ await this.reloadTables();
8978
+ return this.tablesByName.get(fullName) ?? null;
8979
+ }
8980
+ async listTables(componentPath) {
8981
+ await this.ensureLoaded();
8982
+ await this.ensureFresh();
8983
+ const values = Array.from(this.tablesByNumber.values());
8984
+ if (componentPath === undefined) {
8985
+ return values.sort((a, b) => a.tableNumber - b.tableNumber);
8986
+ }
8987
+ return values.filter((table) => table.componentPath === componentPath).sort((a, b) => a.tableNumber - b.tableNumber);
8988
+ }
8989
+ async hasAccess(tableNumber, componentPath) {
8990
+ const info = await this.getTableInfo(tableNumber);
8991
+ if (!info) {
8992
+ return false;
8993
+ }
8994
+ if (info.isSystem) {
8995
+ return true;
8996
+ }
8997
+ return info.componentPath === componentPath;
8998
+ }
8999
+ getSystemTableNumber(systemTableName) {
9000
+ return SYSTEM_TABLE_NUMBERS[systemTableName];
9001
+ }
9002
+ async ensureLoaded() {
9003
+ if (!this.loadPromise) {
9004
+ this.loadPromise = this.loadTables();
9005
+ }
9006
+ await this.loadPromise;
9007
+ }
9008
+ async ensureFresh() {
9009
+ const metadata = await readSystemMetadata(this.docstore);
9010
+ if (!metadata) {
9011
+ if (this.cachedRegistryVersion !== 0 || this.tablesByName.size > 0 || this.tablesByNumber.size > 0) {
9012
+ await this.reloadTables();
9013
+ }
9014
+ return;
9015
+ }
9016
+ if (metadata.registryVersion > this.cachedRegistryVersion) {
9017
+ await this.reloadTables();
9018
+ }
9019
+ }
9020
+ async reloadTables() {
9021
+ this.loadPromise = this.loadTables();
9022
+ await this.loadPromise;
9023
+ }
9024
+ async loadTables() {
9025
+ await ensureSystemTablesBootstrapped(this.docstore);
9026
+ const docs = await this.docstore.scan(stringToHex("_tables"));
9027
+ this.tablesByName.clear();
9028
+ this.tablesByNumber.clear();
9029
+ for (const doc of docs) {
9030
+ const info = tableInfoFromStoredDocument(doc.value.value);
9031
+ if (!info) {
9032
+ continue;
9033
+ }
9034
+ this.tablesByName.set(info.fullName, info);
9035
+ this.tablesByNumber.set(info.tableNumber, info);
9036
+ }
9037
+ if (this.tablesByNumber.size === 0) {
9038
+ for (const [name, tableNumber] of Object.entries(SYSTEM_TABLE_NUMBERS)) {
9039
+ const info = createTableInfo(name, tableNumber, "", { isSystem: true });
9040
+ this.tablesByName.set(info.fullName, info);
9041
+ this.tablesByNumber.set(info.tableNumber, info);
9042
+ }
9043
+ }
9044
+ const metadata = await readSystemMetadata(this.docstore);
9045
+ if (!metadata) {
9046
+ const now = Date.now();
9047
+ this.cachedRegistryVersion = now;
9048
+ await this.docstore.writeGlobal(SYSTEM_METADATA_GLOBAL_KEY, createSystemMetadata({
9049
+ nextUserTableNumber: Math.max(FIRST_USER_TABLE_NUMBER, nextUserTableNumber(this.tablesByNumber.values())),
9050
+ registryVersion: now,
9051
+ bootstrappedAt: now,
9052
+ updatedAt: now
9053
+ }));
9054
+ } else {
9055
+ this.cachedRegistryVersion = metadata.registryVersion;
9056
+ }
9057
+ }
9058
+ }
9059
+
9060
+ // ../core/dist/tables/transactional-table-registry.js
9061
+ init_system_tables();
9062
+ init_utils();
9063
+ init_interface();
8570
9064
  // ../core/dist/kernel/contexts.js
8571
9065
  init_context_storage();
8572
- var snapshotContext = new ContextStorage;
8573
- var transactionContext = new ContextStorage;
8574
- var idGeneratorContext = new ContextStorage;
9066
+ var SNAPSHOT_CONTEXT_SYMBOL = Symbol.for("@concavejs/core/snapshot-context");
9067
+ var TRANSACTION_CONTEXT_SYMBOL = Symbol.for("@concavejs/core/transaction-context");
9068
+ var ID_GENERATOR_CONTEXT_SYMBOL = Symbol.for("@concavejs/core/id-generator-context");
9069
+ var globalContexts = globalThis;
9070
+ var snapshotContext = globalContexts[SNAPSHOT_CONTEXT_SYMBOL] ?? new ContextStorage;
9071
+ var transactionContext = globalContexts[TRANSACTION_CONTEXT_SYMBOL] ?? new ContextStorage;
9072
+ var idGeneratorContext = globalContexts[ID_GENERATOR_CONTEXT_SYMBOL] ?? new ContextStorage;
9073
+ if (!globalContexts[SNAPSHOT_CONTEXT_SYMBOL]) {
9074
+ globalContexts[SNAPSHOT_CONTEXT_SYMBOL] = snapshotContext;
9075
+ }
9076
+ if (!globalContexts[TRANSACTION_CONTEXT_SYMBOL]) {
9077
+ globalContexts[TRANSACTION_CONTEXT_SYMBOL] = transactionContext;
9078
+ }
9079
+ if (!globalContexts[ID_GENERATOR_CONTEXT_SYMBOL]) {
9080
+ globalContexts[ID_GENERATOR_CONTEXT_SYMBOL] = idGeneratorContext;
9081
+ }
8575
9082
  // ../core/dist/queryengine/convex-ops.js
8576
9083
  var debug = () => {};
8577
9084
  class CfConvex {
@@ -8624,6 +9131,8 @@ class BaseSqliteDocStore {
8624
9131
  vectorIndexesByTable = new Map;
8625
9132
  fts5Available = true;
8626
9133
  statementCache = new Map;
9134
+ configuredSearchIndexes = [];
9135
+ configuredVectorIndexes = [];
8627
9136
  constructor(adapter) {
8628
9137
  this.adapter = adapter;
8629
9138
  this.timestampOracle = new TimestampOracle;
@@ -8638,6 +9147,8 @@ class BaseSqliteDocStore {
8638
9147
  return statement;
8639
9148
  }
8640
9149
  async setupSchema(options) {
9150
+ this.configuredSearchIndexes = [...options?.searchIndexes ?? []];
9151
+ this.configuredVectorIndexes = [...options?.vectorIndexes ?? []];
8641
9152
  await this.adapter.exec(DOCUMENTS_TABLE_SCHEMA);
8642
9153
  await this.adapter.exec(DOCUMENTS_BY_TABLE_INDEX);
8643
9154
  await this.adapter.exec(INDEXES_TABLE_SCHEMA);
@@ -8645,6 +9156,24 @@ class BaseSqliteDocStore {
8645
9156
  await this.setupSearchIndexes(options?.searchIndexes ?? []);
8646
9157
  await this.setupVectorIndexes(options?.vectorIndexes ?? []);
8647
9158
  }
9159
+ async resetForTesting() {
9160
+ const rows = await this.adapter.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND sql IS NOT NULL").all();
9161
+ for (const row of rows) {
9162
+ const tableName = row?.name;
9163
+ if (typeof tableName !== "string" || tableName.length === 0) {
9164
+ continue;
9165
+ }
9166
+ await this.adapter.exec(`DROP TABLE IF EXISTS ${quoteSqlIdentifier(tableName)}`);
9167
+ }
9168
+ this.statementCache.clear();
9169
+ this.searchIndexesByTable.clear();
9170
+ this.vectorIndexesByTable.clear();
9171
+ this.fts5Available = true;
9172
+ await this.setupSchema({
9173
+ searchIndexes: this.configuredSearchIndexes,
9174
+ vectorIndexes: this.configuredVectorIndexes
9175
+ });
9176
+ }
8648
9177
  async setupSearchIndexes(searchIndexes) {
8649
9178
  try {
8650
9179
  await this.adapter.exec(SEARCH_INDEXES_FTS_SCHEMA);
@@ -8860,6 +9389,15 @@ class BaseSqliteDocStore {
8860
9389
  const stmt = this.getPreparedStatement("INSERT OR REPLACE INTO persistence_globals (key, json_value) VALUES (?, ?)");
8861
9390
  await stmt.run(key, JSON.stringify(value));
8862
9391
  }
9392
+ async writeGlobalIfAbsent(key, value) {
9393
+ const insertStmt = this.getPreparedStatement("INSERT OR IGNORE INTO persistence_globals (key, json_value) VALUES (?, ?)");
9394
+ const changesStmt = this.getPreparedStatement("SELECT changes() as changes");
9395
+ return this.adapter.transaction(async () => {
9396
+ await insertStmt.run(key, JSON.stringify(value));
9397
+ const row = await changesStmt.get();
9398
+ return Number(row?.changes ?? 0) > 0;
9399
+ });
9400
+ }
8863
9401
  async previous_revisions(queries) {
8864
9402
  const results = new Map;
8865
9403
  const stmt = this.getPreparedStatement(`
@@ -9155,6 +9693,9 @@ class BaseSqliteDocStore {
9155
9693
  return scored.slice(0, limit);
9156
9694
  }
9157
9695
  }
9696
+ function quoteSqlIdentifier(value) {
9697
+ return `"${value.replace(/"/g, '""')}"`;
9698
+ }
9158
9699
  // ../docstore-sqlite-base/dist/transaction-runner.js
9159
9700
  function createSerializedTransactionRunner(hooks) {
9160
9701
  let queue = Promise.resolve();