miqro 7.2.0 → 7.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/build/editor.bundle.js +3 -3
  2. package/build/esm/editor/auth.js +2 -1
  3. package/build/esm/editor/auth.js.map +1 -1
  4. package/build/esm/editor/http/admin/editor/api/fs/read.api.js +2 -2
  5. package/build/esm/editor/http/admin/editor/api/fs/read.api.js.map +1 -1
  6. package/build/esm/editor/ws.js +1 -1
  7. package/build/esm/editor/ws.js.map +1 -1
  8. package/build/esm/src/cluster.js +0 -0
  9. package/build/esm/src/common/esbuild.js +1 -1
  10. package/build/esm/src/common/esbuild.js.map +1 -1
  11. package/build/esm/src/inflate/inflate-sea.js +2 -2
  12. package/build/esm/src/inflate/inflate-sea.js.map +1 -1
  13. package/build/esm/src/main.js +0 -0
  14. package/build/esm/src/services/app.js +3 -3
  15. package/build/esm/src/services/utils/cluster-cache.js +90 -64
  16. package/build/esm/src/services/utils/cluster-cache.js.map +1 -1
  17. package/build/esm/src/services/utils/cluster-ws.js +2 -2
  18. package/build/esm/src/services/utils/cluster-ws.js.map +1 -1
  19. package/build/esm/src/services/utils/websocketmanager.js +2 -1
  20. package/build/esm/src/services/utils/websocketmanager.js.map +1 -1
  21. package/build/lib.cjs +1466 -1222
  22. package/editor/auth.ts +2 -1
  23. package/editor/http/admin/editor/api/fs/read.api.tsx +2 -2
  24. package/editor/ws.ts +1 -1
  25. package/package.json +8 -8
  26. package/sea/install-esbuild.sh +1 -1
  27. package/sea/install-nodejs.sh +1 -1
  28. package/sea/node.version.tag +1 -1
  29. package/src/common/esbuild.ts +1 -1
  30. package/src/inflate/inflate-sea.ts +2 -2
  31. package/src/services/app.ts +3 -3
  32. package/src/services/utils/cluster-cache.ts +90 -65
  33. package/src/services/utils/cluster-ws.ts +2 -2
  34. package/src/services/utils/websocketmanager.ts +2 -1
package/build/lib.cjs CHANGED
@@ -230,8 +230,8 @@ function parseBoolean(value) {
230
230
  return value === "true" || value === true ? true : value === "false" || value === false ? false : void 0;
231
231
  }
232
232
  function parseDict(value, args, parser4) {
233
- const isObject = typeof value === "object";
234
- if (!isObject || !value) {
233
+ const isObject2 = typeof value === "object";
234
+ if (!isObject2 || !value) {
235
235
  return;
236
236
  }
237
237
  if (args.dictType !== void 0) {
@@ -253,7 +253,7 @@ function parseEmail(value, args) {
253
253
  if (!emailRegex.test(String(str).toLowerCase())) {
254
254
  return;
255
255
  }
256
- return value;
256
+ return str;
257
257
  }
258
258
  function parseEnum(value, args, parser4) {
259
259
  const enumValues = parseArray(args.enumValues, {
@@ -281,8 +281,8 @@ function decodeHTML(str) {
281
281
  }
282
282
  function encodeHTML(str) {
283
283
  const buf = [];
284
- for (let i = str.length - 1; i >= 0; i--) {
285
- buf.unshift(["&#", str[i].charCodeAt(0), ";"].join(""));
284
+ for (let i = 0; i < str.length; i++) {
285
+ buf.push("&#" + str[i].charCodeAt(0) + ";");
286
286
  }
287
287
  return buf.join("");
288
288
  }
@@ -312,7 +312,7 @@ function parseInteger(value, args, parser4) {
312
312
  }
313
313
  function parseNumber(value, args) {
314
314
  const sValue = String(value);
315
- if (!(value === null || value === void 0 ? false : !isNaN(parseInt(sValue, 10)))) {
315
+ if (!(value === null || value === void 0 ? false : !isNaN(Number(sValue)) && !isNaN(parseInt(sValue, 10)))) {
316
316
  return;
317
317
  }
318
318
  const parsedValue = parseFloat(sValue);
@@ -335,8 +335,8 @@ function parseNumber(value, args) {
335
335
  return parsedValue;
336
336
  }
337
337
  function parseObject(value, args, parser4) {
338
- const isObject = typeof value === "object" ? value : void 0;
339
- if (!isObject || !value) {
338
+ const isObject2 = typeof value === "object" ? value : void 0;
339
+ if (!isObject2 || !value) {
340
340
  return;
341
341
  }
342
342
  if (args.properties !== void 0) {
@@ -372,7 +372,7 @@ function parseObject(value, args, parser4) {
372
372
  throw new Error(`unsupported mode [${mode}]`);
373
373
  }
374
374
  } else {
375
- return isObject;
375
+ return isObject2;
376
376
  }
377
377
  }
378
378
  function parseRegex(value, args) {
@@ -443,7 +443,7 @@ function parseURL(value, args) {
443
443
  if (args.stringMaxLength !== void 0 && parsedValue.length > args.stringMaxLength) {
444
444
  return;
445
445
  }
446
- const str = parseString(value, args);
446
+ const str = parseString(parsedValue, args);
447
447
  if (str === void 0) {
448
448
  return void 0;
449
449
  } else {
@@ -605,7 +605,7 @@ var init_lib = __esm({
605
605
  throw new Error("parser must be a function or Schema or a string");
606
606
  }
607
607
  if (typeof noList !== "boolean") {
608
- throw new Error("noList must be a function");
608
+ throw new Error("noList must be a boolean");
609
609
  }
610
610
  for (const reserved of RESERVED) {
611
611
  if (type.indexOf(reserved) !== -1) {
@@ -714,7 +714,7 @@ function ReadBuffer(options) {
714
714
  req.removeListener("error", errorListener);
715
715
  req.removeListener("data", chunkListener);
716
716
  req.removeListener("end", endListener);
717
- res.asyncClose();
717
+ reject(new BadRequestError(`Read Timeout`));
718
718
  return;
719
719
  }, timeout);
720
720
  let cLength = 0;
@@ -860,12 +860,12 @@ function JSONParser(options) {
860
860
  }
861
861
  function TextParser(options) {
862
862
  let limit = DEFAULT_READ_BUFFER_LIMIT;
863
- let type = "plain/text";
863
+ let type = "text/plain";
864
864
  if (options) {
865
865
  limit = options.limit !== void 0 ? options.limit : limit;
866
866
  type = options.type !== void 0 ? options.type : type;
867
867
  } else {
868
- const [limitS, typeS] = checkEnvVariables(["BODY_TEXT_PARSER_LIMIT", "BODY_TEXT_PARSER_TYPE"], [String(DEFAULT_READ_BUFFER_LIMIT), "plain/text"]);
868
+ const [limitS, typeS] = checkEnvVariables(["BODY_TEXT_PARSER_LIMIT", "BODY_TEXT_PARSER_TYPE"], [String(DEFAULT_READ_BUFFER_LIMIT), "text/plain"]);
869
869
  limit = parseInt(limitS, 10);
870
870
  type = typeS;
871
871
  }
@@ -992,7 +992,7 @@ function ResultParser(options, parser4) {
992
992
  const mappedLastResult = {
993
993
  ...lastResult
994
994
  };
995
- const parsedStatus = (parser4 ? parser4 : DEFAULT_PARSER).parse(lastResult.status, "number?", `ctx.results.status}`);
995
+ const parsedStatus = (parser4 ? parser4 : DEFAULT_PARSER).parse(lastResult.status, "number?", `ctx.results.status`);
996
996
  if (statusParserSet) {
997
997
  if (parsedStatus === void 0) {
998
998
  throw new Error(`error parsing lastResult.status[${lastResult.status}] not defined as [${statusParserSet}]`);
@@ -1201,8 +1201,6 @@ function SessionHandler(config) {
1201
1201
  throw new Error("authService must be provided!");
1202
1202
  }
1203
1203
  if (!config.options || !config.options.setCookieOptions) {
1204
- console.dir(config);
1205
- process.exit(1);
1206
1204
  throw new Error("config.options not populated!");
1207
1205
  }
1208
1206
  const tokenLocation = config.options.tokenLocation;
@@ -1734,7 +1732,7 @@ var init_types = __esm({
1734
1732
  return this.asyncEnd({
1735
1733
  status: status !== void 0 ? status : 200,
1736
1734
  headers: {
1737
- ["Content-Type"]: "plain/text; charset=utf-8",
1735
+ ["Content-Type"]: "text/plain; charset=utf-8",
1738
1736
  ...headers
1739
1737
  },
1740
1738
  body: text
@@ -1750,9 +1748,9 @@ var init_types = __esm({
1750
1748
  const newValue = current ? `${current}, ${nV}` : nV;
1751
1749
  return this.setHeader("Vary", newValue.indexOf("*") !== -1 ? "*" : newValue);
1752
1750
  }
1753
- async asyncClose() {
1751
+ async asyncClose(status = 400) {
1754
1752
  return this.asyncEnd({
1755
- status: 400,
1753
+ status,
1756
1754
  headers: {
1757
1755
  connection: "close"
1758
1756
  }
@@ -2009,7 +2007,7 @@ function defaultAppErrorHandler() {
2009
2007
  }
2010
2008
  };
2011
2009
  }
2012
- var import_node_util, import_node_fs, import_node_path, Logger, FILE_TRANSPORT_ENV_VARIABLE, FileTransportCacheMap, FILE_TRANSPORT_TIMEOUT, FILE_TRANSPORT_THREASHOLD, FileTransport, DEFAULT_LOGGER_TRANSPORTS, DEFAULT_LOGGER_FORMATTER, LOG_LEVEL_MAP, LoggerEvents, loggerContainer, DEFAULT_ENV_NAME, customLoggerFactory, BadRequestError, ForbiddenError, UnAuthorizedError, HTML_HEADERS, STATUS, checkEnvVariables, checkEnvVariable, getEnvVariable;
2010
+ var import_node_util, import_node_fs, import_node_path, Logger, FILE_TRANSPORT_ENV_VARIABLE, FileTransportCacheMap, FILE_TRANSPORT_TIMEOUT, FILE_TRANSPORT_THRESHOLD, FileTransport, DEFAULT_LOGGER_TRANSPORTS, DEFAULT_LOGGER_FORMATTER, LOG_LEVEL_MAP, LoggerEvents, loggerContainer, DEFAULT_ENV_NAME, customLoggerFactory, BadRequestError, ForbiddenError, UnAuthorizedError, HTML_HEADERS, STATUS, checkEnvVariables, checkEnvVariable, getEnvVariable;
2013
2011
  var init_common = __esm({
2014
2012
  "node_modules/@miqro/core/build/common.js"() {
2015
2013
  import_node_util = require("node:util");
@@ -2033,7 +2031,7 @@ var init_common = __esm({
2033
2031
  };
2034
2032
  }
2035
2033
  setLevel(level) {
2036
- if (!LOG_LEVEL_MAP[level]) {
2034
+ if (LOG_LEVEL_MAP[level] === void 0) {
2037
2035
  throw new Error(`Unknown level [${level}]`);
2038
2036
  }
2039
2037
  this.level = level;
@@ -2110,7 +2108,7 @@ var init_common = __esm({
2110
2108
  FILE_TRANSPORT_ENV_VARIABLE = "LOG_FILE";
2111
2109
  FileTransportCacheMap = {};
2112
2110
  FILE_TRANSPORT_TIMEOUT = 150;
2113
- FILE_TRANSPORT_THREASHOLD = 2 * 1024 * 1024;
2111
+ FILE_TRANSPORT_THRESHOLD = 2 * 1024 * 1024;
2114
2112
  FileTransport = (filePath = process.env[FILE_TRANSPORT_ENV_VARIABLE] ? process.env[FILE_TRANSPORT_ENV_VARIABLE] : null, level) => {
2115
2113
  if (filePath && !FileTransportCacheMap[filePath]) {
2116
2114
  FileTransportCacheMap[filePath] = {
@@ -2134,7 +2132,7 @@ var init_common = __esm({
2134
2132
  FileTransportCacheMap[filePath].fileHandler = null;
2135
2133
  });
2136
2134
  }
2137
- FileTransportCacheMap[filePath].lastWrite = now;
2135
+ FileTransportCacheMap[filePath].lastWrite = Date.now();
2138
2136
  const oldBuffer = FileTransportCacheMap[filePath].flushBuffer;
2139
2137
  FileTransportCacheMap[filePath].flushBuffer = "";
2140
2138
  fileHandler.write(oldBuffer, (err) => {
@@ -2152,7 +2150,7 @@ var init_common = __esm({
2152
2150
  FileTransportCacheMap[filePath].currentTimeout = null;
2153
2151
  if (filePath) {
2154
2152
  const now2 = Date.now();
2155
- if (FileTransportCacheMap[filePath].flushBuffer && (now2 - FileTransportCacheMap[filePath].lastWrite > FILE_TRANSPORT_TIMEOUT || FileTransportCacheMap[filePath].flushBuffer.length > FILE_TRANSPORT_THREASHOLD)) {
2153
+ if (FileTransportCacheMap[filePath].flushBuffer && (now2 - FileTransportCacheMap[filePath].lastWrite > FILE_TRANSPORT_TIMEOUT || FileTransportCacheMap[filePath].flushBuffer.length > FILE_TRANSPORT_THRESHOLD)) {
2156
2154
  flush(false);
2157
2155
  }
2158
2156
  }
@@ -2162,10 +2160,9 @@ var init_common = __esm({
2162
2160
  };
2163
2161
  };
2164
2162
  const now = Date.now();
2165
- FileTransportCacheMap[filePath].lastWrite = Date.now();
2166
2163
  FileTransportCacheMap[filePath].flushBuffer += `${out}
2167
2164
  `;
2168
- if (now - FileTransportCacheMap[filePath].lastWrite > FILE_TRANSPORT_TIMEOUT || FileTransportCacheMap[filePath].flushBuffer.length > FILE_TRANSPORT_THREASHOLD) {
2165
+ if (now - FileTransportCacheMap[filePath].lastWrite > FILE_TRANSPORT_TIMEOUT || FileTransportCacheMap[filePath].flushBuffer.length > FILE_TRANSPORT_THRESHOLD) {
2169
2166
  clearTimeout(FileTransportCacheMap[filePath].currentTimeout);
2170
2167
  FileTransportCacheMap[filePath].currentTimeout = null;
2171
2168
  return flush(true);
@@ -2255,6 +2252,7 @@ var init_router = __esm({
2255
2252
  init_session();
2256
2253
  init_body_parser();
2257
2254
  init_lib2();
2255
+ init_built_in_parsers();
2258
2256
  Router2 = class {
2259
2257
  constructor(config) {
2260
2258
  this.config = config;
@@ -2689,26 +2687,30 @@ function parseFrame(buffer) {
2689
2687
  const opCode = firstByte & 15;
2690
2688
  if (opCode === OPCODES.close) {
2691
2689
  return null;
2690
+ } else if (opCode === OPCODES.ping) {
2691
+ return PING;
2692
2692
  } else if (opCode !== OPCODES.text) {
2693
- return;
2693
+ return null;
2694
2694
  }
2695
2695
  const secondByte = buffer.readUInt8(1);
2696
2696
  let offset = 2;
2697
2697
  let payloadLength = secondByte & 127;
2698
2698
  if (payloadLength === 126) {
2699
+ payloadLength = buffer.readUInt16BE(offset);
2699
2700
  offset += 2;
2700
2701
  } else if (payloadLength === 127) {
2702
+ payloadLength = Number(buffer.readBigUInt64BE(offset));
2701
2703
  offset += 8;
2702
2704
  }
2703
2705
  const isMasked = Boolean(secondByte >>> 7 & 1);
2704
2706
  if (isMasked) {
2705
2707
  const maskingKey = buffer.readUInt32BE(offset);
2706
2708
  offset += 4;
2707
- const payload = buffer.subarray(offset);
2709
+ const payload = buffer.subarray(offset, offset + payloadLength);
2708
2710
  const result = unmask(payload, maskingKey);
2709
2711
  return result.toString("utf-8");
2710
2712
  }
2711
- return buffer.subarray(offset).toString("utf-8");
2713
+ return buffer.subarray(offset, offset + payloadLength).toString("utf-8");
2712
2714
  }
2713
2715
  function unmask(payload, maskingKey) {
2714
2716
  const result = Buffer.alloc(payload.byteLength);
@@ -2737,13 +2739,13 @@ function createFrame(payload) {
2737
2739
  buffer[1] = payloadLength;
2738
2740
  if (payloadLength === 126) {
2739
2741
  buffer.writeUInt16BE(payloadByteLength, 2);
2740
- } else if (payloadByteLength === 127) {
2742
+ } else if (payloadLength === 127) {
2741
2743
  buffer.writeBigUInt64BE(BigInt(payloadByteLength), 2);
2742
2744
  }
2743
2745
  buffer.write(payload, payloadBytesOffset);
2744
2746
  return buffer;
2745
2747
  }
2746
- var import_crypto3, WebSocketServer, OPCODES, GUID;
2748
+ var import_crypto3, WebSocketServer, PING, OPCODES, GUID;
2747
2749
  var init_websocket = __esm({
2748
2750
  "node_modules/@miqro/core/build/websocket.js"() {
2749
2751
  import_crypto3 = require("crypto");
@@ -2767,14 +2769,7 @@ var init_websocket = __esm({
2767
2769
  const clients = this.clients.values();
2768
2770
  for (const client of clients) {
2769
2771
  if (fromUUID === void 0 || client.uuid !== fromUUID) {
2770
- tR.push(new Promise(async (resolve24, reject) => {
2771
- try {
2772
- await this.writeTo(client.uuid, data);
2773
- resolve24();
2774
- } catch (e) {
2775
- reject(e);
2776
- }
2777
- }));
2772
+ tR.push(this.writeTo(client.uuid, data));
2778
2773
  }
2779
2774
  }
2780
2775
  await Promise.allSettled(tR);
@@ -2850,7 +2845,13 @@ var init_websocket = __esm({
2850
2845
  socket.write(createUpgradeHeaders(acceptKey, extraHeaders));
2851
2846
  socket.on("data", (data) => {
2852
2847
  const frame = parseFrame(data);
2853
- if (frame !== null) {
2848
+ if (frame === PING) {
2849
+ try {
2850
+ socket.write(Buffer.from([138, 0]));
2851
+ } catch (e) {
2852
+ req.logger.error(e);
2853
+ }
2854
+ } else if (frame !== null) {
2854
2855
  if (!this.options.onMessage) {
2855
2856
  socket.end();
2856
2857
  socket.destroy();
@@ -2861,6 +2862,14 @@ var init_websocket = __esm({
2861
2862
  req.logger.error(e);
2862
2863
  }
2863
2864
  }
2865
+ } else {
2866
+ try {
2867
+ socket.write(Buffer.from([136, 0]));
2868
+ } catch (e) {
2869
+ req.logger.error(e);
2870
+ }
2871
+ socket.end();
2872
+ socket.destroy();
2864
2873
  }
2865
2874
  });
2866
2875
  socket.on("error", (error2) => {
@@ -2899,7 +2908,8 @@ var init_websocket = __esm({
2899
2908
  }
2900
2909
  }
2901
2910
  };
2902
- OPCODES = { text: 1, close: 8 };
2911
+ PING = /* @__PURE__ */ Symbol();
2912
+ OPCODES = { text: 1, close: 8, ping: 9, pong: 10 };
2903
2913
  GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
2904
2914
  }
2905
2915
  });
@@ -3544,7 +3554,7 @@ var require_showdown = __commonJS({
3544
3554
  };
3545
3555
  showdown2.helper.encodeEmailAddress = function(mail) {
3546
3556
  "use strict";
3547
- var encode2 = [
3557
+ var encode3 = [
3548
3558
  function(ch) {
3549
3559
  return "&#" + ch.charCodeAt(0) + ";";
3550
3560
  },
@@ -3557,10 +3567,10 @@ var require_showdown = __commonJS({
3557
3567
  ];
3558
3568
  mail = mail.replace(/./g, function(ch) {
3559
3569
  if (ch === "@") {
3560
- ch = encode2[Math.floor(Math.random() * 2)](ch);
3570
+ ch = encode3[Math.floor(Math.random() * 2)](ch);
3561
3571
  } else {
3562
3572
  var r = Math.random();
3563
- ch = r > 0.9 ? encode2[2](ch) : r > 0.45 ? encode2[1](ch) : encode2[0](ch);
3573
+ ch = r > 0.9 ? encode3[2](ch) : r > 0.45 ? encode3[1](ch) : encode3[0](ch);
3564
3574
  }
3565
3575
  return ch;
3566
3576
  });
@@ -6772,7 +6782,7 @@ function readFile2(path) {
6772
6782
  }
6773
6783
  }
6774
6784
  function getPath(path) {
6775
- const realPath = (0, import_node_path21.resolve)(BASE_PATH, path);
6785
+ const realPath = (0, import_node_fs19.realpathSync)((0, import_node_path21.resolve)(BASE_PATH, path));
6776
6786
  if ((0, import_node_path21.relative)(BASE_PATH, realPath).startsWith("..")) {
6777
6787
  throw new Error("invalid path! [" + path + "]");
6778
6788
  }
@@ -7585,7 +7595,7 @@ function getDefaultOptions() {
7585
7595
  }
7586
7596
 
7587
7597
  // node_modules/@miqro/jsx/build/esm/jsx.js
7588
- var Fragment = Symbol("Fragment");
7598
+ var Fragment = /* @__PURE__ */ Symbol("Fragment");
7589
7599
  function createElement(tag2, attributes, ...children) {
7590
7600
  if (!tag2) {
7591
7601
  throw new Error(`cannot call createElement with [${String(tag2)}] `);
@@ -8564,7 +8574,7 @@ function useElement() {
8564
8574
 
8565
8575
  // node_modules/@miqro/jsx/build/esm/hooks/context.js
8566
8576
  function createContext(defaultValue) {
8567
- const symbol = Symbol();
8577
+ const symbol = /* @__PURE__ */ Symbol();
8568
8578
  return {
8569
8579
  provider: createContextProvider(symbol, defaultValue),
8570
8580
  symbol
@@ -9362,7 +9372,7 @@ async function esBuild2(options, logger) {
9362
9372
  return new Promise(async (resolve24, reject) => {
9363
9373
  try {
9364
9374
  const valid = await validateESBuild(logger);
9365
- const esBuildCMD = `${getESBuildBinaryPath()} "${options.entryPoints[0]}" ${(options.external ? options.external : NODEJS_EXTERNAL).map((e) => `--external:${e}`).join(" ")} --loader:.js=jsx --jsx-factory=${options.jsxFactory} --jsx-fragment=${options.jsxFragment} ${options.bundle ? " --bundle" : ""}${options.minify ? " --minify" : ""}${options.outfile ? ` --outfile="${options.outfile}"` : ""}${options.platform ? ` --platform=${options.platform}` : ""}${options.mainFields ? ` --main-fields=${options.mainFields}` : ""}${options.keepNames ? ` --keep-names` : ""}`;
9375
+ const esBuildCMD = `${getESBuildBinaryPath()} "${options.entryPoints[0]}" ${(options.external ? options.external : NODEJS_EXTERNAL).map((e) => `--external:"${e}"`).join(" ")} --loader:.js=jsx --jsx-factory=${options.jsxFactory} --jsx-fragment=${options.jsxFragment} ${options.bundle ? " --bundle" : ""}${options.minify ? " --minify" : ""}${options.outfile ? ` --outfile="${options.outfile}"` : ""}${options.platform ? ` --platform=${options.platform}` : ""}${options.mainFields ? ` --main-fields=${options.mainFields}` : ""}${options.keepNames ? ` --keep-names` : ""}`;
9366
9376
  logger?.trace(esBuildCMD);
9367
9377
  if (!valid) {
9368
9378
  const err = new Error(`esbuild installation at [${getESBuildBinaryPath()}] tampered`);
@@ -9815,7 +9825,7 @@ function sqlite3ExecutorPrepare(args) {
9815
9825
  const where = getWhereStatement(q);
9816
9826
  const returing = q._returning.length === 0 ? "*" : q._returning.join(",");
9817
9827
  const whereSQL = where.sql !== "" ? ` WHERE ${where.sql}` : "";
9818
- const sql = `DELETE FROM ${q._table}${whereSQL}${getOrderBy(q._orderBy)}${getLimit(q._limitBy, q._offsetBy)} RETURNING ${returing}`;
9828
+ const sql = `DELETE FROM "${q._table}"${whereSQL}${getOrderBy(q._orderBy)}${getLimit(q._limitBy, q._offsetBy)} RETURNING ${returing}`;
9819
9829
  return {
9820
9830
  sql,
9821
9831
  values: where.values
@@ -9823,22 +9833,22 @@ function sqlite3ExecutorPrepare(args) {
9823
9833
  }
9824
9834
  case "create-database": {
9825
9835
  const q = args;
9826
- const sql = `CREATE DATABASE ${q._dbName}`;
9836
+ const sql = `CREATE DATABASE "${q._dbName}"`;
9827
9837
  return sql;
9828
9838
  }
9829
9839
  case "create-table": {
9830
9840
  const q = args;
9831
- const sql = `CREATE TABLE${q._ignoreDuplicate ? " IF NOT EXISTS" : ""} ${q._table}${getCreateTableColumns(q._definition)}`;
9841
+ const sql = `CREATE TABLE${q._ignoreDuplicate ? " IF NOT EXISTS" : ""} "${q._table}"${getCreateTableColumns(q._definition)}`;
9832
9842
  return sql;
9833
9843
  }
9834
9844
  case "drop-database": {
9835
9845
  const q = args;
9836
- const sql = `DROP DATABASE${q._ignoreDuplicate ? " IF EXISTS" : ""} ${q._dbName}`;
9846
+ const sql = `DROP DATABASE${q._ignoreDuplicate ? " IF EXISTS" : ""} "${q._dbName}"`;
9837
9847
  return sql;
9838
9848
  }
9839
9849
  case "drop-table": {
9840
9850
  const q = args;
9841
- const sql = `DROP TABLE${q._ignoreDuplicate ? " IF EXISTS" : ""} ${q._table}`;
9851
+ const sql = `DROP TABLE${q._ignoreDuplicate ? " IF EXISTS" : ""} "${q._table}"`;
9842
9852
  return sql;
9843
9853
  }
9844
9854
  case "alter-table": {
@@ -9857,17 +9867,17 @@ function sqlite3ExecutorPrepare(args) {
9857
9867
  throw new Error("unsupported alter action add without definition");
9858
9868
  }
9859
9869
  alters.push({
9860
- sql: `ALTER TABLE ${q._table} ADD COLUMN ${getCreateTableColumn(l._column, l._definition, [])}`
9870
+ sql: `ALTER TABLE "${q._table}" ADD COLUMN ${getCreateTableColumn(l._column, l._definition, [])}`
9861
9871
  });
9862
9872
  break;
9863
9873
  case "drop":
9864
9874
  alters.push({
9865
- sql: `ALTER TABLE ${q._table} DROP COLUMN ${l._column}`
9875
+ sql: `ALTER TABLE "${q._table}" DROP COLUMN "${l._column}"`
9866
9876
  });
9867
9877
  break;
9868
9878
  case "rename":
9869
9879
  alters.push({
9870
- sql: `ALTER TABLE ${q._table} RENAME COLUMN ${l._column} TO ${l._newName}`
9880
+ sql: `ALTER TABLE "${q._table}" RENAME COLUMN "${l._column}" TO "${l._newName}"`
9871
9881
  });
9872
9882
  break;
9873
9883
  default:
@@ -9880,7 +9890,7 @@ function sqlite3ExecutorPrepare(args) {
9880
9890
  const q = args;
9881
9891
  const rows = getInsertValues(q._columns, q._values);
9882
9892
  const returing = q._returning.length === 0 ? "*" : q._returning.join(",");
9883
- const sql = `INSERT${q._ignoreDuplicate ? " OR IGNORE" : ""} INTO ${q._table}${getInsertColumns(q._columns)}${rows.sql} RETURNING ${returing}`;
9893
+ const sql = `INSERT${q._ignoreDuplicate ? " OR IGNORE" : ""} INTO "${q._table}"${getInsertColumns(q._columns)}${rows.sql} RETURNING ${returing}`;
9884
9894
  return [{
9885
9895
  sql,
9886
9896
  values: rows.values
@@ -9891,7 +9901,7 @@ function sqlite3ExecutorPrepare(args) {
9891
9901
  const isSelect = args._type === "select";
9892
9902
  const q = isSelect ? args : args;
9893
9903
  const where = getWhereStatement(q);
9894
- const columnsSQL = isSelect ? `SELECT ${renderNameAS(q._columns)}` : "SELECT count(*) as count";
9904
+ const columnsSQL = isSelect ? `SELECT ${renderNameAS(q._columns, void 0, '"')}` : "SELECT count(*) as count";
9895
9905
  const whereSQL = where.sql !== "" ? ` WHERE ${where.sql}` : "";
9896
9906
  const fromSQL = ` FROM ${renderNameAS(q._selectFrom)}`;
9897
9907
  const join15 = q._joins.map((j) => getJoin(j));
@@ -9917,8 +9927,8 @@ function sqlite3ExecutorPrepare(args) {
9917
9927
  const returing = q._returning.length === 0 ? "*" : q._returning.join(",");
9918
9928
  const where = getWhereStatement(q);
9919
9929
  const whereSQL = where.sql !== "" ? ` WHERE ${where.sql}` : "";
9920
- const setSQL = ` SET ${q._sets.map((set) => `${set.column}=?`)}`;
9921
- const sql = `UPDATE ${q._table}${setSQL}${whereSQL}${getOrderBy(q._orderBy)}${getLimit(q._limitBy, q._offsetBy)} RETURNING ${returing}`;
9930
+ const setSQL = ` SET ${q._sets.map((set) => `${renderColumn(set.column)}=?`)}`;
9931
+ const sql = `UPDATE "${q._table}"${setSQL}${whereSQL}${getOrderBy(q._orderBy)}${getLimit(q._limitBy, q._offsetBy)} RETURNING ${returing}`;
9922
9932
  return [{
9923
9933
  sql,
9924
9934
  values: q._sets.map((set) => set.value).concat(where.values)
@@ -10027,7 +10037,7 @@ function getWhereStatement(where) {
10027
10037
  case "gte": {
10028
10038
  const { _column, _value } = getWhereFilterColumnName(filter);
10029
10039
  ret = mergePrepareArgs(ret, {
10030
- sql: `${renderColumn(_value)}>=?`,
10040
+ sql: `${renderColumn(_column)}>=?`,
10031
10041
  values: [_value]
10032
10042
  });
10033
10043
  break;
@@ -10087,23 +10097,23 @@ function getCreateTableColumn(columnName, def, primaryKeyColumns) {
10087
10097
  const autoIncrement = `${def.autoIncrement !== void 0 && def.autoIncrement === true ? ` AUTOINCREMENT` : ""}`;
10088
10098
  switch (def.type) {
10089
10099
  case "datetime":
10090
- return `${columnName} DATETIME${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
10100
+ return `"${columnName}" DATETIME${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
10091
10101
  case "boolean":
10092
- return `${columnName} TINYINT${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
10102
+ return `"${columnName}" TINYINT${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
10093
10103
  case "json":
10094
10104
  case "string":
10095
- return `${columnName} TEXT${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
10105
+ return `"${columnName}" TEXT${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
10096
10106
  case "real":
10097
- return `${columnName} REAL${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
10107
+ return `"${columnName}" REAL${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
10098
10108
  case "bigint":
10099
10109
  case "integer":
10100
- return `${columnName} INTEGER${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
10110
+ return `"${columnName}" INTEGER${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
10101
10111
  default:
10102
10112
  throw new Error("unsupported type " + def.type);
10103
10113
  }
10104
10114
  }
10105
10115
  function getInsertColumns(columns) {
10106
- return `(${columns.join(",")})`;
10116
+ return `(${columns.map((c) => renderColumn(c)).join(",")})`;
10107
10117
  }
10108
10118
  function getInsertValues(columns, values) {
10109
10119
  let args = [];
@@ -10115,21 +10125,21 @@ function getInsertValues(columns, values) {
10115
10125
  values: args
10116
10126
  };
10117
10127
  }
10118
- function renderNameAS(input, join15 = ", ") {
10128
+ function renderNameAS(input, join15 = ", ", wrapper = '"') {
10119
10129
  const list = input instanceof Array ? input : [input];
10120
- return list.map((i) => typeof i === "string" ? i : `${i.name} AS ${i.as}`).join(join15);
10130
+ return list.map((i) => typeof i === "string" ? `${renderColumn(i, wrapper)}` : `${renderColumn(i.name, wrapper)} AS ${renderColumn(i.as, wrapper)}`).join(join15);
10121
10131
  }
10122
- function getGroupBy(groupBy) {
10123
- return groupBy.length > 0 ? ` GROUP BY ${groupBy.join(",")}` : "";
10132
+ function getGroupBy(groupBy, wrapper = '"') {
10133
+ return groupBy.length > 0 ? ` GROUP BY ${groupBy.map((g) => renderColumn(g, wrapper)).join(",")}` : "";
10124
10134
  }
10125
- function getOrderBy(orderBy) {
10126
- return orderBy.length > 0 ? ` ORDER BY ${orderBy.map((o) => `${o.column} ${o.mode}`).join(",")}` : "";
10135
+ function getOrderBy(orderBy, wrapper = '"') {
10136
+ return orderBy.length > 0 ? ` ORDER BY ${orderBy.map((o) => `${renderColumn(o.column, wrapper)} ${o.mode}`).join(",")}` : "";
10127
10137
  }
10128
10138
  function getLimit(limit, offsetBy) {
10129
10139
  return `${limit !== void 0 ? ` LIMIT ${limit}` : ""}${offsetBy ? ` OFFSET ${offsetBy}` : ""}`;
10130
10140
  }
10131
- function renderColumn(column) {
10132
- return column;
10141
+ function renderColumn(column, wrapper = '"') {
10142
+ return `${column.split(".").map((c) => `${wrapper}${c}${wrapper}`).join(".")}`;
10133
10143
  }
10134
10144
  function mergePrepareArgs(to, merge, concatOperator = " AND ") {
10135
10145
  return (merge instanceof Array ? merge : [merge]).reduce((current, value) => {
@@ -10199,6 +10209,77 @@ var TableSchemaSchema = {
10199
10209
  dictType: "ColumnDefinition"
10200
10210
  };
10201
10211
 
10212
+ // node_modules/@miqro/query/build/executors/transform.js
10213
+ function sqliteTransformInput(value) {
10214
+ if (value === null || value === void 0)
10215
+ return value;
10216
+ switch (typeof value) {
10217
+ case "boolean":
10218
+ return value ? 1 : 0;
10219
+ case "bigint":
10220
+ return value.toString();
10221
+ case "object":
10222
+ if (value instanceof Date)
10223
+ return value.toISOString();
10224
+ return JSON.stringify(value);
10225
+ default:
10226
+ return value;
10227
+ }
10228
+ }
10229
+ function sqliteTransformOutput(type, value) {
10230
+ if (value === null || value === void 0)
10231
+ return value;
10232
+ switch (type) {
10233
+ case "boolean":
10234
+ return value === 1 || value === "1" || value === "true" || value === true ? true : false;
10235
+ case "datetime":
10236
+ return value instanceof Date ? value : new Date(value);
10237
+ case "bigint":
10238
+ return BigInt(value);
10239
+ case "real":
10240
+ case "integer": {
10241
+ const f = parseFloat(value);
10242
+ return isNaN(f) ? null : f;
10243
+ }
10244
+ case "json":
10245
+ return typeof value === "string" ? JSON.parse(value) : value;
10246
+ case "string":
10247
+ return value;
10248
+ default:
10249
+ return value;
10250
+ }
10251
+ }
10252
+ function pgTransformInput(value) {
10253
+ if (value === null || value === void 0)
10254
+ return value;
10255
+ switch (typeof value) {
10256
+ case "bigint":
10257
+ return value.toString();
10258
+ case "object":
10259
+ if (value instanceof Date)
10260
+ return value;
10261
+ return JSON.stringify(value);
10262
+ default:
10263
+ return value;
10264
+ }
10265
+ }
10266
+ function pgTransformOutput(type, value) {
10267
+ if (value === null || value === void 0)
10268
+ return value;
10269
+ switch (type) {
10270
+ case "integer":
10271
+ return parseInt(value, 10);
10272
+ case "datetime":
10273
+ return value instanceof Date ? value : new Date(value);
10274
+ case "bigint":
10275
+ return BigInt(value);
10276
+ case "json":
10277
+ return typeof value === "string" ? JSON.parse(value) : value;
10278
+ default:
10279
+ return value;
10280
+ }
10281
+ }
10282
+
10202
10283
  // node_modules/@miqro/query/build/executors/sqlite3/lib.js
10203
10284
  var SQLITE_CONFIG_SCHEMA = {
10204
10285
  type: "object",
@@ -10219,6 +10300,8 @@ async function sqlite3Executor(config) {
10219
10300
  await driver.close();
10220
10301
  },
10221
10302
  prepare: sqlite3ExecutorPrepare,
10303
+ transformInput: sqliteTransformInput,
10304
+ transformOutput: sqliteTransformOutput,
10222
10305
  query: async function sqlite3Executor2(sql, values) {
10223
10306
  return new Promise((resolve24, reject) => {
10224
10307
  const st = driver.prepare(sql, values, function(error2) {
@@ -10268,18 +10351,20 @@ async function postgresExecutor(config) {
10268
10351
  disconnect: async function postgresExecutorDisconnect() {
10269
10352
  await driver.end();
10270
10353
  },
10354
+ transformInput: pgTransformInput,
10355
+ transformOutput: pgTransformOutput,
10271
10356
  prepare: function postgresExecutorPrepare(args) {
10272
10357
  switch (args._type) {
10273
10358
  case "create-table": {
10274
10359
  const q = args;
10275
- const sql = `CREATE TABLE${q._ignoreDuplicate ? " IF NOT EXISTS" : ""} ${q._table}${getCreateTableColumns2(q._definition)}`;
10360
+ const sql = `CREATE TABLE${q._ignoreDuplicate ? " IF NOT EXISTS" : ""} "${q._table}"${getCreateTableColumns2(q._definition)}`;
10276
10361
  return sql;
10277
10362
  }
10278
10363
  case "insert": {
10279
10364
  const q = args;
10280
10365
  const rows = getInsertValues(q._columns, q._values);
10281
10366
  const returing = q._returning.length === 0 ? "*" : q._returning.join(",");
10282
- const sql = `INSERT INTO ${q._table}${getInsertColumns(q._columns)}${rows.sql} ${q._ignoreDuplicate ? "ON CONFLICT DO NOTHING " : ""}RETURNING ${returing}`;
10367
+ const sql = `INSERT INTO "${q._table}"${getInsertColumns(q._columns)}${rows.sql} ${q._ignoreDuplicate ? "ON CONFLICT DO NOTHING " : ""}RETURNING ${returing}`;
10283
10368
  return {
10284
10369
  sql,
10285
10370
  values: rows.values
@@ -10290,7 +10375,7 @@ async function postgresExecutor(config) {
10290
10375
  let alters = [];
10291
10376
  if (q._renameTable) {
10292
10377
  alters.push({
10293
- sql: `ALTER TABLE ${q._table} RENAME TO ?`,
10378
+ sql: `ALTER TABLE "${q._table}" RENAME TO "?"`,
10294
10379
  values: [q._renameTable]
10295
10380
  });
10296
10381
  }
@@ -10301,17 +10386,17 @@ async function postgresExecutor(config) {
10301
10386
  throw new Error("unsupported alter action add without definition");
10302
10387
  }
10303
10388
  alters.push({
10304
- sql: `ALTER TABLE ${q._table} ADD COLUMN ${getCreateTableColumn2(l._column, l._definition, [])}`
10389
+ sql: `ALTER TABLE "${q._table}" ADD COLUMN ${getCreateTableColumn2(l._column, l._definition, [])}`
10305
10390
  });
10306
10391
  break;
10307
10392
  case "drop":
10308
10393
  alters.push({
10309
- sql: `ALTER TABLE ${q._table} DROP COLUMN ${l._column}`
10394
+ sql: `ALTER TABLE "${q._table}" DROP COLUMN "${l._column}"`
10310
10395
  });
10311
10396
  break;
10312
10397
  case "rename":
10313
10398
  alters.push({
10314
- sql: `ALTER TABLE ${q._table} RENAME COLUMN ${l._column} TO ${l._newName}`
10399
+ sql: `ALTER TABLE "${q._table}" RENAME COLUMN "${l._column}" TO "${l._newName}"`
10315
10400
  });
10316
10401
  break;
10317
10402
  default:
@@ -10349,22 +10434,22 @@ function getCreateTableColumn2(columnName, def, primaryKeyColumns) {
10349
10434
  const notNull = `${def.allowNull == false ? " NOT NULL" : ""}`;
10350
10435
  const defaultValue = `${def.defaultValue !== void 0 ? ` DEFAULT '${def.defaultValue}'` : ""}`;
10351
10436
  if (def.autoIncrement) {
10352
- return `${columnName} BIGSERIAL${primaryKey}`;
10437
+ return `"${columnName}" BIGSERIAL${primaryKey}`;
10353
10438
  }
10354
10439
  switch (def.type) {
10355
10440
  case "datetime":
10356
- return `${columnName} TIMESTAMP${primaryKey}${notNull}${defaultValue}`;
10441
+ return `"${columnName}" TIMESTAMP${primaryKey}${notNull}${defaultValue}`;
10357
10442
  case "boolean":
10358
- return `${columnName} BOOLEAN${primaryKey}${notNull}${defaultValue}`;
10443
+ return `"${columnName}" BOOLEAN${primaryKey}${notNull}${defaultValue}`;
10359
10444
  case "real":
10360
- return `${columnName} REAL${primaryKey}${notNull}${defaultValue}`;
10445
+ return `"${columnName}" REAL${primaryKey}${notNull}${defaultValue}`;
10361
10446
  case "json":
10362
10447
  case "string":
10363
- return `${columnName} TEXT${primaryKey}${notNull}${defaultValue}`;
10448
+ return `"${columnName}" TEXT${primaryKey}${notNull}${defaultValue}`;
10364
10449
  case "bigint":
10365
- return `${columnName} bigint${primaryKey}${notNull}${defaultValue}`;
10450
+ return `"${columnName}" bigint${primaryKey}${notNull}${defaultValue}`;
10366
10451
  case "integer":
10367
- return `${columnName} INTEGER${primaryKey}${notNull}${defaultValue}`;
10452
+ return `"${columnName}" INTEGER${primaryKey}${notNull}${defaultValue}`;
10368
10453
  default:
10369
10454
  throw new Error("unsupported type " + def.type);
10370
10455
  }
@@ -10391,6 +10476,15 @@ function tokens2Postgres(inSql, values) {
10391
10476
  }
10392
10477
 
10393
10478
  // node_modules/@miqro/query/build/query/utils.js
10479
+ function applyTransformInput(executor, stmts) {
10480
+ const ti = executor.transformInput.bind(executor);
10481
+ const list = stmts instanceof Array ? stmts : typeof stmts === "string" ? [] : [stmts];
10482
+ for (const stmt of list) {
10483
+ if (stmt.values) {
10484
+ stmt.values = stmt.values.map(ti);
10485
+ }
10486
+ }
10487
+ }
10394
10488
  function getStatements(stmts) {
10395
10489
  if (stmts instanceof Array) {
10396
10490
  return stmts;
@@ -10557,7 +10651,7 @@ var AlterTable = class _AlterTable {
10557
10651
 
10558
10652
  // node_modules/@miqro/query/build/query/insert.js
10559
10653
  var Insert = class _Insert {
10560
- constructor(db, _table) {
10654
+ constructor(db, _table, schema) {
10561
10655
  this.db = db;
10562
10656
  this._table = _table;
10563
10657
  this._type = "insert";
@@ -10565,6 +10659,7 @@ var Insert = class _Insert {
10565
10659
  this._returning = [];
10566
10660
  this._values = [];
10567
10661
  this._ignoreDuplicate = false;
10662
+ this._schema = schema;
10568
10663
  }
10569
10664
  value(value) {
10570
10665
  this._values = this._values.concat(value);
@@ -10573,7 +10668,7 @@ var Insert = class _Insert {
10573
10668
  values(value) {
10574
10669
  return this.value(value);
10575
10670
  }
10576
- returning(column) {
10671
+ returning(...column) {
10577
10672
  this._returning = this._returning.concat(column);
10578
10673
  return this;
10579
10674
  }
@@ -10588,14 +10683,23 @@ var Insert = class _Insert {
10588
10683
  return getStatements(this.db.getExecutor().prepare(this));
10589
10684
  }
10590
10685
  async yield(logger) {
10591
- return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
10686
+ const executor = this.db.getExecutor();
10687
+ const ti = executor.transformInput.bind(executor);
10688
+ this._values = this._values.map((row) => {
10689
+ const out = {};
10690
+ for (const key of Object.keys(row)) {
10691
+ out[key] = ti(row[key]);
10692
+ }
10693
+ return out;
10694
+ });
10695
+ return runStatements(this.db, executor.prepare(this), logger);
10592
10696
  }
10593
10697
  ignoreDuplicates(ignore = true) {
10594
10698
  this._ignoreDuplicate = ignore;
10595
10699
  return this;
10596
10700
  }
10597
10701
  clone() {
10598
- const ret = new _Insert(this.db, this._table);
10702
+ const ret = new _Insert(this.db, this._table, this._schema);
10599
10703
  ret._columns = structuredClone(this._columns);
10600
10704
  ret._values = structuredClone(this._values);
10601
10705
  ret._returning = structuredClone(this._returning);
@@ -10605,11 +10709,19 @@ var Insert = class _Insert {
10605
10709
  };
10606
10710
 
10607
10711
  // node_modules/@miqro/query/build/executors/where.js
10608
- var Where = class {
10712
+ var Where = class _Where {
10609
10713
  constructor() {
10610
10714
  this._orderBy = [];
10611
10715
  this._filters = [];
10612
10716
  }
10717
+ clone() {
10718
+ const ret = new _Where();
10719
+ ret._filters = structuredClone(this._filters);
10720
+ ret._orderBy = structuredClone(this._orderBy);
10721
+ ret._limitBy = this._limitBy;
10722
+ ret._offsetBy = this._offsetBy;
10723
+ return ret;
10724
+ }
10613
10725
  order(column, mode) {
10614
10726
  this._orderBy.push({ column, mode });
10615
10727
  return this;
@@ -10737,9 +10849,167 @@ var Where = class {
10737
10849
  }
10738
10850
  };
10739
10851
 
10852
+ // node_modules/@miqro/query/build/query/include.js
10853
+ function getPrimaryKey(schema) {
10854
+ for (const [key, def] of Object.entries(schema)) {
10855
+ if (def.primaryKey)
10856
+ return key;
10857
+ }
10858
+ return "id";
10859
+ }
10860
+ function transformOutputRow(transformOutput, schema, row) {
10861
+ const out = {};
10862
+ for (const key of Object.keys(row)) {
10863
+ const def = schema[key];
10864
+ out[key] = def ? transformOutput(def.type, row[key]) : row[key];
10865
+ }
10866
+ return out;
10867
+ }
10868
+ function _classifyRecursive(filters, assocNames, assocFilters) {
10869
+ const rootFilters = [];
10870
+ for (const filter of filters) {
10871
+ if (filter._column !== void 0) {
10872
+ const dot = filter._column.indexOf(".");
10873
+ if (dot !== -1) {
10874
+ const prefix = filter._column.substring(0, dot);
10875
+ if (assocNames.has(prefix)) {
10876
+ assocFilters.get(prefix).push({
10877
+ ...filter,
10878
+ _column: filter._column.substring(dot + 1)
10879
+ });
10880
+ continue;
10881
+ }
10882
+ }
10883
+ rootFilters.push(filter);
10884
+ } else if (filter._where !== void 0) {
10885
+ const nestedList = Array.isArray(filter._where) ? filter._where : [filter._where];
10886
+ const rebuiltList = nestedList.map((w) => ({
10887
+ ...w,
10888
+ _filters: _classifyRecursive(w._filters, assocNames, assocFilters)
10889
+ })).filter((w) => w._filters.length > 0);
10890
+ if (rebuiltList.length > 0) {
10891
+ rootFilters.push({
10892
+ ...filter,
10893
+ _where: Array.isArray(filter._where) ? rebuiltList : rebuiltList[0]
10894
+ });
10895
+ }
10896
+ } else {
10897
+ rootFilters.push(filter);
10898
+ }
10899
+ }
10900
+ return rootFilters;
10901
+ }
10902
+ function classifyFilters(filters, include) {
10903
+ const assocNames = new Set(include);
10904
+ const assocFilters = /* @__PURE__ */ new Map();
10905
+ for (const name of include)
10906
+ assocFilters.set(name, []);
10907
+ const rootFilters = _classifyRecursive(filters, assocNames, assocFilters);
10908
+ return { rootFilters, assocFilters };
10909
+ }
10910
+ async function yieldWithInclude(db, schema, assocMap, include, filters, orderBy, limitBy, offsetBy, rootTable, rootColumns, logger) {
10911
+ const { rootFilters, assocFilters } = classifyFilters(filters, include);
10912
+ const pk = getPrimaryKey(schema);
10913
+ const cols = rootColumns.includes(pk) ? rootColumns : [...rootColumns, pk];
10914
+ const assocNames = new Set(include);
10915
+ const rootOrderBy = orderBy.filter((o) => {
10916
+ const dot = o.column.indexOf(".");
10917
+ return dot === -1 || !assocNames.has(o.column.substring(0, dot));
10918
+ });
10919
+ const rootSelect = db.select().from(rootTable);
10920
+ for (const col of cols)
10921
+ rootSelect.column(col);
10922
+ for (const f of rootFilters)
10923
+ rootSelect._filters.push(f);
10924
+ for (const o of rootOrderBy)
10925
+ rootSelect._orderBy.push(o);
10926
+ if (limitBy !== void 0)
10927
+ rootSelect._limitBy = limitBy;
10928
+ if (offsetBy !== void 0)
10929
+ rootSelect._offsetBy = offsetBy;
10930
+ const executor = db.getExecutor();
10931
+ const rootStmts = executor.prepare(rootSelect);
10932
+ applyTransformInput(executor, rootStmts);
10933
+ const rootRaw = await runStatements(db, rootStmts, logger);
10934
+ if (rootRaw.length === 0)
10935
+ return [];
10936
+ const transformedRoots = rootRaw.map((row) => transformOutputRow(executor.transformOutput, schema, row));
10937
+ const rootPKs = transformedRoots.map((r) => r[pk]);
10938
+ const assocResults = await Promise.all(include.map(async (assocName) => {
10939
+ const assocDef = assocMap.get(assocName);
10940
+ if (!assocDef)
10941
+ throw new Error(`unknown association: ${assocName}`);
10942
+ const assocModel = assocDef.model();
10943
+ const assocSchema = assocModel.schema;
10944
+ const assocTable = assocModel.tableName;
10945
+ const extraFilters = assocFilters.get(assocName) ?? [];
10946
+ const fk = assocDef.foreignKey;
10947
+ const lk = assocDef.localKey ?? "id";
10948
+ let inColumn;
10949
+ let inValues;
10950
+ if (assocDef.type === "belongsTo") {
10951
+ inColumn = lk;
10952
+ inValues = [...new Set(transformedRoots.map((r) => r[fk]).filter((v) => v != null))];
10953
+ } else {
10954
+ inColumn = fk;
10955
+ inValues = rootPKs;
10956
+ }
10957
+ if (inValues.length === 0) {
10958
+ return { assocName, assocDef, rows: [], hadFilters: extraFilters.length > 0 };
10959
+ }
10960
+ const assocSelect = db.select().from(assocTable);
10961
+ for (const col of Object.keys(assocSchema))
10962
+ assocSelect.column(col);
10963
+ assocSelect._filters.push({ _type: "in", _column: inColumn, _value: inValues });
10964
+ for (const f of extraFilters)
10965
+ assocSelect._filters.push(f);
10966
+ const stmts = executor.prepare(assocSelect);
10967
+ applyTransformInput(executor, stmts);
10968
+ const raw = await runStatements(db, stmts, logger);
10969
+ const rows = raw.map((row) => transformOutputRow(executor.transformOutput, assocSchema, row));
10970
+ return { assocName, assocDef, rows, hadFilters: extraFilters.length > 0 };
10971
+ }));
10972
+ const result = [];
10973
+ for (const root of transformedRoots) {
10974
+ const pkVal = root[pk];
10975
+ const instance = { ...root };
10976
+ let excluded = false;
10977
+ for (const { assocName, assocDef, rows, hadFilters } of assocResults) {
10978
+ const fk = assocDef.foreignKey;
10979
+ const lk = assocDef.localKey ?? "id";
10980
+ if (assocDef.type === "hasMany") {
10981
+ const matched = rows.filter((r) => r[fk] === pkVal);
10982
+ if (hadFilters && matched.length === 0) {
10983
+ excluded = true;
10984
+ break;
10985
+ }
10986
+ instance[assocName] = matched;
10987
+ } else if (assocDef.type === "hasOne") {
10988
+ const matched = rows.find((r) => r[fk] === pkVal);
10989
+ if (hadFilters && matched === void 0) {
10990
+ excluded = true;
10991
+ break;
10992
+ }
10993
+ instance[assocName] = matched ?? null;
10994
+ } else {
10995
+ const localKeyVal = root[fk];
10996
+ const matched = rows.find((r) => r[lk] === localKeyVal);
10997
+ if (hadFilters && matched === void 0) {
10998
+ excluded = true;
10999
+ break;
11000
+ }
11001
+ instance[assocName] = matched ?? null;
11002
+ }
11003
+ }
11004
+ if (!excluded)
11005
+ result.push(instance);
11006
+ }
11007
+ return result;
11008
+ }
11009
+
10740
11010
  // node_modules/@miqro/query/build/query/select.js
10741
11011
  var Select = class _Select extends Where {
10742
- constructor(db) {
11012
+ constructor(db, schema, associations) {
10743
11013
  super();
10744
11014
  this.db = db;
10745
11015
  this._type = "select";
@@ -10748,12 +11018,20 @@ var Select = class _Select extends Where {
10748
11018
  this._groupBy = [];
10749
11019
  this._joins = [];
10750
11020
  this._orderBy = [];
11021
+ this._schema = schema;
11022
+ if (associations) {
11023
+ this._assocMap = new Map(Object.entries(associations));
11024
+ }
11025
+ }
11026
+ include(...names) {
11027
+ this._include = names;
11028
+ return this;
10751
11029
  }
10752
11030
  prepare() {
10753
11031
  return getStatements(this.db.getExecutor().prepare(this));
10754
11032
  }
10755
11033
  clone() {
10756
- const ret = new _Select(this.db);
11034
+ const ret = new _Select(this.db, this._schema);
10757
11035
  ret._filters = structuredClone(this._filters);
10758
11036
  ret._columns = structuredClone(this._columns);
10759
11037
  ret._groupBy = structuredClone(this._groupBy);
@@ -10762,10 +11040,29 @@ var Select = class _Select extends Where {
10762
11040
  ret._joins = structuredClone(this._joins);
10763
11041
  ret._limitBy = this._limitBy;
10764
11042
  ret._offsetBy = this._offsetBy;
11043
+ ret._assocMap = this._assocMap;
11044
+ ret._include = this._include ? [...this._include] : void 0;
10765
11045
  return ret;
10766
11046
  }
10767
11047
  async yield(logger) {
10768
- return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
11048
+ if (this._include && this._include.length > 0 && this._schema && this._assocMap) {
11049
+ return this._yieldWithInclude(logger);
11050
+ }
11051
+ const executor = this.db.getExecutor();
11052
+ const stmts = executor.prepare(this);
11053
+ applyTransformInput(executor, stmts);
11054
+ const rows = await runStatements(this.db, stmts, logger);
11055
+ if (this._schema) {
11056
+ const schema = this._schema;
11057
+ return rows.map((row) => transformOutputRow(executor.transformOutput, schema, row));
11058
+ }
11059
+ return rows;
11060
+ }
11061
+ async _yieldWithInclude(logger) {
11062
+ const schema = this._schema;
11063
+ const rootTable = this._selectFrom.length > 0 ? typeof this._selectFrom[0] === "string" ? this._selectFrom[0] : this._selectFrom[0].name : "";
11064
+ const rootColumns = this._columns.length > 0 ? this._columns.filter((c) => typeof c === "string") : Object.keys(schema);
11065
+ return yieldWithInclude(this.db, schema, this._assocMap, this._include, this._filters, this._orderBy, this._limitBy, this._offsetBy, rootTable, rootColumns, logger);
10769
11066
  }
10770
11067
  column(column) {
10771
11068
  if (column instanceof Array) {
@@ -10775,8 +11072,9 @@ var Select = class _Select extends Where {
10775
11072
  }
10776
11073
  return this;
10777
11074
  }
10778
- columns(column) {
10779
- return this.column(column);
11075
+ columns(...cols) {
11076
+ this._columns = cols;
11077
+ return this;
10780
11078
  }
10781
11079
  from(from) {
10782
11080
  if (from instanceof Array) {
@@ -10853,7 +11151,10 @@ var Count = class _Count extends Where {
10853
11151
  return getStatements(this.db.getExecutor().prepare(this));
10854
11152
  }
10855
11153
  async yield(logger) {
10856
- return parseCountResult(await runStatements(this.db, this.db.getExecutor().prepare(this), logger));
11154
+ const executor = this.db.getExecutor();
11155
+ const stmts = executor.prepare(this);
11156
+ applyTransformInput(executor, stmts);
11157
+ return parseCountResult(await runStatements(this.db, stmts, logger));
10857
11158
  }
10858
11159
  };
10859
11160
  async function parseCountResult(rows) {
@@ -10864,22 +11165,30 @@ async function parseCountResult(rows) {
10864
11165
 
10865
11166
  // node_modules/@miqro/query/build/query/update.js
10866
11167
  var Update = class _Update extends Where {
10867
- constructor(db, _table) {
11168
+ constructor(db, _table, schema) {
10868
11169
  super();
10869
11170
  this.db = db;
10870
11171
  this._table = _table;
10871
11172
  this._type = "update";
10872
11173
  this._sets = [];
10873
11174
  this._returning = [];
11175
+ this._schema = schema;
10874
11176
  }
10875
11177
  prepare() {
10876
11178
  return getStatements(this.db.getExecutor().prepare(this));
10877
11179
  }
10878
11180
  async yield(logger) {
10879
- return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
11181
+ const executor = this.db.getExecutor();
11182
+ const ti = executor.transformInput.bind(executor);
11183
+ for (const s of this._sets) {
11184
+ s.value = ti(s.value);
11185
+ }
11186
+ const stmts = executor.prepare(this);
11187
+ applyTransformInput(executor, stmts);
11188
+ return runStatements(this.db, stmts, logger);
10880
11189
  }
10881
11190
  clone() {
10882
- const ret = new _Update(this.db, this._table);
11191
+ const ret = new _Update(this.db, this._table, this._schema);
10883
11192
  ret._filters = structuredClone(this._filters);
10884
11193
  ret._orderBy = structuredClone(this._orderBy);
10885
11194
  ret._sets = structuredClone(this._sets);
@@ -10888,36 +11197,37 @@ var Update = class _Update extends Where {
10888
11197
  ret._offsetBy = this._offsetBy;
10889
11198
  return ret;
10890
11199
  }
10891
- returning(column) {
11200
+ returning(...column) {
10892
11201
  this._returning = this._returning.concat(column);
10893
11202
  return this;
10894
11203
  }
10895
11204
  set(column, value) {
10896
- this._sets.push({
10897
- column,
10898
- value
10899
- });
11205
+ this._sets.push({ column, value });
10900
11206
  return this;
10901
11207
  }
10902
11208
  };
10903
11209
 
10904
11210
  // node_modules/@miqro/query/build/query/delete.js
10905
11211
  var Delete = class _Delete extends Where {
10906
- constructor(db, _table) {
11212
+ constructor(db, _table, schema) {
10907
11213
  super();
10908
11214
  this.db = db;
10909
11215
  this._table = _table;
10910
11216
  this._type = "delete";
10911
11217
  this._returning = [];
11218
+ this._schema = schema;
10912
11219
  }
10913
11220
  prepare() {
10914
11221
  return getStatements(this.db.getExecutor().prepare(this));
10915
11222
  }
10916
11223
  async yield(logger) {
10917
- return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
11224
+ const executor = this.db.getExecutor();
11225
+ const stmts = executor.prepare(this);
11226
+ applyTransformInput(executor, stmts);
11227
+ return runStatements(this.db, stmts, logger);
10918
11228
  }
10919
11229
  clone() {
10920
- const ret = new _Delete(this.db, this._table);
11230
+ const ret = new _Delete(this.db, this._table, this._schema);
10921
11231
  ret._filters = structuredClone(this._filters);
10922
11232
  ret._orderBy = structuredClone(this._orderBy);
10923
11233
  ret._returning = structuredClone(this._returning);
@@ -10925,7 +11235,7 @@ var Delete = class _Delete extends Where {
10925
11235
  ret._offsetBy = this._offsetBy;
10926
11236
  return ret;
10927
11237
  }
10928
- returning(column) {
11238
+ returning(...column) {
10929
11239
  this._returning = this._returning.concat(column);
10930
11240
  return this;
10931
11241
  }
@@ -10956,74 +11266,8 @@ var DropDatabase = class _DropDatabase {
10956
11266
  }
10957
11267
  };
10958
11268
 
10959
- // node_modules/@miqro/query/build/executors/sqlite3-cli/lib.js
10960
- var import_child_process = require("child_process");
10961
- var SQLITE_CONFIG_SCHEMA2 = {
10962
- type: "object",
10963
- mode: "remove_extra",
10964
- properties: {
10965
- storage: "string"
10966
- }
10967
- };
10968
- async function sqlite3CLIExecutor(config) {
10969
- const databaseOptions = parser2.parse(config, SQLITE_CONFIG_SCHEMA2);
10970
- if (!databaseOptions) {
10971
- throw new Error("config not valid");
10972
- }
10973
- (config.logger ? config.logger : console).error(`sqlite3-cli is affected by sql injection. do not use! only for testing!`);
10974
- return {
10975
- // we just use the sqlite3Executor prepare function
10976
- prepare: sqlite3ExecutorPrepare,
10977
- disconnect: async function sqlite3ExecutorDisconnect() {
10978
- },
10979
- query: async function sqlite3Executor2(sql, values) {
10980
- return new Promise((resolve24, reject) => {
10981
- try {
10982
- let i = 0;
10983
- const raw = sql.replaceAll("?", (sub) => {
10984
- const value = values ? values[i] : void 0;
10985
- if (value === void 0) {
10986
- throw new Error("cannot convert query");
10987
- }
10988
- i++;
10989
- return `'${value}'`;
10990
- });
10991
- if (values && i !== values.length) {
10992
- throw new Error("cannot convert query");
10993
- }
10994
- (0, import_child_process.exec)(`sqlite3 -json "${databaseOptions.storage}" "${raw}"`, (error2, stdout, stderr) => {
10995
- try {
10996
- if (error2) {
10997
- if (stderr) {
10998
- reject(new Error(stderr));
10999
- } else {
11000
- reject(error2);
11001
- }
11002
- } else {
11003
- if (stderr) {
11004
- reject(new Error(stderr));
11005
- } else {
11006
- if (stdout) {
11007
- resolve24(JSON.parse(stdout));
11008
- } else {
11009
- resolve24([]);
11010
- }
11011
- }
11012
- }
11013
- } catch (e2) {
11014
- reject(e2);
11015
- }
11016
- });
11017
- } catch (e) {
11018
- reject(e);
11019
- }
11020
- });
11021
- }
11022
- };
11023
- }
11024
-
11025
11269
  // node_modules/@miqro/query/build/executors/sqlite-native/lib.js
11026
- var SQLITE_CONFIG_SCHEMA3 = {
11270
+ var SQLITE_CONFIG_SCHEMA2 = {
11027
11271
  type: "object",
11028
11272
  mode: "remove_extra",
11029
11273
  properties: {
@@ -11031,7 +11275,7 @@ var SQLITE_CONFIG_SCHEMA3 = {
11031
11275
  }
11032
11276
  };
11033
11277
  async function nativeSqlite(config) {
11034
- const databaseOptions = parser2.parse(config, SQLITE_CONFIG_SCHEMA3);
11278
+ const databaseOptions = parser2.parse(config, SQLITE_CONFIG_SCHEMA2);
11035
11279
  if (!databaseOptions) {
11036
11280
  throw new Error("config not valid");
11037
11281
  }
@@ -11040,6 +11284,8 @@ async function nativeSqlite(config) {
11040
11284
  return {
11041
11285
  // we just use the sqlite3Executor prepare function
11042
11286
  prepare: sqlite3ExecutorPrepare,
11287
+ transformInput: sqliteTransformInput,
11288
+ transformOutput: sqliteTransformOutput,
11043
11289
  disconnect: async function sqlite3ExecutorDisconnect() {
11044
11290
  return driver.close();
11045
11291
  },
@@ -11062,13 +11308,15 @@ async function nativeSqlite(config) {
11062
11308
  }
11063
11309
  const stmt = driver.prepare(sql);
11064
11310
  stmt.setReadBigInts(true);
11065
- if (values && values.length > 0) {
11066
- const ret = stmt.all(...values);
11067
- resolve24(ret);
11068
- } else {
11069
- const ret = stmt.all();
11070
- resolve24(ret);
11071
- }
11311
+ const ret = values && values.length > 0 ? stmt.all(...values) : stmt.all();
11312
+ resolve24(ret.map((row) => {
11313
+ const out = {};
11314
+ for (const key of Object.keys(row)) {
11315
+ const v = row[key];
11316
+ out[key] = typeof v === "bigint" && v >= Number.MIN_SAFE_INTEGER && v <= Number.MAX_SAFE_INTEGER ? Number(v) : typeof v === "number" ? Number(v) : v;
11317
+ }
11318
+ return out;
11319
+ }));
11072
11320
  } catch (e) {
11073
11321
  reject(e);
11074
11322
  }
@@ -11159,20 +11407,20 @@ var Database = class {
11159
11407
  alterTable(table, inTransaction) {
11160
11408
  return new AlterTable(this, table, inTransaction);
11161
11409
  }
11162
- insert(table) {
11163
- return new Insert(this, table);
11410
+ insert(table, schema) {
11411
+ return new Insert(this, table, schema);
11164
11412
  }
11165
- select() {
11166
- return new Select(this);
11413
+ select(schema, associations) {
11414
+ return new Select(this, schema, associations);
11167
11415
  }
11168
11416
  count() {
11169
11417
  return new Count(this);
11170
11418
  }
11171
- update(table) {
11172
- return new Update(this, table);
11419
+ update(table, schema) {
11420
+ return new Update(this, table, schema);
11173
11421
  }
11174
- delete(table) {
11175
- return new Delete(this, table);
11422
+ delete(table, schema) {
11423
+ return new Delete(this, table, schema);
11176
11424
  }
11177
11425
  where() {
11178
11426
  return new Where();
@@ -11182,14 +11430,17 @@ async function getExecutor(config) {
11182
11430
  switch (config.dialect) {
11183
11431
  case "node:sqlite":
11184
11432
  return await nativeSqlite(config);
11185
- case "sqlite3-cli":
11186
- return await sqlite3CLIExecutor(config);
11187
11433
  case "pg":
11188
11434
  return await postgresExecutor(config);
11189
11435
  case "sqlite3":
11190
11436
  return await sqlite3Executor(config);
11191
11437
  default:
11192
11438
  if (config.executor) {
11439
+ const e = config.executor;
11440
+ if (!e.transformInput)
11441
+ e.transformInput = (v) => v;
11442
+ if (!e.transformOutput)
11443
+ e.transformOutput = (_type, v) => v;
11193
11444
  return config.executor;
11194
11445
  }
11195
11446
  throw new Error("dialect [" + config.dialect + "] not defined");
@@ -11380,7 +11631,7 @@ var ClusterWebSocketServer2 = class extends WebSocketServer {
11380
11631
  clientUUID: req.uuid
11381
11632
  });
11382
11633
  }
11383
- this.logger?.log("[%s] new web socket connection from (%s)", req.uuid, req.req.socket.remoteAddress);
11634
+ this.logger?.debug("[%s] new web socket connection from (%s)", req.uuid, req.req.socket.remoteAddress);
11384
11635
  if (options.onConnection) {
11385
11636
  options.onConnection(req);
11386
11637
  }
@@ -11395,7 +11646,7 @@ var ClusterWebSocketServer2 = class extends WebSocketServer {
11395
11646
  clientUUID: req.uuid
11396
11647
  });
11397
11648
  }
11398
- this.logger?.log("[%s] [%s] web socket disconnection from (%s)", req.uuid, this.path, req.req.socket.remoteAddress);
11649
+ this.logger?.debug("[%s] [%s] web socket disconnection from (%s)", req.uuid, this.path, req.req.socket.remoteAddress);
11399
11650
  if (options.onDisconnect) {
11400
11651
  options.onDisconnect(req);
11401
11652
  }
@@ -11457,6 +11708,9 @@ var ClusterWebSocketServer2 = class extends WebSocketServer {
11457
11708
  };
11458
11709
  this.connect();
11459
11710
  }
11711
+ name;
11712
+ path;
11713
+ logger;
11460
11714
  remoteClients = /* @__PURE__ */ new Set();
11461
11715
  listener;
11462
11716
  connect() {
@@ -11519,9 +11773,26 @@ var ClusterCache = class {
11519
11773
  this.listener = async (data) => {
11520
11774
  try {
11521
11775
  const msg = data;
11522
- if (msg && msg.key && msg.action && msg.type === ClusterCacheType && msg.fromPID !== process.pid, (msg.action === "set_add" || msg.action === "set" || msg.action === "unset" || msg.action === "set_delete" || msg.action === "array_push") && msg.target === this.name) {
11776
+ if (msg && msg.key && msg.action && msg.type === ClusterCacheType && msg.fromPID !== process.pid && (msg.action === "set_clear" || msg.action === "array_clear" || msg.action === "set_add" || msg.action === "set" || msg.action === "unset" || msg.action === "set_delete" || msg.action === "array_push") && msg.target === this.name) {
11523
11777
  this.logger?.debug("remote cluster cache message from [%s] [%s] [%s] [%s]", msg.fromPID, msg.target, msg.action, msg.key);
11524
11778
  switch (msg.action) {
11779
+ case "set_clear": {
11780
+ const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : /* @__PURE__ */ new Set();
11781
+ if (!(list instanceof Set)) {
11782
+ throw new Error("cannot apply clear on non set");
11783
+ }
11784
+ list.clear();
11785
+ this.localCache.set(msg.key, list);
11786
+ break;
11787
+ }
11788
+ case "array_clear": {
11789
+ const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : [];
11790
+ if (!(list instanceof Array)) {
11791
+ throw new Error("cannot apply clear on non array");
11792
+ }
11793
+ this.localCache.set(msg.key, []);
11794
+ break;
11795
+ }
11525
11796
  case "unset":
11526
11797
  this.localCache.delete(msg.key);
11527
11798
  break;
@@ -11531,7 +11802,7 @@ var ClusterCache = class {
11531
11802
  case "set_add": {
11532
11803
  const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : /* @__PURE__ */ new Set();
11533
11804
  if (!(list instanceof Set)) {
11534
- throw new Error("cannot apply push on non array");
11805
+ throw new Error("cannot apply add on non set");
11535
11806
  }
11536
11807
  if (!list.has(msg.value)) {
11537
11808
  list.add(msg.value);
@@ -11542,7 +11813,7 @@ var ClusterCache = class {
11542
11813
  case "set_delete": {
11543
11814
  const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : /* @__PURE__ */ new Set();
11544
11815
  if (!(list instanceof Set)) {
11545
- throw new Error("cannot apply push on non array");
11816
+ throw new Error("cannot apply delete on non set");
11546
11817
  }
11547
11818
  if (list.has(msg.value)) {
11548
11819
  list.delete(msg.value);
@@ -11567,6 +11838,8 @@ var ClusterCache = class {
11567
11838
  };
11568
11839
  this.connect();
11569
11840
  }
11841
+ name;
11842
+ logger;
11570
11843
  localCache = /* @__PURE__ */ new Map();
11571
11844
  //private logger: Logger;
11572
11845
  listener;
@@ -11586,33 +11859,25 @@ var ClusterCache = class {
11586
11859
  set(key, value) {
11587
11860
  this.localCache.set(key, value);
11588
11861
  this.logger?.trace("set(%s, ...)", key);
11589
- if (process.send) {
11590
- setTimeout(() => {
11591
- process.send({
11592
- type: ClusterCacheType,
11593
- action: "set",
11594
- target: this.name,
11595
- fromPID: process.pid,
11596
- key,
11597
- value
11598
- });
11599
- }, 10);
11600
- }
11862
+ sendTimeout({
11863
+ type: ClusterCacheType,
11864
+ action: "set",
11865
+ target: this.name,
11866
+ fromPID: process.pid,
11867
+ key,
11868
+ value
11869
+ });
11601
11870
  }
11602
11871
  unset(key) {
11603
11872
  this.logger?.trace("unset(%s)", key);
11604
11873
  this.localCache.delete(key);
11605
- if (process.send) {
11606
- setTimeout(() => {
11607
- process.send({
11608
- type: ClusterCacheType,
11609
- target: this.name,
11610
- action: "unset",
11611
- fromPID: process.pid,
11612
- key
11613
- });
11614
- }, 10);
11615
- }
11874
+ sendTimeout({
11875
+ type: ClusterCacheType,
11876
+ target: this.name,
11877
+ action: "unset",
11878
+ fromPID: process.pid,
11879
+ key
11880
+ });
11616
11881
  }
11617
11882
  has(key) {
11618
11883
  this.logger?.trace("has(%s)", key);
@@ -11628,18 +11893,14 @@ var ClusterCache = class {
11628
11893
  list.add(value);
11629
11894
  }
11630
11895
  this.localCache.set(key, list);
11631
- if (process.send) {
11632
- setTimeout(() => {
11633
- process.send({
11634
- type: ClusterCacheType,
11635
- target: this.name,
11636
- action: "set_add",
11637
- fromPID: process.pid,
11638
- key,
11639
- value
11640
- });
11641
- }, 10);
11642
- }
11896
+ sendTimeout({
11897
+ type: ClusterCacheType,
11898
+ target: this.name,
11899
+ action: "set_add",
11900
+ fromPID: process.pid,
11901
+ key,
11902
+ value
11903
+ });
11643
11904
  }
11644
11905
  set_delete(key, value) {
11645
11906
  this.logger?.trace("delete(%s)", key);
@@ -11651,18 +11912,14 @@ var ClusterCache = class {
11651
11912
  list.delete(value);
11652
11913
  }
11653
11914
  this.localCache.set(key, list);
11654
- if (process.send) {
11655
- setTimeout(() => {
11656
- process.send({
11657
- type: ClusterCacheType,
11658
- target: this.name,
11659
- action: "set_delete",
11660
- fromPID: process.pid,
11661
- key,
11662
- value
11663
- });
11664
- }, 10);
11665
- }
11915
+ sendTimeout({
11916
+ type: ClusterCacheType,
11917
+ target: this.name,
11918
+ action: "set_delete",
11919
+ fromPID: process.pid,
11920
+ key,
11921
+ value
11922
+ });
11666
11923
  }
11667
11924
  set_has(key, value) {
11668
11925
  this.logger?.trace("set_has(%s)", key);
@@ -11682,6 +11939,13 @@ var ClusterCache = class {
11682
11939
  }
11683
11940
  list.clear();
11684
11941
  this.localCache.set(key, list);
11942
+ sendTimeout({
11943
+ type: ClusterCacheType,
11944
+ target: this.name,
11945
+ action: "set_clear",
11946
+ fromPID: process.pid,
11947
+ key
11948
+ });
11685
11949
  }
11686
11950
  array_push(key, value) {
11687
11951
  this.logger?.trace("array_push(%s)", key);
@@ -11691,18 +11955,14 @@ var ClusterCache = class {
11691
11955
  }
11692
11956
  list.push(value);
11693
11957
  this.localCache.set(key, list);
11694
- if (process.send) {
11695
- setTimeout(() => {
11696
- process.send({
11697
- type: ClusterCacheType,
11698
- target: this.name,
11699
- action: "array_push",
11700
- fromPID: process.pid,
11701
- key,
11702
- value
11703
- });
11704
- }, 10);
11705
- }
11958
+ sendTimeout({
11959
+ type: ClusterCacheType,
11960
+ target: this.name,
11961
+ action: "array_push",
11962
+ fromPID: process.pid,
11963
+ key,
11964
+ value
11965
+ });
11706
11966
  }
11707
11967
  array_clear(key) {
11708
11968
  this.logger?.trace("array_clear(%s)", key);
@@ -11710,8 +11970,28 @@ var ClusterCache = class {
11710
11970
  throw new Error("cannot apply on non Array");
11711
11971
  }
11712
11972
  this.localCache.set(key, []);
11973
+ sendTimeout({
11974
+ type: ClusterCacheType,
11975
+ target: this.name,
11976
+ action: "array_clear",
11977
+ fromPID: process.pid,
11978
+ key
11979
+ });
11713
11980
  }
11714
11981
  };
11982
+ function sendTimeout(msg) {
11983
+ if (process.send) {
11984
+ setTimeout(() => {
11985
+ try {
11986
+ if (process.send) {
11987
+ process.send(msg);
11988
+ }
11989
+ } catch (e) {
11990
+ console.error(e);
11991
+ }
11992
+ }, 10);
11993
+ }
11994
+ }
11715
11995
 
11716
11996
  // src/services/utils/cache.ts
11717
11997
  var LocalCache = class {
@@ -11719,6 +11999,8 @@ var LocalCache = class {
11719
11999
  this.name = name;
11720
12000
  this.logger = logger;
11721
12001
  }
12002
+ name;
12003
+ logger;
11722
12004
  localCache = /* @__PURE__ */ new Map();
11723
12005
  dispose() {
11724
12006
  }
@@ -11815,7 +12097,8 @@ var WebSocketManager = class {
11815
12097
  deleteWS(path) {
11816
12098
  const ws = this.runningGlobalWSMap.get(path);
11817
12099
  this.disconnectAllFrom(path);
11818
- ws.dispose();
12100
+ if (ws)
12101
+ ws.dispose();
11819
12102
  this.runningGlobalWSMap.delete(path);
11820
12103
  }
11821
12104
  deleteAllWS() {
@@ -13229,7 +13512,7 @@ async function runMigrations(db) {
13229
13512
  await migration.init(db);
13230
13513
  ${serviceMigrations.map((file) => {
13231
13514
  const name = `${file.substring(0, file.length - (0, import_node_path14.extname)(file).length)}`;
13232
- return ` await migration.up.module(db, "${file}", (await require("../${(0, import_node_path14.relative)(service, "")}/${service}/migration/${name}.cjs")).default)`;
13515
+ return ` await migration.up.module(db, (await require("../${(0, import_node_path14.relative)(service, "")}/${service}/migration/${name}.cjs")).default.name ?? "${file}", (await require("../${(0, import_node_path14.relative)(service, "")}/${service}/migration/${name}.cjs")).default)`;
13233
13516
  }).join("\n")}
13234
13517
  }
13235
13518
  module.exports = {
@@ -13241,7 +13524,7 @@ async function runMigrations(db) {
13241
13524
  await migration.init(db);
13242
13525
  ${serviceMigrations.reverse().map((file) => {
13243
13526
  const name = `${file.substring(0, file.length - (0, import_node_path14.extname)(file).length)}`;
13244
- return ` await migration.down.module(db, "${file}", (await require("../${(0, import_node_path14.relative)(service, "")}/${service}/migration/${name}.cjs")).default)`;
13527
+ return ` await migration.down.module(db, (await require("../${(0, import_node_path14.relative)(service, "")}/${service}/migration/${name}.cjs")).default.name ?? "${file}", (await require("../${(0, import_node_path14.relative)(service, "")}/${service}/migration/${name}.cjs")).default)`;
13245
13528
  }).join("\n")}
13246
13529
  }
13247
13530
  module.exports = {
@@ -13735,17 +14018,18 @@ var ws_default = {
13735
14018
  const cache2 = admin ? admin.getCache() : req.server.cache;
13736
14019
  const KEY = cache2.get("AUTH_KEY");
13737
14020
  const cookieToken = req.cookies["auth"];
13738
- return cookieToken === KEY ? true : false;
14021
+ return cookieToken && KEY && cookieToken === KEY ? true : false;
13739
14022
  }
13740
14023
  };
13741
14024
 
13742
14025
  // editor/server.ts
13743
- var import_node_crypto4 = require("node:crypto");
14026
+ var import_node_crypto5 = require("node:crypto");
13744
14027
  init_constants();
13745
14028
  var import_node_fs17 = require("node:fs");
13746
14029
  var import_node_path18 = require("node:path");
13747
14030
 
13748
14031
  // editor/auth.ts
14032
+ var import_node_crypto4 = require("node:crypto");
13749
14033
  var ADMIN_EDITOR_AUTH_KEY = "$$ADMIN_EDITOR_AUTH_KEY$$";
13750
14034
  var ADMIN_EDITOR_AUTH_QUERY = "key";
13751
14035
  var ADMIN_EDITOR_AUTH_COOKIE = ADMIN_EDITOR_AUTH_KEY;
@@ -13764,7 +14048,7 @@ var auth_default = {
13764
14048
  const queryToken = args.req.query[ADMIN_EDITOR_AUTH_QUERY];
13765
14049
  const cookieToken = args.req.cookies[ADMIN_EDITOR_AUTH_COOKIE];
13766
14050
  if (queryToken) {
13767
- if (queryToken === KEY) {
14051
+ if (typeof queryToken === "string" && (0, import_node_crypto4.timingSafeEqual)(Buffer.from(queryToken), Buffer.from(KEY))) {
13768
14052
  args.res.setCookie(ADMIN_EDITOR_AUTH_COOKIE, KEY, {
13769
14053
  expires: new Date(Date.now() + 1e3 * 60 * 60 * 24 * 31 * 12 * 500),
13770
14054
  httpOnly: true,
@@ -13798,7 +14082,7 @@ var server_default = {
13798
14082
  serverInterface.logger.warn("loading static ADMIN_KEY from [%s]", (0, import_node_path18.relative)(process.cwd(), adminKEYPath));
13799
14083
  cache2.set(ADMIN_EDITOR_AUTH_KEY, (0, import_node_fs17.readFileSync)(adminKEYPath).toString().trim());
13800
14084
  } else {
13801
- cache2.set(ADMIN_EDITOR_AUTH_KEY, (0, import_node_crypto4.randomUUID)());
14085
+ cache2.set(ADMIN_EDITOR_AUTH_KEY, (0, import_node_crypto5.randomUUID)());
13802
14086
  }
13803
14087
  }
13804
14088
  }
@@ -14174,6 +14458,17 @@ function uint32be(value) {
14174
14458
  writeUInt32BE(buf, value);
14175
14459
  return buf;
14176
14460
  }
14461
+ function encode(string) {
14462
+ const bytes = new Uint8Array(string.length);
14463
+ for (let i = 0; i < string.length; i++) {
14464
+ const code = string.charCodeAt(i);
14465
+ if (code > 127) {
14466
+ throw new TypeError("non-ASCII string encountered in encode()");
14467
+ }
14468
+ bytes[i] = code;
14469
+ }
14470
+ return bytes;
14471
+ }
14177
14472
 
14178
14473
  // node_modules/jose/dist/webapi/lib/base64.js
14179
14474
  function encodeBase64(input) {
@@ -14210,14 +14505,14 @@ function decode(input) {
14210
14505
  if (encoded instanceof Uint8Array) {
14211
14506
  encoded = decoder.decode(encoded);
14212
14507
  }
14213
- encoded = encoded.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
14508
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
14214
14509
  try {
14215
14510
  return decodeBase64(encoded);
14216
14511
  } catch {
14217
14512
  throw new TypeError("The input to be decoded is not correctly encoded.");
14218
14513
  }
14219
14514
  }
14220
- function encode(input) {
14515
+ function encode2(input) {
14221
14516
  let unencoded = input;
14222
14517
  if (typeof unencoded === "string") {
14223
14518
  unencoded = encoder.encode(unencoded);
@@ -14228,122 +14523,17 @@ function encode(input) {
14228
14523
  return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
14229
14524
  }
14230
14525
 
14231
- // node_modules/jose/dist/webapi/util/errors.js
14232
- var JOSEError = class extends Error {
14233
- static code = "ERR_JOSE_GENERIC";
14234
- code = "ERR_JOSE_GENERIC";
14235
- constructor(message2, options) {
14236
- super(message2, options);
14237
- this.name = this.constructor.name;
14238
- Error.captureStackTrace?.(this, this.constructor);
14239
- }
14240
- };
14241
- var JWTClaimValidationFailed = class extends JOSEError {
14242
- static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
14243
- code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
14244
- claim;
14245
- reason;
14246
- payload;
14247
- constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
14248
- super(message2, { cause: { claim, reason, payload } });
14249
- this.claim = claim;
14250
- this.reason = reason;
14251
- this.payload = payload;
14252
- }
14253
- };
14254
- var JWTExpired = class extends JOSEError {
14255
- static code = "ERR_JWT_EXPIRED";
14256
- code = "ERR_JWT_EXPIRED";
14257
- claim;
14258
- reason;
14259
- payload;
14260
- constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
14261
- super(message2, { cause: { claim, reason, payload } });
14262
- this.claim = claim;
14263
- this.reason = reason;
14264
- this.payload = payload;
14265
- }
14266
- };
14267
- var JOSEAlgNotAllowed = class extends JOSEError {
14268
- static code = "ERR_JOSE_ALG_NOT_ALLOWED";
14269
- code = "ERR_JOSE_ALG_NOT_ALLOWED";
14270
- };
14271
- var JOSENotSupported = class extends JOSEError {
14272
- static code = "ERR_JOSE_NOT_SUPPORTED";
14273
- code = "ERR_JOSE_NOT_SUPPORTED";
14274
- };
14275
- var JWEDecryptionFailed = class extends JOSEError {
14276
- static code = "ERR_JWE_DECRYPTION_FAILED";
14277
- code = "ERR_JWE_DECRYPTION_FAILED";
14278
- constructor(message2 = "decryption operation failed", options) {
14279
- super(message2, options);
14280
- }
14281
- };
14282
- var JWEInvalid = class extends JOSEError {
14283
- static code = "ERR_JWE_INVALID";
14284
- code = "ERR_JWE_INVALID";
14285
- };
14286
- var JWSInvalid = class extends JOSEError {
14287
- static code = "ERR_JWS_INVALID";
14288
- code = "ERR_JWS_INVALID";
14289
- };
14290
- var JWTInvalid = class extends JOSEError {
14291
- static code = "ERR_JWT_INVALID";
14292
- code = "ERR_JWT_INVALID";
14293
- };
14294
- var JWSSignatureVerificationFailed = class extends JOSEError {
14295
- static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
14296
- code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
14297
- constructor(message2 = "signature verification failed", options) {
14298
- super(message2, options);
14299
- }
14300
- };
14301
-
14302
- // node_modules/jose/dist/webapi/lib/iv.js
14303
- function bitLength(alg) {
14304
- switch (alg) {
14305
- case "A128GCM":
14306
- case "A128GCMKW":
14307
- case "A192GCM":
14308
- case "A192GCMKW":
14309
- case "A256GCM":
14310
- case "A256GCMKW":
14311
- return 96;
14312
- case "A128CBC-HS256":
14313
- case "A192CBC-HS384":
14314
- case "A256CBC-HS512":
14315
- return 128;
14316
- default:
14317
- throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
14318
- }
14319
- }
14320
- var iv_default = (alg) => crypto.getRandomValues(new Uint8Array(bitLength(alg) >> 3));
14321
-
14322
- // node_modules/jose/dist/webapi/lib/check_iv_length.js
14323
- var check_iv_length_default = (enc, iv) => {
14324
- if (iv.length << 3 !== bitLength(enc)) {
14325
- throw new JWEInvalid("Invalid Initialization Vector length");
14326
- }
14327
- };
14328
-
14329
- // node_modules/jose/dist/webapi/lib/check_cek_length.js
14330
- var check_cek_length_default = (cek, expected) => {
14331
- const actual = cek.byteLength << 3;
14332
- if (actual !== expected) {
14333
- throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
14334
- }
14335
- };
14336
-
14337
14526
  // node_modules/jose/dist/webapi/lib/crypto_key.js
14338
- function unusable(name, prop = "algorithm.name") {
14339
- return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
14340
- }
14341
- function isAlgorithm(algorithm, name) {
14342
- return algorithm.name === name;
14343
- }
14527
+ var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
14528
+ var isAlgorithm = (algorithm, name) => algorithm.name === name;
14344
14529
  function getHashLength(hash) {
14345
14530
  return parseInt(hash.name.slice(4), 10);
14346
14531
  }
14532
+ function checkHashLength(algorithm, expected) {
14533
+ const actual = getHashLength(algorithm.hash);
14534
+ if (actual !== expected)
14535
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
14536
+ }
14347
14537
  function getNamedCurve(alg) {
14348
14538
  switch (alg) {
14349
14539
  case "ES256":
@@ -14368,10 +14558,7 @@ function checkSigCryptoKey(key, alg, usage2) {
14368
14558
  case "HS512": {
14369
14559
  if (!isAlgorithm(key.algorithm, "HMAC"))
14370
14560
  throw unusable("HMAC");
14371
- const expected = parseInt(alg.slice(2), 10);
14372
- const actual = getHashLength(key.algorithm.hash);
14373
- if (actual !== expected)
14374
- throw unusable(`SHA-${expected}`, "algorithm.hash");
14561
+ checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
14375
14562
  break;
14376
14563
  }
14377
14564
  case "RS256":
@@ -14379,10 +14566,7 @@ function checkSigCryptoKey(key, alg, usage2) {
14379
14566
  case "RS512": {
14380
14567
  if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
14381
14568
  throw unusable("RSASSA-PKCS1-v1_5");
14382
- const expected = parseInt(alg.slice(2), 10);
14383
- const actual = getHashLength(key.algorithm.hash);
14384
- if (actual !== expected)
14385
- throw unusable(`SHA-${expected}`, "algorithm.hash");
14569
+ checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
14386
14570
  break;
14387
14571
  }
14388
14572
  case "PS256":
@@ -14390,10 +14574,7 @@ function checkSigCryptoKey(key, alg, usage2) {
14390
14574
  case "PS512": {
14391
14575
  if (!isAlgorithm(key.algorithm, "RSA-PSS"))
14392
14576
  throw unusable("RSA-PSS");
14393
- const expected = parseInt(alg.slice(2), 10);
14394
- const actual = getHashLength(key.algorithm.hash);
14395
- if (actual !== expected)
14396
- throw unusable(`SHA-${expected}`, "algorithm.hash");
14577
+ checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
14397
14578
  break;
14398
14579
  }
14399
14580
  case "Ed25519":
@@ -14471,10 +14652,7 @@ function checkEncCryptoKey(key, alg, usage2) {
14471
14652
  case "RSA-OAEP-512": {
14472
14653
  if (!isAlgorithm(key.algorithm, "RSA-OAEP"))
14473
14654
  throw unusable("RSA-OAEP");
14474
- const expected = parseInt(alg.slice(9), 10) || 1;
14475
- const actual = getHashLength(key.algorithm.hash);
14476
- if (actual !== expected)
14477
- throw unusable(`SHA-${expected}`, "algorithm.hash");
14655
+ checkHashLength(key.algorithm, parseInt(alg.slice(9), 10) || 1);
14478
14656
  break;
14479
14657
  }
14480
14658
  default:
@@ -14505,12 +14683,79 @@ function message(msg, actual, ...types) {
14505
14683
  }
14506
14684
  return msg;
14507
14685
  }
14508
- var invalid_key_input_default = (actual, ...types) => {
14509
- return message("Key must be ", actual, ...types);
14686
+ var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
14687
+ var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
14688
+
14689
+ // node_modules/jose/dist/webapi/util/errors.js
14690
+ var JOSEError = class extends Error {
14691
+ static code = "ERR_JOSE_GENERIC";
14692
+ code = "ERR_JOSE_GENERIC";
14693
+ constructor(message2, options) {
14694
+ super(message2, options);
14695
+ this.name = this.constructor.name;
14696
+ Error.captureStackTrace?.(this, this.constructor);
14697
+ }
14698
+ };
14699
+ var JWTClaimValidationFailed = class extends JOSEError {
14700
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
14701
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
14702
+ claim;
14703
+ reason;
14704
+ payload;
14705
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
14706
+ super(message2, { cause: { claim, reason, payload } });
14707
+ this.claim = claim;
14708
+ this.reason = reason;
14709
+ this.payload = payload;
14710
+ }
14711
+ };
14712
+ var JWTExpired = class extends JOSEError {
14713
+ static code = "ERR_JWT_EXPIRED";
14714
+ code = "ERR_JWT_EXPIRED";
14715
+ claim;
14716
+ reason;
14717
+ payload;
14718
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
14719
+ super(message2, { cause: { claim, reason, payload } });
14720
+ this.claim = claim;
14721
+ this.reason = reason;
14722
+ this.payload = payload;
14723
+ }
14724
+ };
14725
+ var JOSEAlgNotAllowed = class extends JOSEError {
14726
+ static code = "ERR_JOSE_ALG_NOT_ALLOWED";
14727
+ code = "ERR_JOSE_ALG_NOT_ALLOWED";
14728
+ };
14729
+ var JOSENotSupported = class extends JOSEError {
14730
+ static code = "ERR_JOSE_NOT_SUPPORTED";
14731
+ code = "ERR_JOSE_NOT_SUPPORTED";
14732
+ };
14733
+ var JWEDecryptionFailed = class extends JOSEError {
14734
+ static code = "ERR_JWE_DECRYPTION_FAILED";
14735
+ code = "ERR_JWE_DECRYPTION_FAILED";
14736
+ constructor(message2 = "decryption operation failed", options) {
14737
+ super(message2, options);
14738
+ }
14739
+ };
14740
+ var JWEInvalid = class extends JOSEError {
14741
+ static code = "ERR_JWE_INVALID";
14742
+ code = "ERR_JWE_INVALID";
14743
+ };
14744
+ var JWSInvalid = class extends JOSEError {
14745
+ static code = "ERR_JWS_INVALID";
14746
+ code = "ERR_JWS_INVALID";
14747
+ };
14748
+ var JWTInvalid = class extends JOSEError {
14749
+ static code = "ERR_JWT_INVALID";
14750
+ code = "ERR_JWT_INVALID";
14751
+ };
14752
+ var JWSSignatureVerificationFailed = class extends JOSEError {
14753
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
14754
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
14755
+ constructor(message2 = "signature verification failed", options) {
14756
+ super(message2, options);
14757
+ }
14510
14758
  };
14511
- function withAlg(alg, actual, ...types) {
14512
- return message(`Key for the ${alg} algorithm must be `, actual, ...types);
14513
- }
14514
14759
 
14515
14760
  // node_modules/jose/dist/webapi/lib/is_key_like.js
14516
14761
  function assertCryptoKey(key) {
@@ -14518,18 +14763,92 @@ function assertCryptoKey(key) {
14518
14763
  throw new Error("CryptoKey instance expected");
14519
14764
  }
14520
14765
  }
14521
- function isCryptoKey(key) {
14522
- return key?.[Symbol.toStringTag] === "CryptoKey";
14523
- }
14524
- function isKeyObject(key) {
14525
- return key?.[Symbol.toStringTag] === "KeyObject";
14526
- }
14527
- var is_key_like_default = (key) => {
14528
- return isCryptoKey(key) || isKeyObject(key);
14766
+ var isCryptoKey = (key) => {
14767
+ if (key?.[Symbol.toStringTag] === "CryptoKey")
14768
+ return true;
14769
+ try {
14770
+ return key instanceof CryptoKey;
14771
+ } catch {
14772
+ return false;
14773
+ }
14529
14774
  };
14775
+ var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
14776
+ var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
14530
14777
 
14531
- // node_modules/jose/dist/webapi/lib/decrypt.js
14532
- async function timingSafeEqual(a, b) {
14778
+ // node_modules/jose/dist/webapi/lib/content_encryption.js
14779
+ function cekLength(alg) {
14780
+ switch (alg) {
14781
+ case "A128GCM":
14782
+ return 128;
14783
+ case "A192GCM":
14784
+ return 192;
14785
+ case "A256GCM":
14786
+ case "A128CBC-HS256":
14787
+ return 256;
14788
+ case "A192CBC-HS384":
14789
+ return 384;
14790
+ case "A256CBC-HS512":
14791
+ return 512;
14792
+ default:
14793
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
14794
+ }
14795
+ }
14796
+ var generateCek = (alg) => crypto.getRandomValues(new Uint8Array(cekLength(alg) >> 3));
14797
+ function checkCekLength(cek, expected) {
14798
+ const actual = cek.byteLength << 3;
14799
+ if (actual !== expected) {
14800
+ throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
14801
+ }
14802
+ }
14803
+ function ivBitLength(alg) {
14804
+ switch (alg) {
14805
+ case "A128GCM":
14806
+ case "A128GCMKW":
14807
+ case "A192GCM":
14808
+ case "A192GCMKW":
14809
+ case "A256GCM":
14810
+ case "A256GCMKW":
14811
+ return 96;
14812
+ case "A128CBC-HS256":
14813
+ case "A192CBC-HS384":
14814
+ case "A256CBC-HS512":
14815
+ return 128;
14816
+ default:
14817
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
14818
+ }
14819
+ }
14820
+ var generateIv = (alg) => crypto.getRandomValues(new Uint8Array(ivBitLength(alg) >> 3));
14821
+ function checkIvLength(enc, iv) {
14822
+ if (iv.length << 3 !== ivBitLength(enc)) {
14823
+ throw new JWEInvalid("Invalid Initialization Vector length");
14824
+ }
14825
+ }
14826
+ async function cbcKeySetup(enc, cek, usage2) {
14827
+ if (!(cek instanceof Uint8Array)) {
14828
+ throw new TypeError(invalidKeyInput(cek, "Uint8Array"));
14829
+ }
14830
+ const keySize = parseInt(enc.slice(1, 4), 10);
14831
+ const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, [usage2]);
14832
+ const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
14833
+ hash: `SHA-${keySize << 1}`,
14834
+ name: "HMAC"
14835
+ }, false, ["sign"]);
14836
+ return { encKey, macKey, keySize };
14837
+ }
14838
+ async function cbcHmacTag(macKey, macData, keySize) {
14839
+ return new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
14840
+ }
14841
+ async function cbcEncrypt(enc, plaintext, cek, iv, aad) {
14842
+ const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, "encrypt");
14843
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
14844
+ iv,
14845
+ name: "AES-CBC"
14846
+ }, encKey, plaintext));
14847
+ const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
14848
+ const tag2 = await cbcHmacTag(macKey, macData, keySize);
14849
+ return { ciphertext, tag: tag2, iv };
14850
+ }
14851
+ async function timingSafeEqual2(a, b) {
14533
14852
  if (!(a instanceof Uint8Array)) {
14534
14853
  throw new TypeError("First argument must be a buffer");
14535
14854
  }
@@ -14548,20 +14867,12 @@ async function timingSafeEqual(a, b) {
14548
14867
  return out === 0;
14549
14868
  }
14550
14869
  async function cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad) {
14551
- if (!(cek instanceof Uint8Array)) {
14552
- throw new TypeError(invalid_key_input_default(cek, "Uint8Array"));
14553
- }
14554
- const keySize = parseInt(enc.slice(1, 4), 10);
14555
- const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["decrypt"]);
14556
- const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
14557
- hash: `SHA-${keySize << 1}`,
14558
- name: "HMAC"
14559
- }, false, ["sign"]);
14870
+ const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, "decrypt");
14560
14871
  const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
14561
- const expectedTag = new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
14872
+ const expectedTag = await cbcHmacTag(macKey, macData, keySize);
14562
14873
  let macCheckPassed;
14563
14874
  try {
14564
- macCheckPassed = await timingSafeEqual(tag2, expectedTag);
14875
+ macCheckPassed = await timingSafeEqual2(tag2, expectedTag);
14565
14876
  } catch {
14566
14877
  }
14567
14878
  if (!macCheckPassed) {
@@ -14577,6 +14888,24 @@ async function cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad) {
14577
14888
  }
14578
14889
  return plaintext;
14579
14890
  }
14891
+ async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
14892
+ let encKey;
14893
+ if (cek instanceof Uint8Array) {
14894
+ encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]);
14895
+ } else {
14896
+ checkEncCryptoKey(cek, enc, "encrypt");
14897
+ encKey = cek;
14898
+ }
14899
+ const encrypted = new Uint8Array(await crypto.subtle.encrypt({
14900
+ additionalData: aad,
14901
+ iv,
14902
+ name: "AES-GCM",
14903
+ tagLength: 128
14904
+ }, encKey, plaintext));
14905
+ const tag2 = encrypted.slice(-16);
14906
+ const ciphertext = encrypted.slice(0, -16);
14907
+ return { ciphertext, tag: tag2, iv };
14908
+ }
14580
14909
  async function gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad) {
14581
14910
  let encKey;
14582
14911
  if (cek instanceof Uint8Array) {
@@ -14596,37 +14925,99 @@ async function gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad) {
14596
14925
  throw new JWEDecryptionFailed();
14597
14926
  }
14598
14927
  }
14599
- var decrypt_default = async (enc, cek, ciphertext, iv, tag2, aad) => {
14928
+ var unsupportedEnc = "Unsupported JWE Content Encryption Algorithm";
14929
+ async function encrypt(enc, plaintext, cek, iv, aad) {
14600
14930
  if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
14601
- throw new TypeError(invalid_key_input_default(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
14602
- }
14603
- if (!iv) {
14604
- throw new JWEInvalid("JWE Initialization Vector missing");
14931
+ throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
14605
14932
  }
14606
- if (!tag2) {
14607
- throw new JWEInvalid("JWE Authentication Tag missing");
14933
+ if (iv) {
14934
+ checkIvLength(enc, iv);
14935
+ } else {
14936
+ iv = generateIv(enc);
14608
14937
  }
14609
- check_iv_length_default(enc, iv);
14610
14938
  switch (enc) {
14611
14939
  case "A128CBC-HS256":
14612
14940
  case "A192CBC-HS384":
14613
14941
  case "A256CBC-HS512":
14614
- if (cek instanceof Uint8Array)
14615
- check_cek_length_default(cek, parseInt(enc.slice(-3), 10));
14616
- return cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad);
14942
+ if (cek instanceof Uint8Array) {
14943
+ checkCekLength(cek, parseInt(enc.slice(-3), 10));
14944
+ }
14945
+ return cbcEncrypt(enc, plaintext, cek, iv, aad);
14946
+ case "A128GCM":
14947
+ case "A192GCM":
14948
+ case "A256GCM":
14949
+ if (cek instanceof Uint8Array) {
14950
+ checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
14951
+ }
14952
+ return gcmEncrypt(enc, plaintext, cek, iv, aad);
14953
+ default:
14954
+ throw new JOSENotSupported(unsupportedEnc);
14955
+ }
14956
+ }
14957
+ async function decrypt(enc, cek, ciphertext, iv, tag2, aad) {
14958
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
14959
+ throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
14960
+ }
14961
+ if (!iv) {
14962
+ throw new JWEInvalid("JWE Initialization Vector missing");
14963
+ }
14964
+ if (!tag2) {
14965
+ throw new JWEInvalid("JWE Authentication Tag missing");
14966
+ }
14967
+ checkIvLength(enc, iv);
14968
+ switch (enc) {
14969
+ case "A128CBC-HS256":
14970
+ case "A192CBC-HS384":
14971
+ case "A256CBC-HS512":
14972
+ if (cek instanceof Uint8Array)
14973
+ checkCekLength(cek, parseInt(enc.slice(-3), 10));
14974
+ return cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad);
14617
14975
  case "A128GCM":
14618
14976
  case "A192GCM":
14619
14977
  case "A256GCM":
14620
14978
  if (cek instanceof Uint8Array)
14621
- check_cek_length_default(cek, parseInt(enc.slice(1, 4), 10));
14979
+ checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
14622
14980
  return gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad);
14623
14981
  default:
14624
- throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
14982
+ throw new JOSENotSupported(unsupportedEnc);
14625
14983
  }
14626
- };
14984
+ }
14985
+
14986
+ // node_modules/jose/dist/webapi/lib/helpers.js
14987
+ var unprotected = /* @__PURE__ */ Symbol();
14988
+ function assertNotSet(value, name) {
14989
+ if (value) {
14990
+ throw new TypeError(`${name} can only be called once`);
14991
+ }
14992
+ }
14993
+ function decodeBase64url(value, label, ErrorClass) {
14994
+ try {
14995
+ return decode(value);
14996
+ } catch {
14997
+ throw new ErrorClass(`Failed to base64url decode the ${label}`);
14998
+ }
14999
+ }
15000
+ async function digest(algorithm, data) {
15001
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
15002
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
15003
+ }
14627
15004
 
14628
- // node_modules/jose/dist/webapi/lib/is_disjoint.js
14629
- var is_disjoint_default = (...headers) => {
15005
+ // node_modules/jose/dist/webapi/lib/type_checks.js
15006
+ var isObjectLike = (value) => typeof value === "object" && value !== null;
15007
+ function isObject(input) {
15008
+ if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
15009
+ return false;
15010
+ }
15011
+ if (Object.getPrototypeOf(input) === null) {
15012
+ return true;
15013
+ }
15014
+ let proto = input;
15015
+ while (Object.getPrototypeOf(proto) !== null) {
15016
+ proto = Object.getPrototypeOf(proto);
15017
+ }
15018
+ return Object.getPrototypeOf(input) === proto;
15019
+ }
15020
+ function isDisjoint(...headers) {
14630
15021
  const sources = headers.filter(Boolean);
14631
15022
  if (sources.length === 0 || sources.length === 1) {
14632
15023
  return true;
@@ -14646,25 +15037,11 @@ var is_disjoint_default = (...headers) => {
14646
15037
  }
14647
15038
  }
14648
15039
  return true;
14649
- };
14650
-
14651
- // node_modules/jose/dist/webapi/lib/is_object.js
14652
- function isObjectLike(value) {
14653
- return typeof value === "object" && value !== null;
14654
15040
  }
14655
- var is_object_default = (input) => {
14656
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
14657
- return false;
14658
- }
14659
- if (Object.getPrototypeOf(input) === null) {
14660
- return true;
14661
- }
14662
- let proto = input;
14663
- while (Object.getPrototypeOf(proto) !== null) {
14664
- proto = Object.getPrototypeOf(proto);
14665
- }
14666
- return Object.getPrototypeOf(input) === proto;
14667
- };
15041
+ var isJWK = (key) => isObject(key) && typeof key.kty === "string";
15042
+ var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
15043
+ var isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
15044
+ var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
14668
15045
 
14669
15046
  // node_modules/jose/dist/webapi/lib/aeskw.js
14670
15047
  function checkKeySize(key, alg) {
@@ -14692,12 +15069,6 @@ async function unwrap(alg, key, encryptedKey) {
14692
15069
  return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek));
14693
15070
  }
14694
15071
 
14695
- // node_modules/jose/dist/webapi/lib/digest.js
14696
- var digest_default = async (algorithm, data) => {
14697
- const subtleDigest = `SHA-${algorithm.slice(-3)}`;
14698
- return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
14699
- };
14700
-
14701
15072
  // node_modules/jose/dist/webapi/lib/ecdhes.js
14702
15073
  function lengthAndInput(input) {
14703
15074
  return concat(uint32be(input.length), input);
@@ -14712,19 +15083,19 @@ async function concatKdf(Z, L, OtherInfo) {
14712
15083
  hashInput.set(uint32be(i), 0);
14713
15084
  hashInput.set(Z, 4);
14714
15085
  hashInput.set(OtherInfo, 4 + Z.length);
14715
- const hashResult = await digest_default("sha256", hashInput);
15086
+ const hashResult = await digest("sha256", hashInput);
14716
15087
  dk.set(hashResult, (i - 1) * hashLen);
14717
15088
  }
14718
15089
  return dk.slice(0, dkLen);
14719
15090
  }
14720
- async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {
15091
+ async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) {
14721
15092
  checkEncCryptoKey(publicKey, "ECDH");
14722
15093
  checkEncCryptoKey(privateKey, "ECDH", "deriveBits");
14723
- const algorithmID = lengthAndInput(encoder.encode(algorithm));
15094
+ const algorithmID = lengthAndInput(encode(algorithm));
14724
15095
  const partyUInfo = lengthAndInput(apu);
14725
15096
  const partyVInfo = lengthAndInput(apv);
14726
15097
  const suppPubInfo = uint32be(keyLength);
14727
- const suppPrivInfo = new Uint8Array(0);
15098
+ const suppPrivInfo = new Uint8Array();
14728
15099
  const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo);
14729
15100
  const Z = new Uint8Array(await crypto.subtle.deriveBits({
14730
15101
  name: publicKey.algorithm.name,
@@ -14752,12 +15123,14 @@ function allowed(key) {
14752
15123
  // node_modules/jose/dist/webapi/lib/pbes2kw.js
14753
15124
  function getCryptoKey2(key, alg) {
14754
15125
  if (key instanceof Uint8Array) {
14755
- return crypto.subtle.importKey("raw", key, "PBKDF2", false, ["deriveBits"]);
15126
+ return crypto.subtle.importKey("raw", key, "PBKDF2", false, [
15127
+ "deriveBits"
15128
+ ]);
14756
15129
  }
14757
15130
  checkEncCryptoKey(key, alg, "deriveBits");
14758
15131
  return key;
14759
15132
  }
14760
- var concatSalt = (alg, p2sInput) => concat(encoder.encode(alg), new Uint8Array([0]), p2sInput);
15133
+ var concatSalt = (alg, p2sInput) => concat(encode(alg), Uint8Array.of(0), p2sInput);
14761
15134
  async function deriveKey2(p2s, alg, p2c, key) {
14762
15135
  if (!(p2s instanceof Uint8Array) || p2s.length < 8) {
14763
15136
  throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets");
@@ -14776,25 +15149,81 @@ async function deriveKey2(p2s, alg, p2c, key) {
14776
15149
  async function wrap2(alg, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) {
14777
15150
  const derived = await deriveKey2(p2s, alg, p2c, key);
14778
15151
  const encryptedKey = await wrap(alg.slice(-6), derived, cek);
14779
- return { encryptedKey, p2c, p2s: encode(p2s) };
15152
+ return { encryptedKey, p2c, p2s: encode2(p2s) };
14780
15153
  }
14781
15154
  async function unwrap2(alg, key, encryptedKey, p2c, p2s) {
14782
15155
  const derived = await deriveKey2(p2s, alg, p2c, key);
14783
15156
  return unwrap(alg.slice(-6), derived, encryptedKey);
14784
15157
  }
14785
15158
 
14786
- // node_modules/jose/dist/webapi/lib/check_key_length.js
14787
- var check_key_length_default = (alg, key) => {
15159
+ // node_modules/jose/dist/webapi/lib/signing.js
15160
+ function checkKeyLength(alg, key) {
14788
15161
  if (alg.startsWith("RS") || alg.startsWith("PS")) {
14789
15162
  const { modulusLength } = key.algorithm;
14790
15163
  if (typeof modulusLength !== "number" || modulusLength < 2048) {
14791
15164
  throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
14792
15165
  }
14793
15166
  }
14794
- };
15167
+ }
15168
+ function subtleAlgorithm(alg, algorithm) {
15169
+ const hash = `SHA-${alg.slice(-3)}`;
15170
+ switch (alg) {
15171
+ case "HS256":
15172
+ case "HS384":
15173
+ case "HS512":
15174
+ return { hash, name: "HMAC" };
15175
+ case "PS256":
15176
+ case "PS384":
15177
+ case "PS512":
15178
+ return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
15179
+ case "RS256":
15180
+ case "RS384":
15181
+ case "RS512":
15182
+ return { hash, name: "RSASSA-PKCS1-v1_5" };
15183
+ case "ES256":
15184
+ case "ES384":
15185
+ case "ES512":
15186
+ return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
15187
+ case "Ed25519":
15188
+ case "EdDSA":
15189
+ return { name: "Ed25519" };
15190
+ case "ML-DSA-44":
15191
+ case "ML-DSA-65":
15192
+ case "ML-DSA-87":
15193
+ return { name: alg };
15194
+ default:
15195
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
15196
+ }
15197
+ }
15198
+ async function getSigKey(alg, key, usage2) {
15199
+ if (key instanceof Uint8Array) {
15200
+ if (!alg.startsWith("HS")) {
15201
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
15202
+ }
15203
+ return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage2]);
15204
+ }
15205
+ checkSigCryptoKey(key, alg, usage2);
15206
+ return key;
15207
+ }
15208
+ async function sign(alg, key, data) {
15209
+ const cryptoKey = await getSigKey(alg, key, "sign");
15210
+ checkKeyLength(alg, cryptoKey);
15211
+ const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);
15212
+ return new Uint8Array(signature);
15213
+ }
15214
+ async function verify(alg, key, signature, data) {
15215
+ const cryptoKey = await getSigKey(alg, key, "verify");
15216
+ checkKeyLength(alg, cryptoKey);
15217
+ const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
15218
+ try {
15219
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
15220
+ } catch {
15221
+ return false;
15222
+ }
15223
+ }
14795
15224
 
14796
15225
  // node_modules/jose/dist/webapi/lib/rsaes.js
14797
- var subtleAlgorithm = (alg) => {
15226
+ var subtleAlgorithm2 = (alg) => {
14798
15227
  switch (alg) {
14799
15228
  case "RSA-OAEP":
14800
15229
  case "RSA-OAEP-256":
@@ -14805,38 +15234,19 @@ var subtleAlgorithm = (alg) => {
14805
15234
  throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
14806
15235
  }
14807
15236
  };
14808
- async function encrypt(alg, key, cek) {
15237
+ async function encrypt2(alg, key, cek) {
14809
15238
  checkEncCryptoKey(key, alg, "encrypt");
14810
- check_key_length_default(alg, key);
14811
- return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek));
15239
+ checkKeyLength(alg, key);
15240
+ return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm2(alg), key, cek));
14812
15241
  }
14813
- async function decrypt(alg, key, encryptedKey) {
15242
+ async function decrypt2(alg, key, encryptedKey) {
14814
15243
  checkEncCryptoKey(key, alg, "decrypt");
14815
- check_key_length_default(alg, key);
14816
- return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey));
14817
- }
14818
-
14819
- // node_modules/jose/dist/webapi/lib/cek.js
14820
- function bitLength2(alg) {
14821
- switch (alg) {
14822
- case "A128GCM":
14823
- return 128;
14824
- case "A192GCM":
14825
- return 192;
14826
- case "A256GCM":
14827
- case "A128CBC-HS256":
14828
- return 256;
14829
- case "A192CBC-HS384":
14830
- return 384;
14831
- case "A256CBC-HS512":
14832
- return 512;
14833
- default:
14834
- throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
14835
- }
15244
+ checkKeyLength(alg, key);
15245
+ return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm2(alg), key, encryptedKey));
14836
15246
  }
14837
- var cek_default = (alg) => crypto.getRandomValues(new Uint8Array(bitLength2(alg) >> 3));
14838
15247
 
14839
15248
  // node_modules/jose/dist/webapi/lib/jwk_to_key.js
15249
+ var unsupportedAlg = 'Invalid or unsupported JWK "alg" (Algorithm) Parameter value';
14840
15250
  function subtleMapping(jwk) {
14841
15251
  let algorithm;
14842
15252
  let keyUsages;
@@ -14850,7 +15260,7 @@ function subtleMapping(jwk) {
14850
15260
  keyUsages = jwk.priv ? ["sign"] : ["verify"];
14851
15261
  break;
14852
15262
  default:
14853
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
15263
+ throw new JOSENotSupported(unsupportedAlg);
14854
15264
  }
14855
15265
  break;
14856
15266
  }
@@ -14879,22 +15289,19 @@ function subtleMapping(jwk) {
14879
15289
  keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
14880
15290
  break;
14881
15291
  default:
14882
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
15292
+ throw new JOSENotSupported(unsupportedAlg);
14883
15293
  }
14884
15294
  break;
14885
15295
  }
14886
15296
  case "EC": {
14887
15297
  switch (jwk.alg) {
14888
15298
  case "ES256":
14889
- algorithm = { name: "ECDSA", namedCurve: "P-256" };
14890
- keyUsages = jwk.d ? ["sign"] : ["verify"];
14891
- break;
14892
15299
  case "ES384":
14893
- algorithm = { name: "ECDSA", namedCurve: "P-384" };
14894
- keyUsages = jwk.d ? ["sign"] : ["verify"];
14895
- break;
14896
15300
  case "ES512":
14897
- algorithm = { name: "ECDSA", namedCurve: "P-521" };
15301
+ algorithm = {
15302
+ name: "ECDSA",
15303
+ namedCurve: { ES256: "P-256", ES384: "P-384", ES512: "P-521" }[jwk.alg]
15304
+ };
14898
15305
  keyUsages = jwk.d ? ["sign"] : ["verify"];
14899
15306
  break;
14900
15307
  case "ECDH-ES":
@@ -14905,7 +15312,7 @@ function subtleMapping(jwk) {
14905
15312
  keyUsages = jwk.d ? ["deriveBits"] : [];
14906
15313
  break;
14907
15314
  default:
14908
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
15315
+ throw new JOSENotSupported(unsupportedAlg);
14909
15316
  }
14910
15317
  break;
14911
15318
  }
@@ -14924,7 +15331,7 @@ function subtleMapping(jwk) {
14924
15331
  keyUsages = jwk.d ? ["deriveBits"] : [];
14925
15332
  break;
14926
15333
  default:
14927
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
15334
+ throw new JOSENotSupported(unsupportedAlg);
14928
15335
  }
14929
15336
  break;
14930
15337
  }
@@ -14933,7 +15340,7 @@ function subtleMapping(jwk) {
14933
15340
  }
14934
15341
  return { algorithm, keyUsages };
14935
15342
  }
14936
- var jwk_to_key_default = async (jwk) => {
15343
+ async function jwkToKey(jwk) {
14937
15344
  if (!jwk.alg) {
14938
15345
  throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
14939
15346
  }
@@ -14944,127 +15351,261 @@ var jwk_to_key_default = async (jwk) => {
14944
15351
  }
14945
15352
  delete keyData.use;
14946
15353
  return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
14947
- };
14948
-
14949
- // node_modules/jose/dist/webapi/key/import.js
14950
- async function importJWK(jwk, alg, options) {
14951
- if (!is_object_default(jwk)) {
14952
- throw new TypeError("JWK must be an object");
14953
- }
14954
- let ext;
14955
- alg ??= jwk.alg;
14956
- ext ??= options?.extractable ?? jwk.ext;
14957
- switch (jwk.kty) {
14958
- case "oct":
14959
- if (typeof jwk.k !== "string" || !jwk.k) {
14960
- throw new TypeError('missing "k" (Key Value) Parameter value');
14961
- }
14962
- return decode(jwk.k);
14963
- case "RSA":
14964
- if ("oth" in jwk && jwk.oth !== void 0) {
14965
- throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
14966
- }
14967
- return jwk_to_key_default({ ...jwk, alg, ext });
14968
- case "AKP": {
14969
- if (typeof jwk.alg !== "string" || !jwk.alg) {
14970
- throw new TypeError('missing "alg" (Algorithm) Parameter value');
14971
- }
14972
- if (alg !== void 0 && alg !== jwk.alg) {
14973
- throw new TypeError("JWK alg and alg option value mismatch");
14974
- }
14975
- return jwk_to_key_default({ ...jwk, ext });
14976
- }
14977
- case "EC":
14978
- case "OKP":
14979
- return jwk_to_key_default({ ...jwk, alg, ext });
14980
- default:
14981
- throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
14982
- }
14983
15354
  }
14984
15355
 
14985
- // node_modules/jose/dist/webapi/lib/encrypt.js
14986
- async function cbcEncrypt(enc, plaintext, cek, iv, aad) {
14987
- if (!(cek instanceof Uint8Array)) {
14988
- throw new TypeError(invalid_key_input_default(cek, "Uint8Array"));
15356
+ // node_modules/jose/dist/webapi/lib/normalize_key.js
15357
+ var unusableForAlg = "given KeyObject instance cannot be used for this algorithm";
15358
+ var cache;
15359
+ var handleJWK = async (key, jwk, alg, freeze = false) => {
15360
+ cache ||= /* @__PURE__ */ new WeakMap();
15361
+ let cached = cache.get(key);
15362
+ if (cached?.[alg]) {
15363
+ return cached[alg];
14989
15364
  }
14990
- const keySize = parseInt(enc.slice(1, 4), 10);
14991
- const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["encrypt"]);
14992
- const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
14993
- hash: `SHA-${keySize << 1}`,
14994
- name: "HMAC"
14995
- }, false, ["sign"]);
14996
- const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
14997
- iv,
14998
- name: "AES-CBC"
14999
- }, encKey, plaintext));
15000
- const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
15001
- const tag2 = new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
15002
- return { ciphertext, tag: tag2, iv };
15003
- }
15004
- async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
15005
- let encKey;
15006
- if (cek instanceof Uint8Array) {
15007
- encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]);
15365
+ const cryptoKey = await jwkToKey({ ...jwk, alg });
15366
+ if (freeze)
15367
+ Object.freeze(key);
15368
+ if (!cached) {
15369
+ cache.set(key, { [alg]: cryptoKey });
15008
15370
  } else {
15009
- checkEncCryptoKey(cek, enc, "encrypt");
15010
- encKey = cek;
15371
+ cached[alg] = cryptoKey;
15011
15372
  }
15012
- const encrypted = new Uint8Array(await crypto.subtle.encrypt({
15013
- additionalData: aad,
15014
- iv,
15015
- name: "AES-GCM",
15016
- tagLength: 128
15017
- }, encKey, plaintext));
15018
- const tag2 = encrypted.slice(-16);
15019
- const ciphertext = encrypted.slice(0, -16);
15020
- return { ciphertext, tag: tag2, iv };
15021
- }
15022
- var encrypt_default = async (enc, plaintext, cek, iv, aad) => {
15023
- if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
15024
- throw new TypeError(invalid_key_input_default(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
15373
+ return cryptoKey;
15374
+ };
15375
+ var handleKeyObject = (keyObject, alg) => {
15376
+ cache ||= /* @__PURE__ */ new WeakMap();
15377
+ let cached = cache.get(keyObject);
15378
+ if (cached?.[alg]) {
15379
+ return cached[alg];
15025
15380
  }
15026
- if (iv) {
15027
- check_iv_length_default(enc, iv);
15028
- } else {
15029
- iv = iv_default(enc);
15381
+ const isPublic = keyObject.type === "public";
15382
+ const extractable = isPublic ? true : false;
15383
+ let cryptoKey;
15384
+ if (keyObject.asymmetricKeyType === "x25519") {
15385
+ switch (alg) {
15386
+ case "ECDH-ES":
15387
+ case "ECDH-ES+A128KW":
15388
+ case "ECDH-ES+A192KW":
15389
+ case "ECDH-ES+A256KW":
15390
+ break;
15391
+ default:
15392
+ throw new TypeError(unusableForAlg);
15393
+ }
15394
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
15030
15395
  }
15031
- switch (enc) {
15032
- case "A128CBC-HS256":
15033
- case "A192CBC-HS384":
15034
- case "A256CBC-HS512":
15035
- if (cek instanceof Uint8Array) {
15036
- check_cek_length_default(cek, parseInt(enc.slice(-3), 10));
15037
- }
15038
- return cbcEncrypt(enc, plaintext, cek, iv, aad);
15039
- case "A128GCM":
15040
- case "A192GCM":
15041
- case "A256GCM":
15042
- if (cek instanceof Uint8Array) {
15043
- check_cek_length_default(cek, parseInt(enc.slice(1, 4), 10));
15044
- }
15045
- return gcmEncrypt(enc, plaintext, cek, iv, aad);
15046
- default:
15047
- throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
15396
+ if (keyObject.asymmetricKeyType === "ed25519") {
15397
+ if (alg !== "EdDSA" && alg !== "Ed25519") {
15398
+ throw new TypeError(unusableForAlg);
15399
+ }
15400
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
15401
+ isPublic ? "verify" : "sign"
15402
+ ]);
15048
15403
  }
15404
+ switch (keyObject.asymmetricKeyType) {
15405
+ case "ml-dsa-44":
15406
+ case "ml-dsa-65":
15407
+ case "ml-dsa-87": {
15408
+ if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {
15409
+ throw new TypeError(unusableForAlg);
15410
+ }
15411
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
15412
+ isPublic ? "verify" : "sign"
15413
+ ]);
15414
+ }
15415
+ }
15416
+ if (keyObject.asymmetricKeyType === "rsa") {
15417
+ let hash;
15418
+ switch (alg) {
15419
+ case "RSA-OAEP":
15420
+ hash = "SHA-1";
15421
+ break;
15422
+ case "RS256":
15423
+ case "PS256":
15424
+ case "RSA-OAEP-256":
15425
+ hash = "SHA-256";
15426
+ break;
15427
+ case "RS384":
15428
+ case "PS384":
15429
+ case "RSA-OAEP-384":
15430
+ hash = "SHA-384";
15431
+ break;
15432
+ case "RS512":
15433
+ case "PS512":
15434
+ case "RSA-OAEP-512":
15435
+ hash = "SHA-512";
15436
+ break;
15437
+ default:
15438
+ throw new TypeError(unusableForAlg);
15439
+ }
15440
+ if (alg.startsWith("RSA-OAEP")) {
15441
+ return keyObject.toCryptoKey({
15442
+ name: "RSA-OAEP",
15443
+ hash
15444
+ }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
15445
+ }
15446
+ cryptoKey = keyObject.toCryptoKey({
15447
+ name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
15448
+ hash
15449
+ }, extractable, [isPublic ? "verify" : "sign"]);
15450
+ }
15451
+ if (keyObject.asymmetricKeyType === "ec") {
15452
+ const nist = /* @__PURE__ */ new Map([
15453
+ ["prime256v1", "P-256"],
15454
+ ["secp384r1", "P-384"],
15455
+ ["secp521r1", "P-521"]
15456
+ ]);
15457
+ const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
15458
+ if (!namedCurve) {
15459
+ throw new TypeError(unusableForAlg);
15460
+ }
15461
+ const expectedCurve = { ES256: "P-256", ES384: "P-384", ES512: "P-521" };
15462
+ if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) {
15463
+ cryptoKey = keyObject.toCryptoKey({
15464
+ name: "ECDSA",
15465
+ namedCurve
15466
+ }, extractable, [isPublic ? "verify" : "sign"]);
15467
+ }
15468
+ if (alg.startsWith("ECDH-ES")) {
15469
+ cryptoKey = keyObject.toCryptoKey({
15470
+ name: "ECDH",
15471
+ namedCurve
15472
+ }, extractable, isPublic ? [] : ["deriveBits"]);
15473
+ }
15474
+ }
15475
+ if (!cryptoKey) {
15476
+ throw new TypeError(unusableForAlg);
15477
+ }
15478
+ if (!cached) {
15479
+ cache.set(keyObject, { [alg]: cryptoKey });
15480
+ } else {
15481
+ cached[alg] = cryptoKey;
15482
+ }
15483
+ return cryptoKey;
15049
15484
  };
15485
+ async function normalizeKey(key, alg) {
15486
+ if (key instanceof Uint8Array) {
15487
+ return key;
15488
+ }
15489
+ if (isCryptoKey(key)) {
15490
+ return key;
15491
+ }
15492
+ if (isKeyObject(key)) {
15493
+ if (key.type === "secret") {
15494
+ return key.export();
15495
+ }
15496
+ if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
15497
+ try {
15498
+ return handleKeyObject(key, alg);
15499
+ } catch (err) {
15500
+ if (err instanceof TypeError) {
15501
+ throw err;
15502
+ }
15503
+ }
15504
+ }
15505
+ let jwk = key.export({ format: "jwk" });
15506
+ return handleJWK(key, jwk, alg);
15507
+ }
15508
+ if (isJWK(key)) {
15509
+ if (key.k) {
15510
+ return decode(key.k);
15511
+ }
15512
+ return handleJWK(key, key, alg, true);
15513
+ }
15514
+ throw new Error("unreachable");
15515
+ }
15516
+
15517
+ // node_modules/jose/dist/webapi/key/import.js
15518
+ async function importJWK(jwk, alg, options) {
15519
+ if (!isObject(jwk)) {
15520
+ throw new TypeError("JWK must be an object");
15521
+ }
15522
+ let ext;
15523
+ alg ??= jwk.alg;
15524
+ ext ??= options?.extractable ?? jwk.ext;
15525
+ switch (jwk.kty) {
15526
+ case "oct":
15527
+ if (typeof jwk.k !== "string" || !jwk.k) {
15528
+ throw new TypeError('missing "k" (Key Value) Parameter value');
15529
+ }
15530
+ return decode(jwk.k);
15531
+ case "RSA":
15532
+ if ("oth" in jwk && jwk.oth !== void 0) {
15533
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
15534
+ }
15535
+ return jwkToKey({ ...jwk, alg, ext });
15536
+ case "AKP": {
15537
+ if (typeof jwk.alg !== "string" || !jwk.alg) {
15538
+ throw new TypeError('missing "alg" (Algorithm) Parameter value');
15539
+ }
15540
+ if (alg !== void 0 && alg !== jwk.alg) {
15541
+ throw new TypeError("JWK alg and alg option value mismatch");
15542
+ }
15543
+ return jwkToKey({ ...jwk, ext });
15544
+ }
15545
+ case "EC":
15546
+ case "OKP":
15547
+ return jwkToKey({ ...jwk, alg, ext });
15548
+ default:
15549
+ throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
15550
+ }
15551
+ }
15552
+
15553
+ // node_modules/jose/dist/webapi/lib/key_to_jwk.js
15554
+ async function keyToJWK(key) {
15555
+ if (isKeyObject(key)) {
15556
+ if (key.type === "secret") {
15557
+ key = key.export();
15558
+ } else {
15559
+ return key.export({ format: "jwk" });
15560
+ }
15561
+ }
15562
+ if (key instanceof Uint8Array) {
15563
+ return {
15564
+ kty: "oct",
15565
+ k: encode2(key)
15566
+ };
15567
+ }
15568
+ if (!isCryptoKey(key)) {
15569
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
15570
+ }
15571
+ if (!key.extractable) {
15572
+ throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
15573
+ }
15574
+ const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey("jwk", key);
15575
+ if (jwk.kty === "AKP") {
15576
+ ;
15577
+ jwk.alg = alg;
15578
+ }
15579
+ return jwk;
15580
+ }
15581
+
15582
+ // node_modules/jose/dist/webapi/key/export.js
15583
+ async function exportJWK(key) {
15584
+ return keyToJWK(key);
15585
+ }
15050
15586
 
15051
15587
  // node_modules/jose/dist/webapi/lib/aesgcmkw.js
15052
15588
  async function wrap3(alg, key, cek, iv) {
15053
15589
  const jweAlgorithm = alg.slice(0, 7);
15054
- const wrapped = await encrypt_default(jweAlgorithm, cek, key, iv, new Uint8Array(0));
15590
+ const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array());
15055
15591
  return {
15056
15592
  encryptedKey: wrapped.ciphertext,
15057
- iv: encode(wrapped.iv),
15058
- tag: encode(wrapped.tag)
15593
+ iv: encode2(wrapped.iv),
15594
+ tag: encode2(wrapped.tag)
15059
15595
  };
15060
15596
  }
15061
15597
  async function unwrap3(alg, key, encryptedKey, iv, tag2) {
15062
15598
  const jweAlgorithm = alg.slice(0, 7);
15063
- return decrypt_default(jweAlgorithm, key, encryptedKey, iv, tag2, new Uint8Array(0));
15599
+ return decrypt(jweAlgorithm, key, encryptedKey, iv, tag2, new Uint8Array());
15064
15600
  }
15065
15601
 
15066
- // node_modules/jose/dist/webapi/lib/decrypt_key_management.js
15067
- var decrypt_key_management_default = async (alg, key, encryptedKey, joseHeader, options) => {
15602
+ // node_modules/jose/dist/webapi/lib/key_management.js
15603
+ var unsupportedAlgHeader = 'Invalid or unsupported "alg" (JWE Algorithm) header value';
15604
+ function assertEncryptedKey(encryptedKey) {
15605
+ if (encryptedKey === void 0)
15606
+ throw new JWEInvalid("JWE Encrypted Key missing");
15607
+ }
15608
+ async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) {
15068
15609
  switch (alg) {
15069
15610
  case "dir": {
15070
15611
  if (encryptedKey !== void 0)
@@ -15077,7 +15618,7 @@ var decrypt_key_management_default = async (alg, key, encryptedKey, joseHeader,
15077
15618
  case "ECDH-ES+A128KW":
15078
15619
  case "ECDH-ES+A192KW":
15079
15620
  case "ECDH-ES+A256KW": {
15080
- if (!is_object_default(joseHeader.epk))
15621
+ if (!isObject(joseHeader.epk))
15081
15622
  throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);
15082
15623
  assertCryptoKey(key);
15083
15624
  if (!allowed(key))
@@ -15089,42 +15630,31 @@ var decrypt_key_management_default = async (alg, key, encryptedKey, joseHeader,
15089
15630
  if (joseHeader.apu !== void 0) {
15090
15631
  if (typeof joseHeader.apu !== "string")
15091
15632
  throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);
15092
- try {
15093
- partyUInfo = decode(joseHeader.apu);
15094
- } catch {
15095
- throw new JWEInvalid("Failed to base64url decode the apu");
15096
- }
15633
+ partyUInfo = decodeBase64url(joseHeader.apu, "apu", JWEInvalid);
15097
15634
  }
15098
15635
  if (joseHeader.apv !== void 0) {
15099
15636
  if (typeof joseHeader.apv !== "string")
15100
15637
  throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);
15101
- try {
15102
- partyVInfo = decode(joseHeader.apv);
15103
- } catch {
15104
- throw new JWEInvalid("Failed to base64url decode the apv");
15105
- }
15638
+ partyVInfo = decodeBase64url(joseHeader.apv, "apv", JWEInvalid);
15106
15639
  }
15107
- const sharedSecret = await deriveKey(epk, key, alg === "ECDH-ES" ? joseHeader.enc : alg, alg === "ECDH-ES" ? bitLength2(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);
15640
+ const sharedSecret = await deriveKey(epk, key, alg === "ECDH-ES" ? joseHeader.enc : alg, alg === "ECDH-ES" ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);
15108
15641
  if (alg === "ECDH-ES")
15109
15642
  return sharedSecret;
15110
- if (encryptedKey === void 0)
15111
- throw new JWEInvalid("JWE Encrypted Key missing");
15643
+ assertEncryptedKey(encryptedKey);
15112
15644
  return unwrap(alg.slice(-6), sharedSecret, encryptedKey);
15113
15645
  }
15114
15646
  case "RSA-OAEP":
15115
15647
  case "RSA-OAEP-256":
15116
15648
  case "RSA-OAEP-384":
15117
15649
  case "RSA-OAEP-512": {
15118
- if (encryptedKey === void 0)
15119
- throw new JWEInvalid("JWE Encrypted Key missing");
15650
+ assertEncryptedKey(encryptedKey);
15120
15651
  assertCryptoKey(key);
15121
- return decrypt(alg, key, encryptedKey);
15652
+ return decrypt2(alg, key, encryptedKey);
15122
15653
  }
15123
15654
  case "PBES2-HS256+A128KW":
15124
15655
  case "PBES2-HS384+A192KW":
15125
15656
  case "PBES2-HS512+A256KW": {
15126
- if (encryptedKey === void 0)
15127
- throw new JWEInvalid("JWE Encrypted Key missing");
15657
+ assertEncryptedKey(encryptedKey);
15128
15658
  if (typeof joseHeader.p2c !== "number")
15129
15659
  throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
15130
15660
  const p2cLimit = options?.maxPBES2Count || 1e4;
@@ -15133,51 +15663,117 @@ var decrypt_key_management_default = async (alg, key, encryptedKey, joseHeader,
15133
15663
  if (typeof joseHeader.p2s !== "string")
15134
15664
  throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);
15135
15665
  let p2s;
15136
- try {
15137
- p2s = decode(joseHeader.p2s);
15138
- } catch {
15139
- throw new JWEInvalid("Failed to base64url decode the p2s");
15140
- }
15666
+ p2s = decodeBase64url(joseHeader.p2s, "p2s", JWEInvalid);
15141
15667
  return unwrap2(alg, key, encryptedKey, joseHeader.p2c, p2s);
15142
15668
  }
15143
15669
  case "A128KW":
15144
15670
  case "A192KW":
15145
15671
  case "A256KW": {
15146
- if (encryptedKey === void 0)
15147
- throw new JWEInvalid("JWE Encrypted Key missing");
15672
+ assertEncryptedKey(encryptedKey);
15148
15673
  return unwrap(alg, key, encryptedKey);
15149
15674
  }
15150
15675
  case "A128GCMKW":
15151
15676
  case "A192GCMKW":
15152
15677
  case "A256GCMKW": {
15153
- if (encryptedKey === void 0)
15154
- throw new JWEInvalid("JWE Encrypted Key missing");
15678
+ assertEncryptedKey(encryptedKey);
15155
15679
  if (typeof joseHeader.iv !== "string")
15156
15680
  throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`);
15157
15681
  if (typeof joseHeader.tag !== "string")
15158
15682
  throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`);
15159
15683
  let iv;
15160
- try {
15161
- iv = decode(joseHeader.iv);
15162
- } catch {
15163
- throw new JWEInvalid("Failed to base64url decode the iv");
15164
- }
15684
+ iv = decodeBase64url(joseHeader.iv, "iv", JWEInvalid);
15165
15685
  let tag2;
15166
- try {
15167
- tag2 = decode(joseHeader.tag);
15168
- } catch {
15169
- throw new JWEInvalid("Failed to base64url decode the tag");
15170
- }
15686
+ tag2 = decodeBase64url(joseHeader.tag, "tag", JWEInvalid);
15171
15687
  return unwrap3(alg, key, encryptedKey, iv, tag2);
15172
15688
  }
15173
15689
  default: {
15174
- throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
15690
+ throw new JOSENotSupported(unsupportedAlgHeader);
15175
15691
  }
15176
15692
  }
15177
- };
15693
+ }
15694
+ async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) {
15695
+ let encryptedKey;
15696
+ let parameters;
15697
+ let cek;
15698
+ switch (alg) {
15699
+ case "dir": {
15700
+ cek = key;
15701
+ break;
15702
+ }
15703
+ case "ECDH-ES":
15704
+ case "ECDH-ES+A128KW":
15705
+ case "ECDH-ES+A192KW":
15706
+ case "ECDH-ES+A256KW": {
15707
+ assertCryptoKey(key);
15708
+ if (!allowed(key)) {
15709
+ throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
15710
+ }
15711
+ const { apu, apv } = providedParameters;
15712
+ let ephemeralKey;
15713
+ if (providedParameters.epk) {
15714
+ ephemeralKey = await normalizeKey(providedParameters.epk, alg);
15715
+ } else {
15716
+ ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey;
15717
+ }
15718
+ const { x, y, crv, kty } = await exportJWK(ephemeralKey);
15719
+ const sharedSecret = await deriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
15720
+ parameters = { epk: { x, crv, kty } };
15721
+ if (kty === "EC")
15722
+ parameters.epk.y = y;
15723
+ if (apu)
15724
+ parameters.apu = encode2(apu);
15725
+ if (apv)
15726
+ parameters.apv = encode2(apv);
15727
+ if (alg === "ECDH-ES") {
15728
+ cek = sharedSecret;
15729
+ break;
15730
+ }
15731
+ cek = providedCek || generateCek(enc);
15732
+ const kwAlg = alg.slice(-6);
15733
+ encryptedKey = await wrap(kwAlg, sharedSecret, cek);
15734
+ break;
15735
+ }
15736
+ case "RSA-OAEP":
15737
+ case "RSA-OAEP-256":
15738
+ case "RSA-OAEP-384":
15739
+ case "RSA-OAEP-512": {
15740
+ cek = providedCek || generateCek(enc);
15741
+ assertCryptoKey(key);
15742
+ encryptedKey = await encrypt2(alg, key, cek);
15743
+ break;
15744
+ }
15745
+ case "PBES2-HS256+A128KW":
15746
+ case "PBES2-HS384+A192KW":
15747
+ case "PBES2-HS512+A256KW": {
15748
+ cek = providedCek || generateCek(enc);
15749
+ const { p2c, p2s } = providedParameters;
15750
+ ({ encryptedKey, ...parameters } = await wrap2(alg, key, cek, p2c, p2s));
15751
+ break;
15752
+ }
15753
+ case "A128KW":
15754
+ case "A192KW":
15755
+ case "A256KW": {
15756
+ cek = providedCek || generateCek(enc);
15757
+ encryptedKey = await wrap(alg, key, cek);
15758
+ break;
15759
+ }
15760
+ case "A128GCMKW":
15761
+ case "A192GCMKW":
15762
+ case "A256GCMKW": {
15763
+ cek = providedCek || generateCek(enc);
15764
+ const { iv } = providedParameters;
15765
+ ({ encryptedKey, ...parameters } = await wrap3(alg, key, cek, iv));
15766
+ break;
15767
+ }
15768
+ default: {
15769
+ throw new JOSENotSupported(unsupportedAlgHeader);
15770
+ }
15771
+ }
15772
+ return { cek, encryptedKey, parameters };
15773
+ }
15178
15774
 
15179
15775
  // node_modules/jose/dist/webapi/lib/validate_crit.js
15180
- var validate_crit_default = (Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) => {
15776
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
15181
15777
  if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) {
15182
15778
  throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
15183
15779
  }
@@ -15193,215 +15789,30 @@ var validate_crit_default = (Err, recognizedDefault, recognizedOption, protected
15193
15789
  } else {
15194
15790
  recognized = recognizedDefault;
15195
15791
  }
15196
- for (const parameter of protectedHeader.crit) {
15197
- if (!recognized.has(parameter)) {
15198
- throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
15199
- }
15200
- if (joseHeader[parameter] === void 0) {
15201
- throw new Err(`Extension Header Parameter "${parameter}" is missing`);
15202
- }
15203
- if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
15204
- throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
15205
- }
15206
- }
15207
- return new Set(protectedHeader.crit);
15208
- };
15209
-
15210
- // node_modules/jose/dist/webapi/lib/validate_algorithms.js
15211
- var validate_algorithms_default = (option, algorithms) => {
15212
- if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
15213
- throw new TypeError(`"${option}" option must be an array of strings`);
15214
- }
15215
- if (!algorithms) {
15216
- return void 0;
15217
- }
15218
- return new Set(algorithms);
15219
- };
15220
-
15221
- // node_modules/jose/dist/webapi/lib/is_jwk.js
15222
- function isJWK(key) {
15223
- return is_object_default(key) && typeof key.kty === "string";
15224
- }
15225
- function isPrivateJWK(key) {
15226
- return key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
15227
- }
15228
- function isPublicJWK(key) {
15229
- return key.kty !== "oct" && typeof key.d === "undefined" && typeof key.priv === "undefined";
15230
- }
15231
- function isSecretJWK(key) {
15232
- return key.kty === "oct" && typeof key.k === "string";
15233
- }
15234
-
15235
- // node_modules/jose/dist/webapi/lib/normalize_key.js
15236
- var cache;
15237
- var handleJWK = async (key, jwk, alg, freeze = false) => {
15238
- cache ||= /* @__PURE__ */ new WeakMap();
15239
- let cached = cache.get(key);
15240
- if (cached?.[alg]) {
15241
- return cached[alg];
15242
- }
15243
- const cryptoKey = await jwk_to_key_default({ ...jwk, alg });
15244
- if (freeze)
15245
- Object.freeze(key);
15246
- if (!cached) {
15247
- cache.set(key, { [alg]: cryptoKey });
15248
- } else {
15249
- cached[alg] = cryptoKey;
15250
- }
15251
- return cryptoKey;
15252
- };
15253
- var handleKeyObject = (keyObject, alg) => {
15254
- cache ||= /* @__PURE__ */ new WeakMap();
15255
- let cached = cache.get(keyObject);
15256
- if (cached?.[alg]) {
15257
- return cached[alg];
15258
- }
15259
- const isPublic = keyObject.type === "public";
15260
- const extractable = isPublic ? true : false;
15261
- let cryptoKey;
15262
- if (keyObject.asymmetricKeyType === "x25519") {
15263
- switch (alg) {
15264
- case "ECDH-ES":
15265
- case "ECDH-ES+A128KW":
15266
- case "ECDH-ES+A192KW":
15267
- case "ECDH-ES+A256KW":
15268
- break;
15269
- default:
15270
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
15271
- }
15272
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
15273
- }
15274
- if (keyObject.asymmetricKeyType === "ed25519") {
15275
- if (alg !== "EdDSA" && alg !== "Ed25519") {
15276
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
15277
- }
15278
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
15279
- isPublic ? "verify" : "sign"
15280
- ]);
15281
- }
15282
- switch (keyObject.asymmetricKeyType) {
15283
- case "ml-dsa-44":
15284
- case "ml-dsa-65":
15285
- case "ml-dsa-87": {
15286
- if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {
15287
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
15288
- }
15289
- cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
15290
- isPublic ? "verify" : "sign"
15291
- ]);
15292
- }
15293
- }
15294
- if (keyObject.asymmetricKeyType === "rsa") {
15295
- let hash;
15296
- switch (alg) {
15297
- case "RSA-OAEP":
15298
- hash = "SHA-1";
15299
- break;
15300
- case "RS256":
15301
- case "PS256":
15302
- case "RSA-OAEP-256":
15303
- hash = "SHA-256";
15304
- break;
15305
- case "RS384":
15306
- case "PS384":
15307
- case "RSA-OAEP-384":
15308
- hash = "SHA-384";
15309
- break;
15310
- case "RS512":
15311
- case "PS512":
15312
- case "RSA-OAEP-512":
15313
- hash = "SHA-512";
15314
- break;
15315
- default:
15316
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
15317
- }
15318
- if (alg.startsWith("RSA-OAEP")) {
15319
- return keyObject.toCryptoKey({
15320
- name: "RSA-OAEP",
15321
- hash
15322
- }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
15323
- }
15324
- cryptoKey = keyObject.toCryptoKey({
15325
- name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
15326
- hash
15327
- }, extractable, [isPublic ? "verify" : "sign"]);
15328
- }
15329
- if (keyObject.asymmetricKeyType === "ec") {
15330
- const nist = /* @__PURE__ */ new Map([
15331
- ["prime256v1", "P-256"],
15332
- ["secp384r1", "P-384"],
15333
- ["secp521r1", "P-521"]
15334
- ]);
15335
- const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
15336
- if (!namedCurve) {
15337
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
15338
- }
15339
- if (alg === "ES256" && namedCurve === "P-256") {
15340
- cryptoKey = keyObject.toCryptoKey({
15341
- name: "ECDSA",
15342
- namedCurve
15343
- }, extractable, [isPublic ? "verify" : "sign"]);
15344
- }
15345
- if (alg === "ES384" && namedCurve === "P-384") {
15346
- cryptoKey = keyObject.toCryptoKey({
15347
- name: "ECDSA",
15348
- namedCurve
15349
- }, extractable, [isPublic ? "verify" : "sign"]);
15350
- }
15351
- if (alg === "ES512" && namedCurve === "P-521") {
15352
- cryptoKey = keyObject.toCryptoKey({
15353
- name: "ECDSA",
15354
- namedCurve
15355
- }, extractable, [isPublic ? "verify" : "sign"]);
15356
- }
15357
- if (alg.startsWith("ECDH-ES")) {
15358
- cryptoKey = keyObject.toCryptoKey({
15359
- name: "ECDH",
15360
- namedCurve
15361
- }, extractable, isPublic ? [] : ["deriveBits"]);
15362
- }
15363
- }
15364
- if (!cryptoKey) {
15365
- throw new TypeError("given KeyObject instance cannot be used for this algorithm");
15366
- }
15367
- if (!cached) {
15368
- cache.set(keyObject, { [alg]: cryptoKey });
15369
- } else {
15370
- cached[alg] = cryptoKey;
15371
- }
15372
- return cryptoKey;
15373
- };
15374
- var normalize_key_default = async (key, alg) => {
15375
- if (key instanceof Uint8Array) {
15376
- return key;
15377
- }
15378
- if (isCryptoKey(key)) {
15379
- return key;
15380
- }
15381
- if (isKeyObject(key)) {
15382
- if (key.type === "secret") {
15383
- return key.export();
15384
- }
15385
- if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
15386
- try {
15387
- return handleKeyObject(key, alg);
15388
- } catch (err) {
15389
- if (err instanceof TypeError) {
15390
- throw err;
15391
- }
15392
- }
15393
- }
15394
- let jwk = key.export({ format: "jwk" });
15395
- return handleJWK(key, jwk, alg);
15396
- }
15397
- if (isJWK(key)) {
15398
- if (key.k) {
15399
- return decode(key.k);
15792
+ for (const parameter of protectedHeader.crit) {
15793
+ if (!recognized.has(parameter)) {
15794
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
15795
+ }
15796
+ if (joseHeader[parameter] === void 0) {
15797
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
15798
+ }
15799
+ if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
15800
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
15400
15801
  }
15401
- return handleJWK(key, key, alg, true);
15402
15802
  }
15403
- throw new Error("unreachable");
15404
- };
15803
+ return new Set(protectedHeader.crit);
15804
+ }
15805
+
15806
+ // node_modules/jose/dist/webapi/lib/validate_algorithms.js
15807
+ function validateAlgorithms(option, algorithms) {
15808
+ if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
15809
+ throw new TypeError(`"${option}" option must be an array of strings`);
15810
+ }
15811
+ if (!algorithms) {
15812
+ return void 0;
15813
+ }
15814
+ return new Set(algorithms);
15815
+ }
15405
15816
 
15406
15817
  // node_modules/jose/dist/webapi/lib/check_key_type.js
15407
15818
  var tag = (key) => key?.[Symbol.toStringTag];
@@ -15464,7 +15875,7 @@ var symmetricTypeCheck = (alg, key, usage2) => {
15464
15875
  return;
15465
15876
  throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
15466
15877
  }
15467
- if (!is_key_like_default(key)) {
15878
+ if (!isKeyLike(key)) {
15468
15879
  throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
15469
15880
  }
15470
15881
  if (key.type !== "secret") {
@@ -15478,15 +15889,15 @@ var asymmetricTypeCheck = (alg, key, usage2) => {
15478
15889
  case "sign":
15479
15890
  if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage2))
15480
15891
  return;
15481
- throw new TypeError(`JSON Web Key for this operation be a private JWK`);
15892
+ throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
15482
15893
  case "encrypt":
15483
15894
  case "verify":
15484
15895
  if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage2))
15485
15896
  return;
15486
- throw new TypeError(`JSON Web Key for this operation be a public JWK`);
15897
+ throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
15487
15898
  }
15488
15899
  }
15489
- if (!is_key_like_default(key)) {
15900
+ if (!isKeyLike(key)) {
15490
15901
  throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
15491
15902
  }
15492
15903
  if (key.type === "secret") {
@@ -15498,8 +15909,6 @@ var asymmetricTypeCheck = (alg, key, usage2) => {
15498
15909
  throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
15499
15910
  case "decrypt":
15500
15911
  throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
15501
- default:
15502
- break;
15503
15912
  }
15504
15913
  }
15505
15914
  if (key.type === "private") {
@@ -15508,23 +15917,70 @@ var asymmetricTypeCheck = (alg, key, usage2) => {
15508
15917
  throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
15509
15918
  case "encrypt":
15510
15919
  throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
15511
- default:
15512
- break;
15513
15920
  }
15514
15921
  }
15515
15922
  };
15516
- var check_key_type_default = (alg, key, usage2) => {
15517
- const symmetric = alg.startsWith("HS") || alg === "dir" || alg.startsWith("PBES2") || /^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(alg) || /^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(alg);
15518
- if (symmetric) {
15519
- symmetricTypeCheck(alg, key, usage2);
15520
- } else {
15521
- asymmetricTypeCheck(alg, key, usage2);
15923
+ function checkKeyType(alg, key, usage2) {
15924
+ switch (alg.substring(0, 2)) {
15925
+ case "A1":
15926
+ case "A2":
15927
+ case "di":
15928
+ case "HS":
15929
+ case "PB":
15930
+ symmetricTypeCheck(alg, key, usage2);
15931
+ break;
15932
+ default:
15933
+ asymmetricTypeCheck(alg, key, usage2);
15522
15934
  }
15523
- };
15935
+ }
15936
+
15937
+ // node_modules/jose/dist/webapi/lib/deflate.js
15938
+ function supported(name) {
15939
+ if (typeof globalThis[name] === "undefined") {
15940
+ throw new JOSENotSupported(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${name} API.`);
15941
+ }
15942
+ }
15943
+ async function compress(input) {
15944
+ supported("CompressionStream");
15945
+ const cs = new CompressionStream("deflate-raw");
15946
+ const writer = cs.writable.getWriter();
15947
+ writer.write(input);
15948
+ writer.close();
15949
+ const chunks = [];
15950
+ const reader = cs.readable.getReader();
15951
+ for (; ; ) {
15952
+ const { value, done } = await reader.read();
15953
+ if (done)
15954
+ break;
15955
+ chunks.push(value);
15956
+ }
15957
+ return concat(...chunks);
15958
+ }
15959
+ async function decompress(input, maxLength) {
15960
+ supported("DecompressionStream");
15961
+ const ds = new DecompressionStream("deflate-raw");
15962
+ const writer = ds.writable.getWriter();
15963
+ writer.write(input);
15964
+ writer.close();
15965
+ const chunks = [];
15966
+ let length = 0;
15967
+ const reader = ds.readable.getReader();
15968
+ for (; ; ) {
15969
+ const { value, done } = await reader.read();
15970
+ if (done)
15971
+ break;
15972
+ chunks.push(value);
15973
+ length += value.byteLength;
15974
+ if (maxLength !== Infinity && length > maxLength) {
15975
+ throw new JWEInvalid("Decompressed plaintext exceeded the configured limit");
15976
+ }
15977
+ }
15978
+ return concat(...chunks);
15979
+ }
15524
15980
 
15525
15981
  // node_modules/jose/dist/webapi/jwe/flattened/decrypt.js
15526
15982
  async function flattenedDecrypt(jwe, key, options) {
15527
- if (!is_object_default(jwe)) {
15983
+ if (!isObject(jwe)) {
15528
15984
  throw new JWEInvalid("Flattened JWE must be an object");
15529
15985
  }
15530
15986
  if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) {
@@ -15548,10 +16004,10 @@ async function flattenedDecrypt(jwe, key, options) {
15548
16004
  if (jwe.aad !== void 0 && typeof jwe.aad !== "string") {
15549
16005
  throw new JWEInvalid("JWE AAD incorrect type");
15550
16006
  }
15551
- if (jwe.header !== void 0 && !is_object_default(jwe.header)) {
16007
+ if (jwe.header !== void 0 && !isObject(jwe.header)) {
15552
16008
  throw new JWEInvalid("JWE Shared Unprotected Header incorrect type");
15553
16009
  }
15554
- if (jwe.unprotected !== void 0 && !is_object_default(jwe.unprotected)) {
16010
+ if (jwe.unprotected !== void 0 && !isObject(jwe.unprotected)) {
15555
16011
  throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");
15556
16012
  }
15557
16013
  let parsedProt;
@@ -15563,7 +16019,7 @@ async function flattenedDecrypt(jwe, key, options) {
15563
16019
  throw new JWEInvalid("JWE Protected Header is invalid");
15564
16020
  }
15565
16021
  }
15566
- if (!is_disjoint_default(parsedProt, jwe.header, jwe.unprotected)) {
16022
+ if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) {
15567
16023
  throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");
15568
16024
  }
15569
16025
  const joseHeader = {
@@ -15571,9 +16027,12 @@ async function flattenedDecrypt(jwe, key, options) {
15571
16027
  ...jwe.header,
15572
16028
  ...jwe.unprotected
15573
16029
  };
15574
- validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader);
15575
- if (joseHeader.zip !== void 0) {
15576
- throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
16030
+ validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader);
16031
+ if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") {
16032
+ throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');
16033
+ }
16034
+ if (joseHeader.zip !== void 0 && !parsedProt?.zip) {
16035
+ throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');
15577
16036
  }
15578
16037
  const { alg, enc } = joseHeader;
15579
16038
  if (typeof alg !== "string" || !alg) {
@@ -15582,8 +16041,8 @@ async function flattenedDecrypt(jwe, key, options) {
15582
16041
  if (typeof enc !== "string" || !enc) {
15583
16042
  throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");
15584
16043
  }
15585
- const keyManagementAlgorithms = options && validate_algorithms_default("keyManagementAlgorithms", options.keyManagementAlgorithms);
15586
- const contentEncryptionAlgorithms = options && validate_algorithms_default("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms);
16044
+ const keyManagementAlgorithms = options && validateAlgorithms("keyManagementAlgorithms", options.keyManagementAlgorithms);
16045
+ const contentEncryptionAlgorithms = options && validateAlgorithms("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms);
15587
16046
  if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg) || !keyManagementAlgorithms && alg.startsWith("PBES2")) {
15588
16047
  throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
15589
16048
  }
@@ -15592,68 +16051,57 @@ async function flattenedDecrypt(jwe, key, options) {
15592
16051
  }
15593
16052
  let encryptedKey;
15594
16053
  if (jwe.encrypted_key !== void 0) {
15595
- try {
15596
- encryptedKey = decode(jwe.encrypted_key);
15597
- } catch {
15598
- throw new JWEInvalid("Failed to base64url decode the encrypted_key");
15599
- }
16054
+ encryptedKey = decodeBase64url(jwe.encrypted_key, "encrypted_key", JWEInvalid);
15600
16055
  }
15601
16056
  let resolvedKey = false;
15602
16057
  if (typeof key === "function") {
15603
16058
  key = await key(parsedProt, jwe);
15604
16059
  resolvedKey = true;
15605
16060
  }
15606
- check_key_type_default(alg === "dir" ? enc : alg, key, "decrypt");
15607
- const k = await normalize_key_default(key, alg);
16061
+ checkKeyType(alg === "dir" ? enc : alg, key, "decrypt");
16062
+ const k = await normalizeKey(key, alg);
15608
16063
  let cek;
15609
16064
  try {
15610
- cek = await decrypt_key_management_default(alg, k, encryptedKey, joseHeader, options);
16065
+ cek = await decryptKeyManagement(alg, k, encryptedKey, joseHeader, options);
15611
16066
  } catch (err) {
15612
16067
  if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {
15613
16068
  throw err;
15614
16069
  }
15615
- cek = cek_default(enc);
16070
+ cek = generateCek(enc);
15616
16071
  }
15617
16072
  let iv;
15618
16073
  let tag2;
15619
16074
  if (jwe.iv !== void 0) {
15620
- try {
15621
- iv = decode(jwe.iv);
15622
- } catch {
15623
- throw new JWEInvalid("Failed to base64url decode the iv");
15624
- }
16075
+ iv = decodeBase64url(jwe.iv, "iv", JWEInvalid);
15625
16076
  }
15626
16077
  if (jwe.tag !== void 0) {
15627
- try {
15628
- tag2 = decode(jwe.tag);
15629
- } catch {
15630
- throw new JWEInvalid("Failed to base64url decode the tag");
15631
- }
16078
+ tag2 = decodeBase64url(jwe.tag, "tag", JWEInvalid);
15632
16079
  }
15633
- const protectedHeader = encoder.encode(jwe.protected ?? "");
16080
+ const protectedHeader = jwe.protected !== void 0 ? encode(jwe.protected) : new Uint8Array();
15634
16081
  let additionalData;
15635
16082
  if (jwe.aad !== void 0) {
15636
- additionalData = concat(protectedHeader, encoder.encode("."), encoder.encode(jwe.aad));
16083
+ additionalData = concat(protectedHeader, encode("."), encode(jwe.aad));
15637
16084
  } else {
15638
16085
  additionalData = protectedHeader;
15639
16086
  }
15640
- let ciphertext;
15641
- try {
15642
- ciphertext = decode(jwe.ciphertext);
15643
- } catch {
15644
- throw new JWEInvalid("Failed to base64url decode the ciphertext");
15645
- }
15646
- const plaintext = await decrypt_default(enc, cek, ciphertext, iv, tag2, additionalData);
16087
+ const ciphertext = decodeBase64url(jwe.ciphertext, "ciphertext", JWEInvalid);
16088
+ const plaintext = await decrypt(enc, cek, ciphertext, iv, tag2, additionalData);
15647
16089
  const result = { plaintext };
16090
+ if (joseHeader.zip === "DEF") {
16091
+ const maxDecompressedLength = options?.maxDecompressedLength ?? 25e4;
16092
+ if (maxDecompressedLength === 0) {
16093
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
16094
+ }
16095
+ if (maxDecompressedLength !== Infinity && (!Number.isSafeInteger(maxDecompressedLength) || maxDecompressedLength < 1)) {
16096
+ throw new TypeError("maxDecompressedLength must be 0, a positive safe integer, or Infinity");
16097
+ }
16098
+ result.plaintext = await decompress(plaintext, maxDecompressedLength);
16099
+ }
15648
16100
  if (jwe.protected !== void 0) {
15649
16101
  result.protectedHeader = parsedProt;
15650
16102
  }
15651
16103
  if (jwe.aad !== void 0) {
15652
- try {
15653
- result.additionalAuthenticatedData = decode(jwe.aad);
15654
- } catch {
15655
- throw new JWEInvalid("Failed to base64url decode the aad");
15656
- }
16104
+ result.additionalAuthenticatedData = decodeBase64url(jwe.aad, "aad", JWEInvalid);
15657
16105
  }
15658
16106
  if (jwe.unprotected !== void 0) {
15659
16107
  result.sharedUnprotectedHeader = jwe.unprotected;
@@ -15693,125 +16141,6 @@ async function compactDecrypt(jwe, key, options) {
15693
16141
  return result;
15694
16142
  }
15695
16143
 
15696
- // node_modules/jose/dist/webapi/lib/private_symbols.js
15697
- var unprotected = Symbol();
15698
-
15699
- // node_modules/jose/dist/webapi/lib/key_to_jwk.js
15700
- async function keyToJWK(key) {
15701
- if (isKeyObject(key)) {
15702
- if (key.type === "secret") {
15703
- key = key.export();
15704
- } else {
15705
- return key.export({ format: "jwk" });
15706
- }
15707
- }
15708
- if (key instanceof Uint8Array) {
15709
- return {
15710
- kty: "oct",
15711
- k: encode(key)
15712
- };
15713
- }
15714
- if (!isCryptoKey(key)) {
15715
- throw new TypeError(invalid_key_input_default(key, "CryptoKey", "KeyObject", "Uint8Array"));
15716
- }
15717
- if (!key.extractable) {
15718
- throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
15719
- }
15720
- const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey("jwk", key);
15721
- if (jwk.kty === "AKP") {
15722
- ;
15723
- jwk.alg = alg;
15724
- }
15725
- return jwk;
15726
- }
15727
-
15728
- // node_modules/jose/dist/webapi/key/export.js
15729
- async function exportJWK(key) {
15730
- return keyToJWK(key);
15731
- }
15732
-
15733
- // node_modules/jose/dist/webapi/lib/encrypt_key_management.js
15734
- var encrypt_key_management_default = async (alg, enc, key, providedCek, providedParameters = {}) => {
15735
- let encryptedKey;
15736
- let parameters;
15737
- let cek;
15738
- switch (alg) {
15739
- case "dir": {
15740
- cek = key;
15741
- break;
15742
- }
15743
- case "ECDH-ES":
15744
- case "ECDH-ES+A128KW":
15745
- case "ECDH-ES+A192KW":
15746
- case "ECDH-ES+A256KW": {
15747
- assertCryptoKey(key);
15748
- if (!allowed(key)) {
15749
- throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
15750
- }
15751
- const { apu, apv } = providedParameters;
15752
- let ephemeralKey;
15753
- if (providedParameters.epk) {
15754
- ephemeralKey = await normalize_key_default(providedParameters.epk, alg);
15755
- } else {
15756
- ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey;
15757
- }
15758
- const { x, y, crv, kty } = await exportJWK(ephemeralKey);
15759
- const sharedSecret = await deriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? bitLength2(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
15760
- parameters = { epk: { x, crv, kty } };
15761
- if (kty === "EC")
15762
- parameters.epk.y = y;
15763
- if (apu)
15764
- parameters.apu = encode(apu);
15765
- if (apv)
15766
- parameters.apv = encode(apv);
15767
- if (alg === "ECDH-ES") {
15768
- cek = sharedSecret;
15769
- break;
15770
- }
15771
- cek = providedCek || cek_default(enc);
15772
- const kwAlg = alg.slice(-6);
15773
- encryptedKey = await wrap(kwAlg, sharedSecret, cek);
15774
- break;
15775
- }
15776
- case "RSA-OAEP":
15777
- case "RSA-OAEP-256":
15778
- case "RSA-OAEP-384":
15779
- case "RSA-OAEP-512": {
15780
- cek = providedCek || cek_default(enc);
15781
- assertCryptoKey(key);
15782
- encryptedKey = await encrypt(alg, key, cek);
15783
- break;
15784
- }
15785
- case "PBES2-HS256+A128KW":
15786
- case "PBES2-HS384+A192KW":
15787
- case "PBES2-HS512+A256KW": {
15788
- cek = providedCek || cek_default(enc);
15789
- const { p2c, p2s } = providedParameters;
15790
- ({ encryptedKey, ...parameters } = await wrap2(alg, key, cek, p2c, p2s));
15791
- break;
15792
- }
15793
- case "A128KW":
15794
- case "A192KW":
15795
- case "A256KW": {
15796
- cek = providedCek || cek_default(enc);
15797
- encryptedKey = await wrap(alg, key, cek);
15798
- break;
15799
- }
15800
- case "A128GCMKW":
15801
- case "A192GCMKW":
15802
- case "A256GCMKW": {
15803
- cek = providedCek || cek_default(enc);
15804
- const { iv } = providedParameters;
15805
- ({ encryptedKey, ...parameters } = await wrap3(alg, key, cek, iv));
15806
- break;
15807
- }
15808
- default: {
15809
- throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
15810
- }
15811
- }
15812
- return { cek, encryptedKey, parameters };
15813
- };
15814
-
15815
16144
  // node_modules/jose/dist/webapi/jwe/flattened/encrypt.js
15816
16145
  var FlattenedEncrypt = class {
15817
16146
  #plaintext;
@@ -15829,30 +16158,22 @@ var FlattenedEncrypt = class {
15829
16158
  this.#plaintext = plaintext;
15830
16159
  }
15831
16160
  setKeyManagementParameters(parameters) {
15832
- if (this.#keyManagementParameters) {
15833
- throw new TypeError("setKeyManagementParameters can only be called once");
15834
- }
16161
+ assertNotSet(this.#keyManagementParameters, "setKeyManagementParameters");
15835
16162
  this.#keyManagementParameters = parameters;
15836
16163
  return this;
15837
16164
  }
15838
16165
  setProtectedHeader(protectedHeader) {
15839
- if (this.#protectedHeader) {
15840
- throw new TypeError("setProtectedHeader can only be called once");
15841
- }
16166
+ assertNotSet(this.#protectedHeader, "setProtectedHeader");
15842
16167
  this.#protectedHeader = protectedHeader;
15843
16168
  return this;
15844
16169
  }
15845
16170
  setSharedUnprotectedHeader(sharedUnprotectedHeader) {
15846
- if (this.#sharedUnprotectedHeader) {
15847
- throw new TypeError("setSharedUnprotectedHeader can only be called once");
15848
- }
16171
+ assertNotSet(this.#sharedUnprotectedHeader, "setSharedUnprotectedHeader");
15849
16172
  this.#sharedUnprotectedHeader = sharedUnprotectedHeader;
15850
16173
  return this;
15851
16174
  }
15852
16175
  setUnprotectedHeader(unprotectedHeader) {
15853
- if (this.#unprotectedHeader) {
15854
- throw new TypeError("setUnprotectedHeader can only be called once");
15855
- }
16176
+ assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader");
15856
16177
  this.#unprotectedHeader = unprotectedHeader;
15857
16178
  return this;
15858
16179
  }
@@ -15861,16 +16182,12 @@ var FlattenedEncrypt = class {
15861
16182
  return this;
15862
16183
  }
15863
16184
  setContentEncryptionKey(cek) {
15864
- if (this.#cek) {
15865
- throw new TypeError("setContentEncryptionKey can only be called once");
15866
- }
16185
+ assertNotSet(this.#cek, "setContentEncryptionKey");
15867
16186
  this.#cek = cek;
15868
16187
  return this;
15869
16188
  }
15870
16189
  setInitializationVector(iv) {
15871
- if (this.#iv) {
15872
- throw new TypeError("setInitializationVector can only be called once");
15873
- }
16190
+ assertNotSet(this.#iv, "setInitializationVector");
15874
16191
  this.#iv = iv;
15875
16192
  return this;
15876
16193
  }
@@ -15878,7 +16195,7 @@ var FlattenedEncrypt = class {
15878
16195
  if (!this.#protectedHeader && !this.#unprotectedHeader && !this.#sharedUnprotectedHeader) {
15879
16196
  throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");
15880
16197
  }
15881
- if (!is_disjoint_default(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) {
16198
+ if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) {
15882
16199
  throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
15883
16200
  }
15884
16201
  const joseHeader = {
@@ -15886,9 +16203,12 @@ var FlattenedEncrypt = class {
15886
16203
  ...this.#unprotectedHeader,
15887
16204
  ...this.#sharedUnprotectedHeader
15888
16205
  };
15889
- validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, this.#protectedHeader, joseHeader);
15890
- if (joseHeader.zip !== void 0) {
15891
- throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
16206
+ validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, this.#protectedHeader, joseHeader);
16207
+ if (joseHeader.zip !== void 0 && joseHeader.zip !== "DEF") {
16208
+ throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');
16209
+ }
16210
+ if (joseHeader.zip !== void 0 && !this.#protectedHeader?.zip) {
16211
+ throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');
15892
16212
  }
15893
16213
  const { alg, enc } = joseHeader;
15894
16214
  if (typeof alg !== "string" || !alg) {
@@ -15901,12 +16221,12 @@ var FlattenedEncrypt = class {
15901
16221
  if (this.#cek && (alg === "dir" || alg === "ECDH-ES")) {
15902
16222
  throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`);
15903
16223
  }
15904
- check_key_type_default(alg === "dir" ? enc : alg, key, "encrypt");
16224
+ checkKeyType(alg === "dir" ? enc : alg, key, "encrypt");
15905
16225
  let cek;
15906
16226
  {
15907
16227
  let parameters;
15908
- const k = await normalize_key_default(key, alg);
15909
- ({ cek, encryptedKey, parameters } = await encrypt_key_management_default(alg, enc, k, this.#cek, this.#keyManagementParameters));
16228
+ const k = await normalizeKey(key, alg);
16229
+ ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, this.#cek, this.#keyManagementParameters));
15910
16230
  if (parameters) {
15911
16231
  if (options && unprotected in options) {
15912
16232
  if (!this.#unprotectedHeader) {
@@ -15922,37 +16242,45 @@ var FlattenedEncrypt = class {
15922
16242
  }
15923
16243
  }
15924
16244
  let additionalData;
15925
- let protectedHeader;
16245
+ let protectedHeaderS;
16246
+ let protectedHeaderB;
15926
16247
  let aadMember;
15927
16248
  if (this.#protectedHeader) {
15928
- protectedHeader = encoder.encode(encode(JSON.stringify(this.#protectedHeader)));
16249
+ protectedHeaderS = encode2(JSON.stringify(this.#protectedHeader));
16250
+ protectedHeaderB = encode(protectedHeaderS);
15929
16251
  } else {
15930
- protectedHeader = encoder.encode("");
16252
+ protectedHeaderS = "";
16253
+ protectedHeaderB = new Uint8Array();
15931
16254
  }
15932
16255
  if (this.#aad) {
15933
- aadMember = encode(this.#aad);
15934
- additionalData = concat(protectedHeader, encoder.encode("."), encoder.encode(aadMember));
16256
+ aadMember = encode2(this.#aad);
16257
+ const aadMemberBytes = encode(aadMember);
16258
+ additionalData = concat(protectedHeaderB, encode("."), aadMemberBytes);
15935
16259
  } else {
15936
- additionalData = protectedHeader;
16260
+ additionalData = protectedHeaderB;
15937
16261
  }
15938
- const { ciphertext, tag: tag2, iv } = await encrypt_default(enc, this.#plaintext, cek, this.#iv, additionalData);
16262
+ let plaintext = this.#plaintext;
16263
+ if (joseHeader.zip === "DEF") {
16264
+ plaintext = await compress(plaintext);
16265
+ }
16266
+ const { ciphertext, tag: tag2, iv } = await encrypt(enc, plaintext, cek, this.#iv, additionalData);
15939
16267
  const jwe = {
15940
- ciphertext: encode(ciphertext)
16268
+ ciphertext: encode2(ciphertext)
15941
16269
  };
15942
16270
  if (iv) {
15943
- jwe.iv = encode(iv);
16271
+ jwe.iv = encode2(iv);
15944
16272
  }
15945
16273
  if (tag2) {
15946
- jwe.tag = encode(tag2);
16274
+ jwe.tag = encode2(tag2);
15947
16275
  }
15948
16276
  if (encryptedKey) {
15949
- jwe.encrypted_key = encode(encryptedKey);
16277
+ jwe.encrypted_key = encode2(encryptedKey);
15950
16278
  }
15951
16279
  if (aadMember) {
15952
16280
  jwe.aad = aadMember;
15953
16281
  }
15954
16282
  if (this.#protectedHeader) {
15955
- jwe.protected = decoder.decode(protectedHeader);
16283
+ jwe.protected = protectedHeaderS;
15956
16284
  }
15957
16285
  if (this.#sharedUnprotectedHeader) {
15958
16286
  jwe.unprotected = this.#sharedUnprotectedHeader;
@@ -15964,65 +16292,9 @@ var FlattenedEncrypt = class {
15964
16292
  }
15965
16293
  };
15966
16294
 
15967
- // node_modules/jose/dist/webapi/lib/subtle_dsa.js
15968
- var subtle_dsa_default = (alg, algorithm) => {
15969
- const hash = `SHA-${alg.slice(-3)}`;
15970
- switch (alg) {
15971
- case "HS256":
15972
- case "HS384":
15973
- case "HS512":
15974
- return { hash, name: "HMAC" };
15975
- case "PS256":
15976
- case "PS384":
15977
- case "PS512":
15978
- return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
15979
- case "RS256":
15980
- case "RS384":
15981
- case "RS512":
15982
- return { hash, name: "RSASSA-PKCS1-v1_5" };
15983
- case "ES256":
15984
- case "ES384":
15985
- case "ES512":
15986
- return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
15987
- case "Ed25519":
15988
- case "EdDSA":
15989
- return { name: "Ed25519" };
15990
- case "ML-DSA-44":
15991
- case "ML-DSA-65":
15992
- case "ML-DSA-87":
15993
- return { name: alg };
15994
- default:
15995
- throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
15996
- }
15997
- };
15998
-
15999
- // node_modules/jose/dist/webapi/lib/get_sign_verify_key.js
16000
- var get_sign_verify_key_default = async (alg, key, usage2) => {
16001
- if (key instanceof Uint8Array) {
16002
- if (!alg.startsWith("HS")) {
16003
- throw new TypeError(invalid_key_input_default(key, "CryptoKey", "KeyObject", "JSON Web Key"));
16004
- }
16005
- return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage2]);
16006
- }
16007
- checkSigCryptoKey(key, alg, usage2);
16008
- return key;
16009
- };
16010
-
16011
- // node_modules/jose/dist/webapi/lib/verify.js
16012
- var verify_default = async (alg, key, signature, data) => {
16013
- const cryptoKey = await get_sign_verify_key_default(alg, key, "verify");
16014
- check_key_length_default(alg, cryptoKey);
16015
- const algorithm = subtle_dsa_default(alg, cryptoKey.algorithm);
16016
- try {
16017
- return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
16018
- } catch {
16019
- return false;
16020
- }
16021
- };
16022
-
16023
16295
  // node_modules/jose/dist/webapi/jws/flattened/verify.js
16024
16296
  async function flattenedVerify(jws, key, options) {
16025
- if (!is_object_default(jws)) {
16297
+ if (!isObject(jws)) {
16026
16298
  throw new JWSInvalid("Flattened JWS must be an object");
16027
16299
  }
16028
16300
  if (jws.protected === void 0 && jws.header === void 0) {
@@ -16037,7 +16309,7 @@ async function flattenedVerify(jws, key, options) {
16037
16309
  if (typeof jws.signature !== "string") {
16038
16310
  throw new JWSInvalid("JWS Signature missing or incorrect type");
16039
16311
  }
16040
- if (jws.header !== void 0 && !is_object_default(jws.header)) {
16312
+ if (jws.header !== void 0 && !isObject(jws.header)) {
16041
16313
  throw new JWSInvalid("JWS Unprotected Header incorrect type");
16042
16314
  }
16043
16315
  let parsedProt = {};
@@ -16049,14 +16321,14 @@ async function flattenedVerify(jws, key, options) {
16049
16321
  throw new JWSInvalid("JWS Protected Header is invalid");
16050
16322
  }
16051
16323
  }
16052
- if (!is_disjoint_default(parsedProt, jws.header)) {
16324
+ if (!isDisjoint(parsedProt, jws.header)) {
16053
16325
  throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
16054
16326
  }
16055
16327
  const joseHeader = {
16056
16328
  ...parsedProt,
16057
16329
  ...jws.header
16058
16330
  };
16059
- const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
16331
+ const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
16060
16332
  let b64 = true;
16061
16333
  if (extensions.has("b64")) {
16062
16334
  b64 = parsedProt.b64;
@@ -16068,7 +16340,7 @@ async function flattenedVerify(jws, key, options) {
16068
16340
  if (typeof alg !== "string" || !alg) {
16069
16341
  throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
16070
16342
  }
16071
- const algorithms = options && validate_algorithms_default("algorithms", options.algorithms);
16343
+ const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
16072
16344
  if (algorithms && !algorithms.has(alg)) {
16073
16345
  throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
16074
16346
  }
@@ -16084,26 +16356,17 @@ async function flattenedVerify(jws, key, options) {
16084
16356
  key = await key(parsedProt, jws);
16085
16357
  resolvedKey = true;
16086
16358
  }
16087
- check_key_type_default(alg, key, "verify");
16088
- const data = concat(encoder.encode(jws.protected ?? ""), encoder.encode("."), typeof jws.payload === "string" ? encoder.encode(jws.payload) : jws.payload);
16089
- let signature;
16090
- try {
16091
- signature = decode(jws.signature);
16092
- } catch {
16093
- throw new JWSInvalid("Failed to base64url decode the signature");
16094
- }
16095
- const k = await normalize_key_default(key, alg);
16096
- const verified = await verify_default(alg, k, signature, data);
16359
+ checkKeyType(alg, key, "verify");
16360
+ const data = concat(jws.protected !== void 0 ? encode(jws.protected) : new Uint8Array(), encode("."), typeof jws.payload === "string" ? b64 ? encode(jws.payload) : encoder.encode(jws.payload) : jws.payload);
16361
+ const signature = decodeBase64url(jws.signature, "signature", JWSInvalid);
16362
+ const k = await normalizeKey(key, alg);
16363
+ const verified = await verify(alg, k, signature, data);
16097
16364
  if (!verified) {
16098
16365
  throw new JWSSignatureVerificationFailed();
16099
16366
  }
16100
16367
  let payload;
16101
16368
  if (b64) {
16102
- try {
16103
- payload = decode(jws.payload);
16104
- } catch {
16105
- throw new JWSInvalid("Failed to base64url decode the payload");
16106
- }
16369
+ payload = decodeBase64url(jws.payload, "payload", JWSInvalid);
16107
16370
  } else if (typeof jws.payload === "string") {
16108
16371
  payload = encoder.encode(jws.payload);
16109
16372
  } else {
@@ -16142,17 +16405,15 @@ async function compactVerify(jws, key, options) {
16142
16405
  return result;
16143
16406
  }
16144
16407
 
16145
- // node_modules/jose/dist/webapi/lib/epoch.js
16146
- var epoch_default = (date) => Math.floor(date.getTime() / 1e3);
16147
-
16148
- // node_modules/jose/dist/webapi/lib/secs.js
16408
+ // node_modules/jose/dist/webapi/lib/jwt_claims_set.js
16409
+ var epoch = (date) => Math.floor(date.getTime() / 1e3);
16149
16410
  var minute = 60;
16150
16411
  var hour = minute * 60;
16151
16412
  var day = hour * 24;
16152
16413
  var week = day * 7;
16153
16414
  var year = day * 365.25;
16154
16415
  var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
16155
- var secs_default = (str) => {
16416
+ function secs(str) {
16156
16417
  const matched = REGEX.exec(str);
16157
16418
  if (!matched || matched[4] && matched[1]) {
16158
16419
  throw new TypeError("Invalid time period format");
@@ -16200,9 +16461,7 @@ var secs_default = (str) => {
16200
16461
  return -numericDate;
16201
16462
  }
16202
16463
  return numericDate;
16203
- };
16204
-
16205
- // node_modules/jose/dist/webapi/lib/jwt_claims_set.js
16464
+ }
16206
16465
  function validateInput(label, input) {
16207
16466
  if (!Number.isFinite(input)) {
16208
16467
  throw new TypeError(`Invalid ${label} input`);
@@ -16230,7 +16489,7 @@ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
16230
16489
  payload = JSON.parse(decoder.decode(encodedPayload));
16231
16490
  } catch {
16232
16491
  }
16233
- if (!is_object_default(payload)) {
16492
+ if (!isObject(payload)) {
16234
16493
  throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
16235
16494
  }
16236
16495
  const { typ } = options;
@@ -16264,7 +16523,7 @@ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
16264
16523
  let tolerance;
16265
16524
  switch (typeof options.clockTolerance) {
16266
16525
  case "string":
16267
- tolerance = secs_default(options.clockTolerance);
16526
+ tolerance = secs(options.clockTolerance);
16268
16527
  break;
16269
16528
  case "number":
16270
16529
  tolerance = options.clockTolerance;
@@ -16276,7 +16535,7 @@ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
16276
16535
  throw new TypeError("Invalid clockTolerance option type");
16277
16536
  }
16278
16537
  const { currentDate } = options;
16279
- const now = epoch_default(currentDate || /* @__PURE__ */ new Date());
16538
+ const now = epoch(currentDate || /* @__PURE__ */ new Date());
16280
16539
  if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") {
16281
16540
  throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid");
16282
16541
  }
@@ -16298,7 +16557,7 @@ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
16298
16557
  }
16299
16558
  if (maxTokenAge) {
16300
16559
  const age = now - payload.iat;
16301
- const max = typeof maxTokenAge === "number" ? maxTokenAge : secs_default(maxTokenAge);
16560
+ const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
16302
16561
  if (age - tolerance > max) {
16303
16562
  throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed");
16304
16563
  }
@@ -16311,7 +16570,7 @@ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
16311
16570
  var JWTClaimsBuilder = class {
16312
16571
  #payload;
16313
16572
  constructor(payload) {
16314
- if (!is_object_default(payload)) {
16573
+ if (!isObject(payload)) {
16315
16574
  throw new TypeError("JWT Claims Set MUST be an object");
16316
16575
  }
16317
16576
  this.#payload = structuredClone(payload);
@@ -16344,27 +16603,27 @@ var JWTClaimsBuilder = class {
16344
16603
  if (typeof value === "number") {
16345
16604
  this.#payload.nbf = validateInput("setNotBefore", value);
16346
16605
  } else if (value instanceof Date) {
16347
- this.#payload.nbf = validateInput("setNotBefore", epoch_default(value));
16606
+ this.#payload.nbf = validateInput("setNotBefore", epoch(value));
16348
16607
  } else {
16349
- this.#payload.nbf = epoch_default(/* @__PURE__ */ new Date()) + secs_default(value);
16608
+ this.#payload.nbf = epoch(/* @__PURE__ */ new Date()) + secs(value);
16350
16609
  }
16351
16610
  }
16352
16611
  set exp(value) {
16353
16612
  if (typeof value === "number") {
16354
16613
  this.#payload.exp = validateInput("setExpirationTime", value);
16355
16614
  } else if (value instanceof Date) {
16356
- this.#payload.exp = validateInput("setExpirationTime", epoch_default(value));
16615
+ this.#payload.exp = validateInput("setExpirationTime", epoch(value));
16357
16616
  } else {
16358
- this.#payload.exp = epoch_default(/* @__PURE__ */ new Date()) + secs_default(value);
16617
+ this.#payload.exp = epoch(/* @__PURE__ */ new Date()) + secs(value);
16359
16618
  }
16360
16619
  }
16361
16620
  set iat(value) {
16362
- if (typeof value === "undefined") {
16363
- this.#payload.iat = epoch_default(/* @__PURE__ */ new Date());
16621
+ if (value === void 0) {
16622
+ this.#payload.iat = epoch(/* @__PURE__ */ new Date());
16364
16623
  } else if (value instanceof Date) {
16365
- this.#payload.iat = validateInput("setIssuedAt", epoch_default(value));
16624
+ this.#payload.iat = validateInput("setIssuedAt", epoch(value));
16366
16625
  } else if (typeof value === "string") {
16367
- this.#payload.iat = validateInput("setIssuedAt", epoch_default(/* @__PURE__ */ new Date()) + secs_default(value));
16626
+ this.#payload.iat = validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(value));
16368
16627
  } else {
16369
16628
  this.#payload.iat = validateInput("setIssuedAt", value);
16370
16629
  }
@@ -16434,14 +16693,6 @@ var CompactEncrypt = class {
16434
16693
  }
16435
16694
  };
16436
16695
 
16437
- // node_modules/jose/dist/webapi/lib/sign.js
16438
- var sign_default = async (alg, key, data) => {
16439
- const cryptoKey = await get_sign_verify_key_default(alg, key, "sign");
16440
- check_key_length_default(alg, cryptoKey);
16441
- const signature = await crypto.subtle.sign(subtle_dsa_default(alg, cryptoKey.algorithm), cryptoKey, data);
16442
- return new Uint8Array(signature);
16443
- };
16444
-
16445
16696
  // node_modules/jose/dist/webapi/jws/flattened/sign.js
16446
16697
  var FlattenedSign = class {
16447
16698
  #payload;
@@ -16454,16 +16705,12 @@ var FlattenedSign = class {
16454
16705
  this.#payload = payload;
16455
16706
  }
16456
16707
  setProtectedHeader(protectedHeader) {
16457
- if (this.#protectedHeader) {
16458
- throw new TypeError("setProtectedHeader can only be called once");
16459
- }
16708
+ assertNotSet(this.#protectedHeader, "setProtectedHeader");
16460
16709
  this.#protectedHeader = protectedHeader;
16461
16710
  return this;
16462
16711
  }
16463
16712
  setUnprotectedHeader(unprotectedHeader) {
16464
- if (this.#unprotectedHeader) {
16465
- throw new TypeError("setUnprotectedHeader can only be called once");
16466
- }
16713
+ assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader");
16467
16714
  this.#unprotectedHeader = unprotectedHeader;
16468
16715
  return this;
16469
16716
  }
@@ -16471,14 +16718,14 @@ var FlattenedSign = class {
16471
16718
  if (!this.#protectedHeader && !this.#unprotectedHeader) {
16472
16719
  throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
16473
16720
  }
16474
- if (!is_disjoint_default(this.#protectedHeader, this.#unprotectedHeader)) {
16721
+ if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) {
16475
16722
  throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
16476
16723
  }
16477
16724
  const joseHeader = {
16478
16725
  ...this.#protectedHeader,
16479
16726
  ...this.#unprotectedHeader
16480
16727
  };
16481
- const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader);
16728
+ const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader);
16482
16729
  let b64 = true;
16483
16730
  if (extensions.has("b64")) {
16484
16731
  b64 = this.#protectedHeader.b64;
@@ -16490,32 +16737,37 @@ var FlattenedSign = class {
16490
16737
  if (typeof alg !== "string" || !alg) {
16491
16738
  throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
16492
16739
  }
16493
- check_key_type_default(alg, key, "sign");
16494
- let payload = this.#payload;
16740
+ checkKeyType(alg, key, "sign");
16741
+ let payloadS;
16742
+ let payloadB;
16495
16743
  if (b64) {
16496
- payload = encoder.encode(encode(payload));
16744
+ payloadS = encode2(this.#payload);
16745
+ payloadB = encode(payloadS);
16746
+ } else {
16747
+ payloadB = this.#payload;
16748
+ payloadS = "";
16497
16749
  }
16498
- let protectedHeader;
16750
+ let protectedHeaderString;
16751
+ let protectedHeaderBytes;
16499
16752
  if (this.#protectedHeader) {
16500
- protectedHeader = encoder.encode(encode(JSON.stringify(this.#protectedHeader)));
16753
+ protectedHeaderString = encode2(JSON.stringify(this.#protectedHeader));
16754
+ protectedHeaderBytes = encode(protectedHeaderString);
16501
16755
  } else {
16502
- protectedHeader = encoder.encode("");
16756
+ protectedHeaderString = "";
16757
+ protectedHeaderBytes = new Uint8Array();
16503
16758
  }
16504
- const data = concat(protectedHeader, encoder.encode("."), payload);
16505
- const k = await normalize_key_default(key, alg);
16506
- const signature = await sign_default(alg, k, data);
16759
+ const data = concat(protectedHeaderBytes, encode("."), payloadB);
16760
+ const k = await normalizeKey(key, alg);
16761
+ const signature = await sign(alg, k, data);
16507
16762
  const jws = {
16508
- signature: encode(signature),
16509
- payload: ""
16763
+ signature: encode2(signature),
16764
+ payload: payloadS
16510
16765
  };
16511
- if (b64) {
16512
- jws.payload = decoder.decode(payload);
16513
- }
16514
16766
  if (this.#unprotectedHeader) {
16515
16767
  jws.header = this.#unprotectedHeader;
16516
16768
  }
16517
16769
  if (this.#protectedHeader) {
16518
- jws.protected = decoder.decode(protectedHeader);
16770
+ jws.protected = protectedHeaderString;
16519
16771
  }
16520
16772
  return jws;
16521
16773
  }
@@ -16631,30 +16883,22 @@ var EncryptJWT = class {
16631
16883
  return this;
16632
16884
  }
16633
16885
  setProtectedHeader(protectedHeader) {
16634
- if (this.#protectedHeader) {
16635
- throw new TypeError("setProtectedHeader can only be called once");
16636
- }
16886
+ assertNotSet(this.#protectedHeader, "setProtectedHeader");
16637
16887
  this.#protectedHeader = protectedHeader;
16638
16888
  return this;
16639
16889
  }
16640
16890
  setKeyManagementParameters(parameters) {
16641
- if (this.#keyManagementParameters) {
16642
- throw new TypeError("setKeyManagementParameters can only be called once");
16643
- }
16891
+ assertNotSet(this.#keyManagementParameters, "setKeyManagementParameters");
16644
16892
  this.#keyManagementParameters = parameters;
16645
16893
  return this;
16646
16894
  }
16647
16895
  setContentEncryptionKey(cek) {
16648
- if (this.#cek) {
16649
- throw new TypeError("setContentEncryptionKey can only be called once");
16650
- }
16896
+ assertNotSet(this.#cek, "setContentEncryptionKey");
16651
16897
  this.#cek = cek;
16652
16898
  return this;
16653
16899
  }
16654
16900
  setInitializationVector(iv) {
16655
- if (this.#iv) {
16656
- throw new TypeError("setInitializationVector can only be called once");
16657
- }
16901
+ assertNotSet(this.#iv, "setInitializationVector");
16658
16902
  this.#iv = iv;
16659
16903
  return this;
16660
16904
  }
@@ -16715,7 +16959,7 @@ function decodeProtectedHeader(token) {
16715
16959
  throw new Error();
16716
16960
  }
16717
16961
  const result = JSON.parse(decoder.decode(decode(protectedB64u)));
16718
- if (!is_object_default(result)) {
16962
+ if (!isObject(result)) {
16719
16963
  throw new Error();
16720
16964
  }
16721
16965
  return result;
@@ -16747,7 +16991,7 @@ function decodeJwt(jwt2) {
16747
16991
  } catch {
16748
16992
  throw new JWTInvalid("Failed to parse the decoded payload as JSON");
16749
16993
  }
16750
- if (!is_object_default(result))
16994
+ if (!isObject(result))
16751
16995
  throw new JWTInvalid("Invalid JWT Claims Set");
16752
16996
  return result;
16753
16997
  }
@@ -16767,10 +17011,10 @@ async function verifyJWT(jwt2, secret, options) {
16767
17011
  return await jwtVerify(jwt2, secret, options);
16768
17012
  }
16769
17013
  async function signJWT(payload, secret, options) {
16770
- const sign = new SignJWT(payload).setProtectedHeader({
17014
+ const sign2 = new SignJWT(payload).setProtectedHeader({
16771
17015
  alg: options?.alg ? options?.alg : "HS256"
16772
17016
  }).setIssuedAt(options?.iat).setIssuer(options?.iss ? options?.iss : "urn:example:issuer").setAudience(options?.aud ? options?.aud : "urn:example:audience").setExpirationTime(options?.exp ? options?.exp : "2h");
16773
- return sign.sign(secret, options?.options);
17017
+ return sign2.sign(secret, options?.options);
16774
17018
  }
16775
17019
  function decodeProtectedHeaderJWT(token) {
16776
17020
  return decodeProtectedHeader(token);
@@ -16780,9 +17024,9 @@ function decodeJWT(jwt2) {
16780
17024
  }
16781
17025
 
16782
17026
  // src/services/utils/jwt.ts
16783
- var import_node_crypto5 = require("node:crypto");
17027
+ var import_node_crypto6 = require("node:crypto");
16784
17028
  var jwt = {
16785
- createSecretKey: import_node_crypto5.createSecretKey,
17029
+ createSecretKey: import_node_crypto6.createSecretKey,
16786
17030
  decode(jwt2) {
16787
17031
  return decodeJWT(jwt2);
16788
17032
  },
@@ -17071,7 +17315,7 @@ var Miqro = class _Miqro {
17071
17315
  this.listener = async (data) => {
17072
17316
  try {
17073
17317
  const msg = data;
17074
- if (msg && msg.action && msg.type === MiqroApplicationMessageType && msg.target === this.options.name, msg.fromPID !== process.pid, msg.action === "reload" || msg.action === "restart") {
17318
+ if (msg && msg.action && msg.type === MiqroApplicationMessageType && msg.target === this.options.name && msg.fromPID !== process.pid && (msg.action === "reload" || msg.action === "restart")) {
17075
17319
  this.logger?.debug("remote server message from [%s] [%s]", msg.fromPID, msg.action);
17076
17320
  switch (msg.action) {
17077
17321
  case "reload":
@@ -17081,7 +17325,7 @@ var Miqro = class _Miqro {
17081
17325
  await this.restart(true);
17082
17326
  break;
17083
17327
  default:
17084
- throw new Error("unsopported message for ApplicaitonServer");
17328
+ throw new Error("unsupported message for ApplicationServer");
17085
17329
  }
17086
17330
  }
17087
17331
  } catch (e) {