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