@rivetkit/supabase 0.0.0-main.3118df2 → 0.0.0-main.79e97f1

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 (3) hide show
  1. package/dist/mod.js +2494 -1715
  2. package/dist/mod.mjs +2494 -1715
  3. package/package.json +3 -3
package/dist/mod.js CHANGED
@@ -508,7 +508,7 @@ function unsupportedFeature(feature) {
508
508
  );
509
509
  }
510
510
 
511
- // ../rivetkit/dist/tsup/chunk-6HYOPKO3.js
511
+ // ../rivetkit/dist/tsup/chunk-Y5BCFECV.js
512
512
  var import_pino = require("pino");
513
513
 
514
514
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/classic/external.js
@@ -13181,7 +13181,9 @@ var classic_default = external_exports;
13181
13181
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/index.js
13182
13182
  var v4_default = classic_default;
13183
13183
 
13184
- // ../rivetkit/dist/tsup/chunk-6HYOPKO3.js
13184
+ // ../rivetkit/dist/tsup/chunk-Y5BCFECV.js
13185
+ var cbor = __toESM(require("cbor-x"), 1);
13186
+ var import_invariant = __toESM(require_invariant(), 1);
13185
13187
  var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
13186
13188
  var getRivetEndpoint = () => getEnvUniversal("RIVET_ENDPOINT");
13187
13189
  var getRivetToken = () => getEnvUniversal("RIVET_TOKEN");
@@ -13344,7 +13346,7 @@ function noopNext() {
13344
13346
  }
13345
13347
  var package_default = {
13346
13348
  name: "rivetkit",
13347
- version: "0.0.0-main.3118df2",
13349
+ version: "0.0.0-main.79e97f1",
13348
13350
  description: "Lightweight libraries for building stateful actors on edge platforms",
13349
13351
  license: "Apache-2.0",
13350
13352
  keywords: [
@@ -13416,6 +13418,16 @@ var package_default = {
13416
13418
  default: "./dist/tsup/db/drizzle.cjs"
13417
13419
  }
13418
13420
  },
13421
+ "./unstable/migrations": {
13422
+ import: {
13423
+ types: "./dist/tsup/unstable/migrations.d.ts",
13424
+ default: "./dist/tsup/unstable/migrations.js"
13425
+ },
13426
+ require: {
13427
+ types: "./dist/tsup/unstable/migrations.d.cts",
13428
+ default: "./dist/tsup/unstable/migrations.cjs"
13429
+ }
13430
+ },
13419
13431
  "./dynamic": {
13420
13432
  import: {
13421
13433
  types: "./dist/tsup/dynamic/mod.d.ts",
@@ -13515,7 +13527,7 @@ var package_default = {
13515
13527
  "./dist/tsup/chunk-*.cjs"
13516
13528
  ],
13517
13529
  scripts: {
13518
- build: "tsup src/mod.ts src/client/mod.ts src/common/log.ts src/common/websocket.ts src/actor/errors.ts src/utils.ts src/workflow/mod.ts src/test/mod.ts src/inspector/mod.ts src/inspector-tab/mod.ts src/db/mod.ts src/db/drizzle.ts src/dynamic/mod.ts && tsup src/agent-os/index.ts --no-clean --out-dir dist/tsup/agent-os",
13530
+ build: "tsup src/mod.ts src/client/mod.ts src/common/log.ts src/common/websocket.ts src/actor/errors.ts src/utils.ts src/workflow/mod.ts src/test/mod.ts src/inspector/mod.ts src/inspector-tab/mod.ts src/db/mod.ts src/db/drizzle.ts src/dynamic/mod.ts src/unstable/migrations.ts && tsup src/agent-os/index.ts --no-clean --out-dir dist/tsup/agent-os",
13519
13531
  "build:browser": "tsup --config tsup.browser.config.ts",
13520
13532
  "check-types": "tsc --noEmit",
13521
13533
  lint: "biome check . && pnpm run check:test-skips && pnpm run check:wait-for-comments",
@@ -13741,1633 +13753,1766 @@ function quoteLogfmtString(value) {
13741
13753
  }
13742
13754
  return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
13743
13755
  }
13744
- var VERSION = package_default.version;
13745
- var _userAgent;
13746
- function httpUserAgent() {
13747
- if (_userAgent !== void 0) {
13748
- return _userAgent;
13756
+ function uint8ArrayToBase642(uint8Array) {
13757
+ if (typeof Buffer !== "undefined") {
13758
+ return Buffer.from(uint8Array).toString("base64");
13749
13759
  }
13750
- let userAgent = `RivetKit/${VERSION}`;
13751
- const navigatorObj = typeof navigator !== "undefined" ? navigator : void 0;
13752
- if (navigatorObj == null ? void 0 : navigatorObj.userAgent) userAgent += ` ${navigatorObj.userAgent}`;
13753
- _userAgent = userAgent;
13754
- return userAgent;
13755
- }
13756
- function getEnvUniversal(key) {
13757
- if (typeof Deno !== "undefined") {
13758
- return Deno.env.get(key);
13759
- } else if (typeof process !== "undefined") {
13760
- return process.env[key];
13760
+ let binary = "";
13761
+ const len = uint8Array.byteLength;
13762
+ for (let i = 0; i < len; i++) {
13763
+ binary += String.fromCharCode(uint8Array[i]);
13761
13764
  }
13765
+ return btoa(binary);
13762
13766
  }
13763
- function toUint8Array(data) {
13764
- if (data instanceof Uint8Array) {
13765
- return data;
13766
- } else if (data instanceof ArrayBuffer) {
13767
- return new Uint8Array(data);
13768
- } else if (ArrayBuffer.isView(data)) {
13769
- return new Uint8Array(
13770
- data.buffer.slice(
13771
- data.byteOffset,
13772
- data.byteOffset + data.byteLength
13773
- )
13774
- );
13767
+ function contentTypeForEncoding(encoding) {
13768
+ if (encoding === "json") {
13769
+ return "application/json";
13770
+ } else if (encoding === "cbor" || encoding === "bare") {
13771
+ return "application/octet-stream";
13775
13772
  } else {
13776
- throw new TypeError("Input must be ArrayBuffer or ArrayBufferView");
13773
+ assertUnreachable(encoding);
13777
13774
  }
13778
13775
  }
13779
- function promiseWithResolvers(onReject) {
13780
- let resolve;
13781
- let reject;
13782
- const promise2 = new Promise((res, rej) => {
13783
- resolve = res;
13784
- reject = rej;
13785
- });
13786
- promise2.catch(onReject);
13787
- return { promise: promise2, resolve, reject };
13776
+ function encodeCborCompat(value) {
13777
+ return cbor.encode(encodeJsonCompatValue(value));
13788
13778
  }
13789
- function bufferToArrayBuffer(buf) {
13790
- return buf.buffer.slice(
13791
- buf.byteOffset,
13792
- buf.byteOffset + buf.byteLength
13793
- );
13779
+ function decodeCborCompat(buffer) {
13780
+ return reviveJsonCompatValue(cbor.decode(buffer));
13794
13781
  }
13795
- function combineUrlPath(endpoint, path2, queryParams) {
13796
- const baseUrl = new URL(endpoint);
13797
- const pathParts = path2.split("?");
13798
- const pathOnly = pathParts[0];
13799
- const existingQuery = pathParts[1] || "";
13800
- const basePath = baseUrl.pathname.replace(/\/$/, "");
13801
- const cleanPath = pathOnly.startsWith("/") ? pathOnly : `/${pathOnly}`;
13802
- const fullPath = (basePath + cleanPath).replace(/\/\//g, "/");
13803
- const queryParts = [];
13804
- if (existingQuery) {
13805
- queryParts.push(existingQuery);
13806
- }
13807
- if (queryParams) {
13808
- for (const [key, value] of Object.entries(queryParams)) {
13809
- if (value !== void 0) {
13810
- queryParts.push(
13811
- `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
13812
- );
13813
- }
13782
+ function serializeWithEncoding(encoding, value, versionedDataHandler, version2, zodSchema, toJson, toBare) {
13783
+ if (encoding === "json") {
13784
+ const jsonValue = toJson(value);
13785
+ const validated = zodSchema.parse(jsonValue);
13786
+ return jsonStringifyCompat(validated);
13787
+ } else if (encoding === "cbor") {
13788
+ const jsonValue = toJson(value);
13789
+ const validated = zodSchema.parse(jsonValue);
13790
+ return cbor.encode(validated);
13791
+ } else if (encoding === "bare") {
13792
+ if (!versionedDataHandler) {
13793
+ throw new Error(
13794
+ "VersionedDataHandler is required for 'bare' encoding"
13795
+ );
13814
13796
  }
13815
- }
13816
- const fullQuery = queryParts.length > 0 ? `?${queryParts.join("&")}` : "";
13817
- return `${baseUrl.protocol}//${baseUrl.host}${fullPath}${fullQuery}`;
13818
- }
13819
-
13820
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/imports/dev.node.js
13821
- var DEV = process.env.NODE_ENV === "development";
13822
-
13823
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/util/assert.js
13824
- var V8Error = Error;
13825
- function assert2(test, message = "") {
13826
- if (!test) {
13827
- const e = new AssertionError(message);
13828
- V8Error.captureStackTrace?.(e, assert2);
13829
- throw e;
13797
+ if (version2 === void 0) {
13798
+ throw new Error("version is required for 'bare' encoding");
13799
+ }
13800
+ const bareValue = toBare(value);
13801
+ return versionedDataHandler.serializeWithEmbeddedVersion(
13802
+ bareValue,
13803
+ version2
13804
+ );
13805
+ } else {
13806
+ assertUnreachable(encoding);
13830
13807
  }
13831
13808
  }
13832
- var AssertionError = class extends Error {
13833
- constructor() {
13834
- super(...arguments);
13835
- this.name = "AssertionError";
13809
+ function deserializeWithEncoding(encoding, buffer, versionedDataHandler, zodSchema, fromJson, fromBare) {
13810
+ if (encoding === "json") {
13811
+ let parsed;
13812
+ if (typeof buffer === "string") {
13813
+ parsed = jsonParseCompat(buffer);
13814
+ } else {
13815
+ const decoder = new TextDecoder("utf-8");
13816
+ const jsonString = decoder.decode(buffer);
13817
+ parsed = jsonParseCompat(jsonString);
13818
+ }
13819
+ const validated = zodSchema.parse(parsed);
13820
+ return fromJson(validated);
13821
+ } else if (encoding === "cbor") {
13822
+ (0, import_invariant.default)(
13823
+ typeof buffer !== "string",
13824
+ "buffer cannot be string for cbor encoding"
13825
+ );
13826
+ const decoded = decodeCborCompat(buffer);
13827
+ const validated = zodSchema.parse(decoded);
13828
+ return fromJson(validated);
13829
+ } else if (encoding === "bare") {
13830
+ (0, import_invariant.default)(
13831
+ typeof buffer !== "string",
13832
+ "buffer cannot be string for bare encoding"
13833
+ );
13834
+ if (!versionedDataHandler) {
13835
+ throw new Error(
13836
+ "VersionedDataHandler is required for 'bare' encoding"
13837
+ );
13838
+ }
13839
+ const bareValue = versionedDataHandler.deserializeWithEmbeddedVersion(buffer);
13840
+ return fromBare(bareValue);
13841
+ } else {
13842
+ assertUnreachable(encoding);
13836
13843
  }
13837
- };
13838
-
13839
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/util/validator.js
13840
- function isU8(val) {
13841
- return val === (val & 255);
13842
- }
13843
- function isU32(val) {
13844
- return val === val >>> 0;
13845
13844
  }
13846
- function isU64(val) {
13847
- return val === BigInt.asUintN(64, val);
13845
+ var JSON_COMPAT_BIGINT = "$BigInt";
13846
+ var JSON_COMPAT_ARRAY_BUFFER = "$ArrayBuffer";
13847
+ var JSON_COMPAT_UINT8_ARRAY = "$Uint8Array";
13848
+ var JSON_COMPAT_UNDEFINED = "$Undefined";
13849
+ var JSON_COMPAT_SET = "$Set";
13850
+ function isTypedArray(value) {
13851
+ return value instanceof Uint8ClampedArray || value instanceof Uint16Array || value instanceof Uint32Array || value instanceof BigUint64Array || value instanceof Int8Array || value instanceof Int16Array || value instanceof Int32Array || value instanceof BigInt64Array || value instanceof Float32Array || value instanceof Float64Array;
13848
13852
  }
13849
-
13850
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/util/constants.js
13851
- var TEXT_DECODER_THRESHOLD = 256;
13852
- var TEXT_ENCODER_THRESHOLD = 256;
13853
- var INT_SAFE_MAX_BYTE_COUNT = 8;
13854
- var UINT_MAX_BYTE_COUNT = 10;
13855
- var UINT_SAFE32_MAX_BYTE_COUNT = 5;
13856
- var INVALID_UTF8_STRING = "invalid UTF-8 string";
13857
- var NON_CANONICAL_REPRESENTATION = "must be canonical";
13858
- var TOO_LARGE_BUFFER = "too large buffer";
13859
- var TOO_LARGE_NUMBER = "too large number";
13860
-
13861
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/core/bare-error.js
13862
- var BareError = class extends Error {
13863
- constructor(offset, issue2, opts) {
13864
- super(`(byte:${offset}) ${issue2}`);
13865
- this.name = "BareError";
13866
- this.issue = issue2;
13867
- this.offset = offset;
13868
- this.cause = opts?.cause;
13869
- }
13870
- };
13871
-
13872
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/core/byte-cursor.js
13873
- var ByteCursor = class {
13874
- /**
13875
- * @throws {BareError} Buffer exceeds `config.maxBufferLength`
13876
- */
13877
- constructor(bytes, config3) {
13878
- this.offset = 0;
13879
- if (bytes.length > config3.maxBufferLength) {
13880
- throw new BareError(0, TOO_LARGE_BUFFER);
13881
- }
13882
- this.bytes = bytes;
13883
- this.config = config3;
13884
- this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.length);
13853
+ function assertJsonCompatValue(value, path2 = "") {
13854
+ var _a2;
13855
+ if (value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
13856
+ return;
13885
13857
  }
13886
- };
13887
- function check2(bc, min) {
13888
- if (DEV) {
13889
- assert2(isU32(min));
13858
+ if (typeof value === "function") {
13859
+ throw new TypeError(
13860
+ `Value at ${path2 || "root"} is a function and is not CBOR serializable`
13861
+ );
13890
13862
  }
13891
- if (bc.offset + min > bc.bytes.length) {
13892
- throw new BareError(bc.offset, "missing bytes");
13863
+ if (typeof value === "symbol") {
13864
+ throw new TypeError(
13865
+ `Value at ${path2 || "root"} is a symbol and is not CBOR serializable`
13866
+ );
13893
13867
  }
13894
- }
13895
- function reserve(bc, min) {
13896
- if (DEV) {
13897
- assert2(isU32(min));
13868
+ if (value instanceof Date || value instanceof RegExp || value instanceof Error || value instanceof ArrayBuffer || value instanceof Uint8Array || isTypedArray(value)) {
13869
+ return;
13898
13870
  }
13899
- const minLen = bc.offset + min | 0;
13900
- if (minLen > bc.bytes.length) {
13901
- grow(bc, minLen);
13871
+ if (value instanceof WeakMap) {
13872
+ throw new TypeError(
13873
+ `Value at ${path2 || "root"} is a WeakMap and is not CBOR serializable`
13874
+ );
13902
13875
  }
13903
- }
13904
- function grow(bc, minLen) {
13905
- if (minLen > bc.config.maxBufferLength) {
13906
- throw new BareError(0, TOO_LARGE_BUFFER);
13876
+ if (value instanceof WeakSet) {
13877
+ throw new TypeError(
13878
+ `Value at ${path2 || "root"} is a WeakSet and is not CBOR serializable`
13879
+ );
13907
13880
  }
13908
- const buffer = bc.bytes.buffer;
13909
- let newBytes;
13910
- if (isEs2024ArrayBufferLike(buffer) && // Make sure that the view covers the end of the buffer.
13911
- // If it is not the case, this indicates that the user don't want
13912
- // to override the trailing bytes.
13913
- bc.bytes.byteOffset + bc.bytes.byteLength === buffer.byteLength && bc.bytes.byteLength + minLen <= buffer.maxByteLength) {
13914
- const newLen = Math.min(minLen << 1, bc.config.maxBufferLength, buffer.maxByteLength);
13915
- if (buffer instanceof ArrayBuffer) {
13916
- buffer.resize(newLen);
13917
- } else {
13918
- buffer.grow(newLen);
13919
- }
13920
- newBytes = new Uint8Array(buffer, bc.bytes.byteOffset, newLen);
13921
- } else {
13922
- const newLen = Math.min(minLen << 1, bc.config.maxBufferLength);
13923
- newBytes = new Uint8Array(newLen);
13924
- newBytes.set(bc.bytes);
13925
- }
13926
- bc.bytes = newBytes;
13927
- bc.view = new DataView(newBytes.buffer);
13928
- }
13929
- function isEs2024ArrayBufferLike(buffer) {
13930
- return "maxByteLength" in buffer;
13931
- }
13932
-
13933
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/fixed-primitive.js
13934
- function readBool(bc) {
13935
- const val = readU8(bc);
13936
- if (val > 1) {
13937
- bc.offset--;
13938
- throw new BareError(bc.offset, "a bool must be equal to 0 or 1");
13939
- }
13940
- return val > 0;
13941
- }
13942
- function writeBool(bc, x) {
13943
- writeU8(bc, x ? 1 : 0);
13944
- }
13945
- function readU8(bc) {
13946
- check2(bc, 1);
13947
- return bc.bytes[bc.offset++];
13948
- }
13949
- function writeU8(bc, x) {
13950
- if (DEV) {
13951
- assert2(isU8(x), TOO_LARGE_NUMBER);
13881
+ if (value instanceof WeakRef) {
13882
+ throw new TypeError(
13883
+ `Value at ${path2 || "root"} is a WeakRef and is not CBOR serializable`
13884
+ );
13952
13885
  }
13953
- reserve(bc, 1);
13954
- bc.bytes[bc.offset++] = x;
13955
- }
13956
- function readU32(bc) {
13957
- check2(bc, 4);
13958
- const result = bc.view.getUint32(bc.offset, true);
13959
- bc.offset += 4;
13960
- return result;
13961
- }
13962
- function readU64(bc) {
13963
- check2(bc, 8);
13964
- const result = bc.view.getBigUint64(bc.offset, true);
13965
- bc.offset += 8;
13966
- return result;
13967
- }
13968
- function writeU64(bc, x) {
13969
- if (DEV) {
13970
- assert2(isU64(x), TOO_LARGE_NUMBER);
13886
+ if (value instanceof Promise) {
13887
+ throw new TypeError(
13888
+ `Value at ${path2 || "root"} is a Promise and is not CBOR serializable`
13889
+ );
13971
13890
  }
13972
- reserve(bc, 8);
13973
- bc.view.setBigUint64(bc.offset, x, true);
13974
- bc.offset += 8;
13975
- }
13976
-
13977
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/uint.js
13978
- function readUint(bc) {
13979
- let low = readU8(bc);
13980
- if (low >= 128) {
13981
- low &= 127;
13982
- let shiftMul = 128;
13983
- let byteCount = 1;
13984
- let byte;
13985
- do {
13986
- byte = readU8(bc);
13987
- low += (byte & 127) * shiftMul;
13988
- shiftMul *= /* 2**7 */
13989
- 128;
13990
- byteCount++;
13991
- } while (byte >= 128 && byteCount < 7);
13992
- let height = 0;
13993
- shiftMul = 1;
13994
- while (byte >= 128 && byteCount < UINT_MAX_BYTE_COUNT) {
13995
- byte = readU8(bc);
13996
- height += (byte & 127) * shiftMul;
13997
- shiftMul *= /* 2**7 */
13998
- 128;
13999
- byteCount++;
14000
- }
14001
- if (byte === 0 || byteCount === UINT_MAX_BYTE_COUNT && byte > 1) {
14002
- bc.offset -= byteCount;
14003
- throw new BareError(bc.offset, NON_CANONICAL_REPRESENTATION);
13891
+ if (value instanceof Map) {
13892
+ for (const [k, v] of value.entries()) {
13893
+ assertJsonCompatValue(k, `${path2 || "root"}.key(${String(k)})`);
13894
+ assertJsonCompatValue(v, `${path2 || "root"}.value(${String(k)})`);
14004
13895
  }
14005
- return BigInt(low) + (BigInt(height) << BigInt(7 * 7));
14006
- }
14007
- return BigInt(low);
14008
- }
14009
- function writeUint(bc, x) {
14010
- const truncated = BigInt.asUintN(64, x);
14011
- if (DEV) {
14012
- assert2(truncated === x, TOO_LARGE_NUMBER);
13896
+ return;
14013
13897
  }
14014
- writeUintTruncated(bc, truncated);
14015
- }
14016
- function writeUintTruncated(bc, x) {
14017
- let tmp = Number(BigInt.asUintN(7 * 7, x));
14018
- let rest = Number(x >> BigInt(7 * 7));
14019
- let byteCount = 0;
14020
- while (tmp >= 128 || rest > 0) {
14021
- writeU8(bc, 128 | tmp & 127);
14022
- tmp = Math.floor(tmp / /* 2**7 */
14023
- 128);
14024
- byteCount++;
14025
- if (byteCount === 7) {
14026
- tmp = rest;
14027
- rest = 0;
13898
+ if (value instanceof Set) {
13899
+ let index = 0;
13900
+ for (const item of value.values()) {
13901
+ assertJsonCompatValue(item, `${path2 || "root"}.set[${index}]`);
13902
+ index++;
14028
13903
  }
13904
+ return;
14029
13905
  }
14030
- writeU8(bc, tmp);
14031
- }
14032
- function readUintSafe32(bc) {
14033
- let result = readU8(bc);
14034
- if (result >= 128) {
14035
- result &= 127;
14036
- let shift = 7;
14037
- let byteCount = 1;
14038
- let byte;
14039
- do {
14040
- byte = readU8(bc);
14041
- result += (byte & 127) << shift >>> 0;
14042
- shift += 7;
14043
- byteCount++;
14044
- } while (byte >= 128 && byteCount < UINT_SAFE32_MAX_BYTE_COUNT);
14045
- if (byte === 0) {
14046
- bc.offset -= byteCount - 1;
14047
- throw new BareError(bc.offset - byteCount + 1, NON_CANONICAL_REPRESENTATION);
13906
+ if (Array.isArray(value)) {
13907
+ for (let i = 0; i < value.length; i++) {
13908
+ assertJsonCompatValue(value[i], `${path2 || "root"}[${i}]`);
14048
13909
  }
14049
- if (byteCount === UINT_SAFE32_MAX_BYTE_COUNT && byte > 15) {
14050
- bc.offset -= byteCount - 1;
14051
- throw new BareError(bc.offset, TOO_LARGE_NUMBER);
13910
+ return;
13911
+ }
13912
+ if (isPlainObject2(value)) {
13913
+ for (const key in value) {
13914
+ assertJsonCompatValue(
13915
+ value[key],
13916
+ path2 ? `${path2}.${key}` : key
13917
+ );
14052
13918
  }
13919
+ return;
14053
13920
  }
14054
- return result;
13921
+ const typeName = typeof value === "object" && value !== null ? ((_a2 = value.constructor) == null ? void 0 : _a2.name) ?? typeof value : typeof value;
13922
+ throw new TypeError(
13923
+ `Value at ${path2 || "root"} of type "${typeName}" is not CBOR serializable`
13924
+ );
14055
13925
  }
14056
- function writeUintSafe32(bc, x) {
14057
- if (DEV) {
14058
- assert2(isU32(x), TOO_LARGE_NUMBER);
13926
+ var EncodingSchema = external_exports.enum(["json", "cbor", "bare"]);
13927
+ async function inputDataToBuffer(data) {
13928
+ if (typeof data === "string") {
13929
+ return data;
14059
13930
  }
14060
- let zigZag = x >>> 0;
14061
- while (zigZag >= 128) {
14062
- writeU8(bc, 128 | zigZag & 127);
14063
- zigZag >>>= 7;
13931
+ if (data instanceof Blob) {
13932
+ return new Uint8Array(await data.arrayBuffer());
14064
13933
  }
14065
- writeU8(bc, zigZag);
14066
- }
14067
- function readUintSafe(bc) {
14068
- let result = readU8(bc);
14069
- if (result >= 128) {
14070
- result &= 127;
14071
- let shiftMul = (
14072
- /* 2**7 */
14073
- 128
14074
- );
14075
- let byteCount = 1;
14076
- let byte;
14077
- do {
14078
- byte = readU8(bc);
14079
- result += (byte & 127) * shiftMul;
14080
- shiftMul *= /* 2**7 */
14081
- 128;
14082
- byteCount++;
14083
- } while (byte >= 128 && byteCount < INT_SAFE_MAX_BYTE_COUNT);
14084
- if (byte === 0) {
14085
- bc.offset -= byteCount - 1;
14086
- throw new BareError(bc.offset - byteCount + 1, NON_CANONICAL_REPRESENTATION);
14087
- }
14088
- if (byteCount === INT_SAFE_MAX_BYTE_COUNT && byte > 15) {
14089
- bc.offset -= byteCount - 1;
14090
- throw new BareError(bc.offset, TOO_LARGE_NUMBER);
14091
- }
13934
+ if (data instanceof Uint8Array) {
13935
+ return data;
14092
13936
  }
14093
- return result;
14094
- }
14095
-
14096
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/u8-array.js
14097
- function readU8Array(bc) {
14098
- return readU8FixedArray(bc, readUintSafe32(bc));
13937
+ if (data instanceof ArrayBuffer || data instanceof SharedArrayBuffer) {
13938
+ return new Uint8Array(data);
13939
+ }
13940
+ throw new Error("Malformed message");
14099
13941
  }
14100
- function writeU8Array(bc, x) {
14101
- writeUintSafe32(bc, x.length);
14102
- writeU8FixedArray(bc, x);
13942
+ function base64EncodeUint8Array(uint8Array) {
13943
+ let binary = "";
13944
+ for (const value of uint8Array) {
13945
+ binary += String.fromCharCode(value);
13946
+ }
13947
+ return btoa(binary);
14103
13948
  }
14104
- function readU8FixedArray(bc, len) {
14105
- return readUnsafeU8FixedArray(bc, len).slice();
13949
+ function base64EncodeArrayBuffer(arrayBuffer) {
13950
+ return base64EncodeUint8Array(new Uint8Array(arrayBuffer));
14106
13951
  }
14107
- function writeU8FixedArray(bc, x) {
14108
- const len = x.length;
14109
- if (len > 0) {
14110
- reserve(bc, len);
14111
- bc.bytes.set(x, bc.offset);
14112
- bc.offset += len;
13952
+ function isPlainObject2(value) {
13953
+ if (value === null || typeof value !== "object") {
13954
+ return false;
14113
13955
  }
13956
+ const proto = Object.getPrototypeOf(value);
13957
+ return proto === Object.prototype || proto === null;
14114
13958
  }
14115
- function readUnsafeU8FixedArray(bc, len) {
14116
- if (DEV) {
14117
- assert2(isU32(len));
13959
+ function encodeJsonCompatValue(input) {
13960
+ var _a2;
13961
+ if (input === null) {
13962
+ return input;
14118
13963
  }
14119
- check2(bc, len);
14120
- const offset = bc.offset;
14121
- bc.offset += len;
14122
- return bc.bytes.subarray(offset, offset + len);
14123
- }
14124
-
14125
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/data.js
14126
- function readData(bc) {
14127
- return readU8Array(bc).buffer;
14128
- }
14129
- function writeData(bc, x) {
14130
- writeU8Array(bc, new Uint8Array(x));
14131
- }
14132
-
14133
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/string.js
14134
- function readString(bc) {
14135
- return readFixedString(bc, readUintSafe32(bc));
14136
- }
14137
- function writeString(bc, x) {
14138
- if (x.length < TEXT_ENCODER_THRESHOLD) {
14139
- const byteLen = utf8ByteLength(x);
14140
- writeUintSafe32(bc, byteLen);
14141
- reserve(bc, byteLen);
14142
- writeUtf8Js(bc, x);
14143
- } else {
14144
- const strBytes = UTF8_ENCODER.encode(x);
14145
- writeUintSafe32(bc, strBytes.length);
14146
- writeU8FixedArray(bc, strBytes);
13964
+ if (input === void 0) {
13965
+ return [JSON_COMPAT_UNDEFINED, 0];
14147
13966
  }
14148
- }
14149
- function readFixedString(bc, byteLen) {
14150
- if (DEV) {
14151
- assert2(isU32(byteLen));
13967
+ if (typeof input === "string" || typeof input === "number" || typeof input === "boolean") {
13968
+ return input;
14152
13969
  }
14153
- if (byteLen < TEXT_DECODER_THRESHOLD) {
14154
- return readUtf8Js(bc, byteLen);
13970
+ if (typeof input === "bigint") {
13971
+ return [JSON_COMPAT_BIGINT, input.toString()];
14155
13972
  }
14156
- try {
14157
- return UTF8_DECODER.decode(readUnsafeU8FixedArray(bc, byteLen));
14158
- } catch (_cause) {
14159
- throw new BareError(bc.offset, INVALID_UTF8_STRING);
13973
+ if (input instanceof ArrayBuffer) {
13974
+ return [JSON_COMPAT_ARRAY_BUFFER, base64EncodeArrayBuffer(input)];
14160
13975
  }
14161
- }
14162
- function readUtf8Js(bc, byteLen) {
14163
- check2(bc, byteLen);
14164
- let result = "";
14165
- const bytes = bc.bytes;
14166
- let offset = bc.offset;
14167
- const upperOffset = offset + byteLen;
14168
- while (offset < upperOffset) {
14169
- let codePoint = bytes[offset++];
14170
- if (codePoint > 127) {
14171
- let malformed = true;
14172
- const byte1 = codePoint;
14173
- if (offset < upperOffset && codePoint < 224) {
14174
- const byte2 = bytes[offset++];
14175
- codePoint = (byte1 & 31) << 6 | byte2 & 63;
14176
- malformed = codePoint >> 7 === 0 || // non-canonical char
14177
- byte1 >> 5 !== 6 || // invalid tag
14178
- byte2 >> 6 !== 2;
14179
- } else if (offset + 1 < upperOffset && codePoint < 240) {
14180
- const byte2 = bytes[offset++];
14181
- const byte3 = bytes[offset++];
14182
- codePoint = (byte1 & 15) << 12 | (byte2 & 63) << 6 | byte3 & 63;
14183
- malformed = codePoint >> 11 === 0 || // non-canonical char or missing data
14184
- codePoint >> 11 === 27 || // surrogate char (0xD800 <= codePoint <= 0xDFFF)
14185
- byte1 >> 4 !== 14 || // invalid tag
14186
- byte2 >> 6 !== 2 || // invalid tag
14187
- byte3 >> 6 !== 2;
14188
- } else if (offset + 2 < upperOffset) {
14189
- const byte2 = bytes[offset++];
14190
- const byte3 = bytes[offset++];
14191
- const byte4 = bytes[offset++];
14192
- codePoint = (byte1 & 7) << 18 | (byte2 & 63) << 12 | (byte3 & 63) << 6 | byte4 & 63;
14193
- malformed = codePoint >> 16 === 0 || // non-canonical char or missing data
14194
- codePoint > 1114111 || // too large code point
14195
- byte1 >> 3 !== 30 || // invalid tag
14196
- byte2 >> 6 !== 2 || // invalid tag
14197
- byte3 >> 6 !== 2 || // invalid tag
14198
- byte4 >> 6 !== 2;
14199
- }
14200
- if (malformed) {
14201
- throw new BareError(bc.offset, INVALID_UTF8_STRING);
14202
- }
14203
- }
14204
- result += String.fromCodePoint(codePoint);
13976
+ if (input instanceof Uint8Array) {
13977
+ return [JSON_COMPAT_UINT8_ARRAY, base64EncodeUint8Array(input)];
14205
13978
  }
14206
- bc.offset = offset;
14207
- return result;
14208
- }
14209
- function writeUtf8Js(bc, s) {
14210
- const bytes = bc.bytes;
14211
- let offset = bc.offset;
14212
- let i = 0;
14213
- while (i < s.length) {
14214
- const codePoint = s.codePointAt(i++);
14215
- if (codePoint < 128) {
14216
- bytes[offset++] = codePoint;
14217
- } else {
14218
- if (codePoint < 2048) {
14219
- bytes[offset++] = 192 | codePoint >> 6;
14220
- } else {
14221
- if (codePoint < 65536) {
14222
- bytes[offset++] = 224 | codePoint >> 12;
14223
- } else {
14224
- bytes[offset++] = 240 | codePoint >> 18;
14225
- bytes[offset++] = 128 | codePoint >> 12 & 63;
14226
- i++;
14227
- }
14228
- bytes[offset++] = 128 | codePoint >> 6 & 63;
14229
- }
14230
- bytes[offset++] = 128 | codePoint & 63;
14231
- }
13979
+ if (isTypedArray(input)) {
13980
+ return input;
14232
13981
  }
14233
- bc.offset = offset;
14234
- }
14235
- function utf8ByteLength(s) {
14236
- let result = s.length;
14237
- for (let i = 0; i < s.length; i++) {
14238
- const codePoint = s.codePointAt(i);
14239
- if (codePoint > 127) {
14240
- result++;
14241
- if (codePoint > 2047) {
14242
- result++;
14243
- if (codePoint > 65535) {
14244
- i++;
14245
- }
14246
- }
14247
- }
13982
+ if (input instanceof Date || input instanceof RegExp || input instanceof Error) {
13983
+ return input;
14248
13984
  }
14249
- return result;
14250
- }
14251
- var UTF8_DECODER = /* @__PURE__ */ new TextDecoder("utf-8", { fatal: true });
14252
- var UTF8_ENCODER = /* @__PURE__ */ new TextEncoder();
14253
-
14254
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/core/config.js
14255
- function Config({ initialBufferLength = 1024, maxBufferLength = 1024 * 1024 * 32 }) {
14256
- if (DEV) {
14257
- assert2(isU32(initialBufferLength), TOO_LARGE_NUMBER);
14258
- assert2(isU32(maxBufferLength), TOO_LARGE_NUMBER);
14259
- assert2(initialBufferLength <= maxBufferLength, "initialBufferLength must be lower than or equal to maxBufferLength");
13985
+ if (input instanceof Set) {
13986
+ const encoded = [...input.values()].map(
13987
+ (v) => encodeJsonCompatValue(v)
13988
+ );
13989
+ return [JSON_COMPAT_SET, encoded];
14260
13990
  }
14261
- return {
14262
- initialBufferLength,
14263
- maxBufferLength
14264
- };
14265
- }
14266
-
14267
- // ../rivetkit/dist/tsup/chunk-QTINS2PE.js
14268
- var config2 = /* @__PURE__ */ Config({});
14269
- function readWorkflowCbor(bc) {
14270
- return readData(bc);
14271
- }
14272
- function readWorkflowNameIndex(bc) {
14273
- return readU32(bc);
14274
- }
14275
- function readWorkflowLoopIterationMarker(bc) {
14276
- return {
14277
- loop: readWorkflowNameIndex(bc),
14278
- iteration: readU32(bc)
14279
- };
14280
- }
14281
- function readWorkflowPathSegment(bc) {
14282
- const offset = bc.offset;
14283
- const tag = readU8(bc);
14284
- switch (tag) {
14285
- case 0:
14286
- return { tag: "WorkflowNameIndex", val: readWorkflowNameIndex(bc) };
14287
- case 1:
14288
- return {
14289
- tag: "WorkflowLoopIterationMarker",
14290
- val: readWorkflowLoopIterationMarker(bc)
14291
- };
14292
- default: {
14293
- bc.offset = offset;
14294
- throw new BareError(offset, "invalid tag");
13991
+ if (input instanceof Map) {
13992
+ const encoded = /* @__PURE__ */ new Map();
13993
+ for (const [k, v] of input.entries()) {
13994
+ encoded.set(
13995
+ encodeJsonCompatValue(k),
13996
+ encodeJsonCompatValue(v)
13997
+ );
14295
13998
  }
13999
+ return encoded;
14296
14000
  }
14297
- }
14298
- function readWorkflowLocation(bc) {
14299
- const len = readUintSafe(bc);
14300
- if (len === 0) {
14301
- return [];
14302
- }
14303
- const result = [readWorkflowPathSegment(bc)];
14304
- for (let i = 1; i < len; i++) {
14305
- result[i] = readWorkflowPathSegment(bc);
14001
+ if (Array.isArray(input)) {
14002
+ const encoded = input.map(
14003
+ (value) => encodeJsonCompatValue(value)
14004
+ );
14005
+ if (encoded.length === 2 && typeof encoded[0] === "string" && encoded[0].startsWith("$")) {
14006
+ return [`$${encoded[0]}`, encoded[1]];
14007
+ }
14008
+ return encoded;
14306
14009
  }
14307
- return result;
14308
- }
14309
- function readWorkflowEntryStatus(bc) {
14310
- const offset = bc.offset;
14311
- const tag = readU8(bc);
14312
- switch (tag) {
14313
- case 0:
14314
- return "PENDING";
14315
- case 1:
14316
- return "RUNNING";
14317
- case 2:
14318
- return "COMPLETED";
14319
- case 3:
14320
- return "FAILED";
14321
- case 4:
14322
- return "EXHAUSTED";
14323
- default: {
14324
- bc.offset = offset;
14325
- throw new BareError(offset, "invalid tag");
14010
+ if (isPlainObject2(input)) {
14011
+ const encoded = {};
14012
+ for (const [key, value] of Object.entries(input)) {
14013
+ encoded[key] = encodeJsonCompatValue(value);
14326
14014
  }
14015
+ return encoded;
14327
14016
  }
14017
+ const typeName = typeof input === "object" && input !== null ? ((_a2 = input.constructor) == null ? void 0 : _a2.name) ?? typeof input : typeof input;
14018
+ throw new TypeError(`Value of type "${typeName}" is not CBOR serializable`);
14328
14019
  }
14329
- function readWorkflowSleepState(bc) {
14330
- const offset = bc.offset;
14331
- const tag = readU8(bc);
14332
- switch (tag) {
14333
- case 0:
14334
- return "PENDING";
14335
- case 1:
14336
- return "COMPLETED";
14337
- case 2:
14338
- return "INTERRUPTED";
14339
- default: {
14340
- bc.offset = offset;
14341
- throw new BareError(offset, "invalid tag");
14020
+ function reviveJsonCompatValue(input, options = {}) {
14021
+ if (typeof input === "bigint") {
14022
+ if (options.coerceSafeIntegerBigInts && input >= BigInt(Number.MIN_SAFE_INTEGER) && input <= BigInt(Number.MAX_SAFE_INTEGER)) {
14023
+ return Number(input);
14342
14024
  }
14025
+ return input;
14343
14026
  }
14344
- }
14345
- function readWorkflowBranchStatusType(bc) {
14346
- const offset = bc.offset;
14347
- const tag = readU8(bc);
14348
- switch (tag) {
14349
- case 0:
14350
- return "PENDING";
14351
- case 1:
14352
- return "RUNNING";
14353
- case 2:
14354
- return "COMPLETED";
14355
- case 3:
14356
- return "FAILED";
14357
- case 4:
14358
- return "CANCELLED";
14359
- default: {
14360
- bc.offset = offset;
14361
- throw new BareError(offset, "invalid tag");
14027
+ if (input instanceof Map) {
14028
+ const revived = /* @__PURE__ */ new Map();
14029
+ for (const [k, v] of input.entries()) {
14030
+ revived.set(
14031
+ reviveJsonCompatValue(k, options),
14032
+ reviveJsonCompatValue(v, options)
14033
+ );
14034
+ }
14035
+ return revived;
14036
+ }
14037
+ if (Array.isArray(input)) {
14038
+ if (input.length === 2 && typeof input[0] === "string" && input[0].startsWith("$")) {
14039
+ if (input[0] === JSON_COMPAT_BIGINT) {
14040
+ return BigInt(input[1]);
14041
+ }
14042
+ if (input[0] === JSON_COMPAT_ARRAY_BUFFER) {
14043
+ return base64DecodeToArrayBuffer(input[1]);
14044
+ }
14045
+ if (input[0] === JSON_COMPAT_UINT8_ARRAY) {
14046
+ return base64DecodeToUint8Array(input[1]);
14047
+ }
14048
+ if (input[0] === JSON_COMPAT_UNDEFINED) {
14049
+ return void 0;
14050
+ }
14051
+ if (input[0] === JSON_COMPAT_SET) {
14052
+ const items = input[1].map(
14053
+ (v) => reviveJsonCompatValue(v, options)
14054
+ );
14055
+ return new Set(items);
14056
+ }
14057
+ if (input[0].startsWith("$$")) {
14058
+ return [
14059
+ input[0].substring(1),
14060
+ reviveJsonCompatValue(input[1], options)
14061
+ ];
14062
+ }
14063
+ throw new Error(
14064
+ `Unknown JSON encoding type: ${input[0]}. This may indicate corrupted data or a version mismatch.`
14065
+ );
14362
14066
  }
14067
+ return input.map((value) => reviveJsonCompatValue(value, options));
14068
+ }
14069
+ if (isPlainObject2(input)) {
14070
+ const decoded = {};
14071
+ for (const [key, value] of Object.entries(input)) {
14072
+ decoded[key] = reviveJsonCompatValue(value, options);
14073
+ }
14074
+ return decoded;
14363
14075
  }
14076
+ return input;
14364
14077
  }
14365
- function read0(bc) {
14366
- return readBool(bc) ? readWorkflowCbor(bc) : null;
14078
+ function base64DecodeToUint8Array(base643) {
14079
+ if (typeof Buffer !== "undefined") {
14080
+ return new Uint8Array(Buffer.from(base643, "base64"));
14081
+ }
14082
+ const binary = atob(base643);
14083
+ const bytes = new Uint8Array(binary.length);
14084
+ for (let i = 0; i < binary.length; i++) {
14085
+ bytes[i] = binary.charCodeAt(i);
14086
+ }
14087
+ return bytes;
14367
14088
  }
14368
- function read1(bc) {
14369
- return readBool(bc) ? readString(bc) : null;
14089
+ function base64DecodeToArrayBuffer(base643) {
14090
+ return base64DecodeToUint8Array(base643).buffer;
14370
14091
  }
14371
- function readWorkflowStepEntry(bc) {
14372
- return {
14373
- output: read0(bc),
14374
- error: read1(bc)
14375
- };
14092
+ function jsonStringifyCompat(input, space) {
14093
+ return JSON.stringify(
14094
+ input,
14095
+ (_key, value) => {
14096
+ if (typeof value === "bigint") {
14097
+ return [JSON_COMPAT_BIGINT, value.toString()];
14098
+ }
14099
+ if (value instanceof ArrayBuffer) {
14100
+ return [
14101
+ JSON_COMPAT_ARRAY_BUFFER,
14102
+ base64EncodeArrayBuffer(value)
14103
+ ];
14104
+ }
14105
+ if (value instanceof Uint8Array) {
14106
+ return [JSON_COMPAT_UINT8_ARRAY, base64EncodeUint8Array(value)];
14107
+ }
14108
+ if (Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && value[0].startsWith("$")) {
14109
+ return [`$${value[0]}`, value[1]];
14110
+ }
14111
+ return value;
14112
+ },
14113
+ space
14114
+ );
14376
14115
  }
14377
- function readWorkflowLoopEntry(bc) {
14378
- return {
14379
- state: readWorkflowCbor(bc),
14380
- iteration: readU32(bc),
14381
- output: read0(bc)
14382
- };
14116
+ function jsonParseCompat(input) {
14117
+ return reviveJsonCompatValue(JSON.parse(input));
14383
14118
  }
14384
- function readWorkflowSleepEntry(bc) {
14385
- return {
14386
- deadline: readU64(bc),
14387
- state: readWorkflowSleepState(bc)
14388
- };
14119
+ var VERSION = package_default.version;
14120
+ var _userAgent;
14121
+ function httpUserAgent() {
14122
+ if (_userAgent !== void 0) {
14123
+ return _userAgent;
14124
+ }
14125
+ let userAgent = `RivetKit/${VERSION}`;
14126
+ const navigatorObj = typeof navigator !== "undefined" ? navigator : void 0;
14127
+ if (navigatorObj == null ? void 0 : navigatorObj.userAgent) userAgent += ` ${navigatorObj.userAgent}`;
14128
+ _userAgent = userAgent;
14129
+ return userAgent;
14389
14130
  }
14390
- function readWorkflowMessageEntry(bc) {
14391
- return {
14392
- name: readString(bc),
14393
- messageData: readWorkflowCbor(bc)
14394
- };
14131
+ function getEnvUniversal(key) {
14132
+ if (typeof Deno !== "undefined") {
14133
+ return Deno.env.get(key);
14134
+ } else if (typeof process !== "undefined") {
14135
+ return process.env[key];
14136
+ }
14395
14137
  }
14396
- function readWorkflowRollbackCheckpointEntry(bc) {
14397
- return {
14398
- name: readString(bc)
14399
- };
14138
+ function toUint8Array(data) {
14139
+ if (data instanceof Uint8Array) {
14140
+ return data;
14141
+ } else if (data instanceof ArrayBuffer) {
14142
+ return new Uint8Array(data);
14143
+ } else if (ArrayBuffer.isView(data)) {
14144
+ return new Uint8Array(
14145
+ data.buffer.slice(
14146
+ data.byteOffset,
14147
+ data.byteOffset + data.byteLength
14148
+ )
14149
+ );
14150
+ } else {
14151
+ throw new TypeError("Input must be ArrayBuffer or ArrayBufferView");
14152
+ }
14400
14153
  }
14401
- function readWorkflowBranchStatus(bc) {
14402
- return {
14403
- status: readWorkflowBranchStatusType(bc),
14404
- output: read0(bc),
14405
- error: read1(bc)
14406
- };
14154
+ function promiseWithResolvers(onReject) {
14155
+ let resolve;
14156
+ let reject;
14157
+ const promise2 = new Promise((res, rej) => {
14158
+ resolve = res;
14159
+ reject = rej;
14160
+ });
14161
+ promise2.catch(onReject);
14162
+ return { promise: promise2, resolve, reject };
14407
14163
  }
14408
- function read2(bc) {
14409
- const len = readUintSafe(bc);
14410
- const result = /* @__PURE__ */ new Map();
14411
- for (let i = 0; i < len; i++) {
14412
- const offset = bc.offset;
14413
- const key = readString(bc);
14414
- if (result.has(key)) {
14415
- bc.offset = offset;
14416
- throw new BareError(offset, "duplicated key");
14164
+ function bufferToArrayBuffer(buf) {
14165
+ return buf.buffer.slice(
14166
+ buf.byteOffset,
14167
+ buf.byteOffset + buf.byteLength
14168
+ );
14169
+ }
14170
+ function combineUrlPath(endpoint, path2, queryParams) {
14171
+ const baseUrl = new URL(endpoint);
14172
+ const pathParts = path2.split("?");
14173
+ const pathOnly = pathParts[0];
14174
+ const existingQuery = pathParts[1] || "";
14175
+ const basePath = baseUrl.pathname.replace(/\/$/, "");
14176
+ const cleanPath = pathOnly.startsWith("/") ? pathOnly : `/${pathOnly}`;
14177
+ const fullPath = (basePath + cleanPath).replace(/\/\//g, "/");
14178
+ const queryParts = [];
14179
+ if (existingQuery) {
14180
+ queryParts.push(existingQuery);
14181
+ }
14182
+ if (queryParams) {
14183
+ for (const [key, value] of Object.entries(queryParams)) {
14184
+ if (value !== void 0) {
14185
+ queryParts.push(
14186
+ `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
14187
+ );
14188
+ }
14417
14189
  }
14418
- result.set(key, readWorkflowBranchStatus(bc));
14419
14190
  }
14420
- return result;
14191
+ const fullQuery = queryParts.length > 0 ? `?${queryParts.join("&")}` : "";
14192
+ return `${baseUrl.protocol}//${baseUrl.host}${fullPath}${fullQuery}`;
14421
14193
  }
14422
- function readWorkflowJoinEntry(bc) {
14423
- return {
14424
- branches: read2(bc)
14425
- };
14194
+
14195
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/imports/dev.node.js
14196
+ var DEV = process.env.NODE_ENV === "development";
14197
+
14198
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/util/assert.js
14199
+ var V8Error = Error;
14200
+ function assert2(test, message = "") {
14201
+ if (!test) {
14202
+ const e = new AssertionError(message);
14203
+ V8Error.captureStackTrace?.(e, assert2);
14204
+ throw e;
14205
+ }
14426
14206
  }
14427
- function readWorkflowRaceEntry(bc) {
14428
- return {
14429
- winner: read1(bc),
14430
- branches: read2(bc)
14431
- };
14207
+ var AssertionError = class extends Error {
14208
+ constructor() {
14209
+ super(...arguments);
14210
+ this.name = "AssertionError";
14211
+ }
14212
+ };
14213
+
14214
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/util/validator.js
14215
+ function isU8(val) {
14216
+ return val === (val & 255);
14432
14217
  }
14433
- function readWorkflowRemovedEntry(bc) {
14434
- return {
14435
- originalType: readString(bc),
14436
- originalName: read1(bc)
14437
- };
14218
+ function isU32(val) {
14219
+ return val === val >>> 0;
14438
14220
  }
14439
- function readWorkflowVersionCheckEntry(bc) {
14440
- return {
14441
- resolved: readU32(bc),
14442
- latest: readU32(bc)
14443
- };
14221
+ function isU64(val) {
14222
+ return val === BigInt.asUintN(64, val);
14444
14223
  }
14445
- function readWorkflowEntryKind(bc) {
14446
- const offset = bc.offset;
14447
- const tag = readU8(bc);
14448
- switch (tag) {
14449
- case 0:
14450
- return { tag: "WorkflowStepEntry", val: readWorkflowStepEntry(bc) };
14451
- case 1:
14452
- return { tag: "WorkflowLoopEntry", val: readWorkflowLoopEntry(bc) };
14453
- case 2:
14454
- return {
14455
- tag: "WorkflowSleepEntry",
14456
- val: readWorkflowSleepEntry(bc)
14457
- };
14458
- case 3:
14459
- return {
14460
- tag: "WorkflowMessageEntry",
14461
- val: readWorkflowMessageEntry(bc)
14462
- };
14463
- case 4:
14464
- return {
14465
- tag: "WorkflowRollbackCheckpointEntry",
14466
- val: readWorkflowRollbackCheckpointEntry(bc)
14467
- };
14468
- case 5:
14469
- return { tag: "WorkflowJoinEntry", val: readWorkflowJoinEntry(bc) };
14470
- case 6:
14471
- return { tag: "WorkflowRaceEntry", val: readWorkflowRaceEntry(bc) };
14472
- case 7:
14473
- return {
14474
- tag: "WorkflowRemovedEntry",
14475
- val: readWorkflowRemovedEntry(bc)
14476
- };
14477
- case 8:
14478
- return {
14479
- tag: "WorkflowVersionCheckEntry",
14480
- val: readWorkflowVersionCheckEntry(bc)
14481
- };
14482
- default: {
14483
- bc.offset = offset;
14484
- throw new BareError(offset, "invalid tag");
14224
+
14225
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/util/constants.js
14226
+ var TEXT_DECODER_THRESHOLD = 256;
14227
+ var TEXT_ENCODER_THRESHOLD = 256;
14228
+ var INT_SAFE_MAX_BYTE_COUNT = 8;
14229
+ var UINT_MAX_BYTE_COUNT = 10;
14230
+ var UINT_SAFE32_MAX_BYTE_COUNT = 5;
14231
+ var INVALID_UTF8_STRING = "invalid UTF-8 string";
14232
+ var NON_CANONICAL_REPRESENTATION = "must be canonical";
14233
+ var TOO_LARGE_BUFFER = "too large buffer";
14234
+ var TOO_LARGE_NUMBER = "too large number";
14235
+
14236
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/core/bare-error.js
14237
+ var BareError = class extends Error {
14238
+ constructor(offset, issue2, opts) {
14239
+ super(`(byte:${offset}) ${issue2}`);
14240
+ this.name = "BareError";
14241
+ this.issue = issue2;
14242
+ this.offset = offset;
14243
+ this.cause = opts?.cause;
14244
+ }
14245
+ };
14246
+
14247
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/core/byte-cursor.js
14248
+ var ByteCursor = class {
14249
+ /**
14250
+ * @throws {BareError} Buffer exceeds `config.maxBufferLength`
14251
+ */
14252
+ constructor(bytes, config3) {
14253
+ this.offset = 0;
14254
+ if (bytes.length > config3.maxBufferLength) {
14255
+ throw new BareError(0, TOO_LARGE_BUFFER);
14485
14256
  }
14257
+ this.bytes = bytes;
14258
+ this.config = config3;
14259
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.length);
14260
+ }
14261
+ };
14262
+ function check2(bc, min) {
14263
+ if (DEV) {
14264
+ assert2(isU32(min));
14265
+ }
14266
+ if (bc.offset + min > bc.bytes.length) {
14267
+ throw new BareError(bc.offset, "missing bytes");
14486
14268
  }
14487
14269
  }
14488
- function readWorkflowEntry(bc) {
14489
- return {
14490
- id: readString(bc),
14491
- location: readWorkflowLocation(bc),
14492
- kind: readWorkflowEntryKind(bc)
14493
- };
14270
+ function reserve(bc, min) {
14271
+ if (DEV) {
14272
+ assert2(isU32(min));
14273
+ }
14274
+ const minLen = bc.offset + min | 0;
14275
+ if (minLen > bc.bytes.length) {
14276
+ grow(bc, minLen);
14277
+ }
14494
14278
  }
14495
- function read3(bc) {
14496
- return readBool(bc) ? readU64(bc) : null;
14279
+ function grow(bc, minLen) {
14280
+ if (minLen > bc.config.maxBufferLength) {
14281
+ throw new BareError(0, TOO_LARGE_BUFFER);
14282
+ }
14283
+ const buffer = bc.bytes.buffer;
14284
+ let newBytes;
14285
+ if (isEs2024ArrayBufferLike(buffer) && // Make sure that the view covers the end of the buffer.
14286
+ // If it is not the case, this indicates that the user don't want
14287
+ // to override the trailing bytes.
14288
+ bc.bytes.byteOffset + bc.bytes.byteLength === buffer.byteLength && bc.bytes.byteLength + minLen <= buffer.maxByteLength) {
14289
+ const newLen = Math.min(minLen << 1, bc.config.maxBufferLength, buffer.maxByteLength);
14290
+ if (buffer instanceof ArrayBuffer) {
14291
+ buffer.resize(newLen);
14292
+ } else {
14293
+ buffer.grow(newLen);
14294
+ }
14295
+ newBytes = new Uint8Array(buffer, bc.bytes.byteOffset, newLen);
14296
+ } else {
14297
+ const newLen = Math.min(minLen << 1, bc.config.maxBufferLength);
14298
+ newBytes = new Uint8Array(newLen);
14299
+ newBytes.set(bc.bytes);
14300
+ }
14301
+ bc.bytes = newBytes;
14302
+ bc.view = new DataView(newBytes.buffer);
14497
14303
  }
14498
- function readWorkflowEntryMetadata(bc) {
14499
- return {
14500
- status: readWorkflowEntryStatus(bc),
14501
- error: read1(bc),
14502
- attempts: readU32(bc),
14503
- lastAttemptAt: readU64(bc),
14504
- createdAt: readU64(bc),
14505
- completedAt: read3(bc),
14506
- rollbackCompletedAt: read3(bc),
14507
- rollbackError: read1(bc)
14508
- };
14304
+ function isEs2024ArrayBufferLike(buffer) {
14305
+ return "maxByteLength" in buffer;
14509
14306
  }
14510
- function read4(bc) {
14511
- const len = readUintSafe(bc);
14512
- if (len === 0) {
14513
- return [];
14307
+
14308
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/fixed-primitive.js
14309
+ function readBool(bc) {
14310
+ const val = readU8(bc);
14311
+ if (val > 1) {
14312
+ bc.offset--;
14313
+ throw new BareError(bc.offset, "a bool must be equal to 0 or 1");
14514
14314
  }
14515
- const result = [readString(bc)];
14516
- for (let i = 1; i < len; i++) {
14517
- result[i] = readString(bc);
14315
+ return val > 0;
14316
+ }
14317
+ function writeBool(bc, x) {
14318
+ writeU8(bc, x ? 1 : 0);
14319
+ }
14320
+ function readU8(bc) {
14321
+ check2(bc, 1);
14322
+ return bc.bytes[bc.offset++];
14323
+ }
14324
+ function writeU8(bc, x) {
14325
+ if (DEV) {
14326
+ assert2(isU8(x), TOO_LARGE_NUMBER);
14518
14327
  }
14328
+ reserve(bc, 1);
14329
+ bc.bytes[bc.offset++] = x;
14330
+ }
14331
+ function readU32(bc) {
14332
+ check2(bc, 4);
14333
+ const result = bc.view.getUint32(bc.offset, true);
14334
+ bc.offset += 4;
14519
14335
  return result;
14520
14336
  }
14521
- function read5(bc) {
14522
- const len = readUintSafe(bc);
14523
- if (len === 0) {
14524
- return [];
14525
- }
14526
- const result = [readWorkflowEntry(bc)];
14527
- for (let i = 1; i < len; i++) {
14528
- result[i] = readWorkflowEntry(bc);
14529
- }
14337
+ function readU64(bc) {
14338
+ check2(bc, 8);
14339
+ const result = bc.view.getBigUint64(bc.offset, true);
14340
+ bc.offset += 8;
14530
14341
  return result;
14531
14342
  }
14532
- function read6(bc) {
14533
- const len = readUintSafe(bc);
14534
- const result = /* @__PURE__ */ new Map();
14535
- for (let i = 0; i < len; i++) {
14536
- const offset = bc.offset;
14537
- const key = readString(bc);
14538
- if (result.has(key)) {
14539
- bc.offset = offset;
14540
- throw new BareError(offset, "duplicated key");
14343
+ function writeU64(bc, x) {
14344
+ if (DEV) {
14345
+ assert2(isU64(x), TOO_LARGE_NUMBER);
14346
+ }
14347
+ reserve(bc, 8);
14348
+ bc.view.setBigUint64(bc.offset, x, true);
14349
+ bc.offset += 8;
14350
+ }
14351
+
14352
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/uint.js
14353
+ function readUint(bc) {
14354
+ let low = readU8(bc);
14355
+ if (low >= 128) {
14356
+ low &= 127;
14357
+ let shiftMul = 128;
14358
+ let byteCount = 1;
14359
+ let byte;
14360
+ do {
14361
+ byte = readU8(bc);
14362
+ low += (byte & 127) * shiftMul;
14363
+ shiftMul *= /* 2**7 */
14364
+ 128;
14365
+ byteCount++;
14366
+ } while (byte >= 128 && byteCount < 7);
14367
+ let height = 0;
14368
+ shiftMul = 1;
14369
+ while (byte >= 128 && byteCount < UINT_MAX_BYTE_COUNT) {
14370
+ byte = readU8(bc);
14371
+ height += (byte & 127) * shiftMul;
14372
+ shiftMul *= /* 2**7 */
14373
+ 128;
14374
+ byteCount++;
14541
14375
  }
14542
- result.set(key, readWorkflowEntryMetadata(bc));
14376
+ if (byte === 0 || byteCount === UINT_MAX_BYTE_COUNT && byte > 1) {
14377
+ bc.offset -= byteCount;
14378
+ throw new BareError(bc.offset, NON_CANONICAL_REPRESENTATION);
14379
+ }
14380
+ return BigInt(low) + (BigInt(height) << BigInt(7 * 7));
14543
14381
  }
14544
- return result;
14382
+ return BigInt(low);
14545
14383
  }
14546
- function readWorkflowHistory(bc) {
14547
- return {
14548
- nameRegistry: read4(bc),
14549
- entries: read5(bc),
14550
- entryMetadata: read6(bc)
14551
- };
14384
+ function writeUint(bc, x) {
14385
+ const truncated = BigInt.asUintN(64, x);
14386
+ if (DEV) {
14387
+ assert2(truncated === x, TOO_LARGE_NUMBER);
14388
+ }
14389
+ writeUintTruncated(bc, truncated);
14552
14390
  }
14553
- function decodeWorkflowHistory(bytes) {
14554
- const bc = new ByteCursor(bytes, config2);
14555
- const result = readWorkflowHistory(bc);
14556
- if (bc.offset < bc.view.byteLength) {
14557
- throw new BareError(bc.offset, "remaining bytes");
14391
+ function writeUintTruncated(bc, x) {
14392
+ let tmp = Number(BigInt.asUintN(7 * 7, x));
14393
+ let rest = Number(x >> BigInt(7 * 7));
14394
+ let byteCount = 0;
14395
+ while (tmp >= 128 || rest > 0) {
14396
+ writeU8(bc, 128 | tmp & 127);
14397
+ tmp = Math.floor(tmp / /* 2**7 */
14398
+ 128);
14399
+ byteCount++;
14400
+ if (byteCount === 7) {
14401
+ tmp = rest;
14402
+ rest = 0;
14403
+ }
14558
14404
  }
14559
- return result;
14405
+ writeU8(bc, tmp);
14560
14406
  }
14561
- function decodeWorkflowHistoryTransport(data) {
14562
- return decodeWorkflowHistory(toUint8Array(data));
14407
+ function readUintSafe32(bc) {
14408
+ let result = readU8(bc);
14409
+ if (result >= 128) {
14410
+ result &= 127;
14411
+ let shift = 7;
14412
+ let byteCount = 1;
14413
+ let byte;
14414
+ do {
14415
+ byte = readU8(bc);
14416
+ result += (byte & 127) << shift >>> 0;
14417
+ shift += 7;
14418
+ byteCount++;
14419
+ } while (byte >= 128 && byteCount < UINT_SAFE32_MAX_BYTE_COUNT);
14420
+ if (byte === 0) {
14421
+ bc.offset -= byteCount - 1;
14422
+ throw new BareError(bc.offset - byteCount + 1, NON_CANONICAL_REPRESENTATION);
14423
+ }
14424
+ if (byteCount === UINT_SAFE32_MAX_BYTE_COUNT && byte > 15) {
14425
+ bc.offset -= byteCount - 1;
14426
+ throw new BareError(bc.offset, TOO_LARGE_NUMBER);
14427
+ }
14428
+ }
14429
+ return result;
14563
14430
  }
14564
-
14565
- // ../rivetkit/dist/tsup/chunk-X3LBDNEH.js
14566
- var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
14567
- var ACTOR_CONTEXT_INTERNAL_SYMBOL = /* @__PURE__ */ Symbol(
14568
- "rivetkit.actor_context_internal"
14569
- );
14570
- var RAW_STATE_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.raw_state");
14571
- var CONN_STATE_MANAGER_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.conn_state_manager");
14572
- var zFunction = () => external_exports.custom((val) => typeof val === "function");
14573
- var WorkflowInspectorConfigSchema = external_exports.object({
14574
- getHistory: zFunction(),
14575
- onHistoryUpdated: zFunction().optional(),
14576
- replayFromStep: zFunction().optional()
14577
- });
14578
- var RunInspectorConfigSchema = external_exports.object({
14579
- workflow: WorkflowInspectorConfigSchema.optional()
14580
- }).optional();
14581
- var BUILTIN_INSPECTOR_TAB_IDS = [
14582
- "workflow",
14583
- "database",
14584
- "state",
14585
- "queue",
14586
- "connections",
14587
- "console"
14588
- ];
14589
- var BuiltinInspectorTabIdSchema = external_exports.enum(BUILTIN_INSPECTOR_TAB_IDS);
14590
- var CUSTOM_INSPECTOR_TAB_ID_RE = /^[A-Za-z0-9_-]+$/;
14591
- var CustomInspectorTabEntrySchema = external_exports.object({
14592
- id: external_exports.string().regex(
14593
- CUSTOM_INSPECTOR_TAB_ID_RE,
14594
- "inspector.tabs[].id must contain only letters, digits, underscore, or dash"
14595
- ),
14596
- label: external_exports.string().min(1),
14597
- source: external_exports.string().min(1),
14598
- /**
14599
- * Optional icon id. The dashboard maps strings to glyphs (see its
14600
- * icon registry); unknown ids fall back to a generic icon.
14601
- */
14602
- icon: external_exports.string().min(1).optional(),
14603
- hidden: external_exports.literal(false).optional()
14604
- }).strict();
14605
- var HideInspectorTabEntrySchema = external_exports.object({
14606
- id: BuiltinInspectorTabIdSchema,
14607
- hidden: external_exports.literal(true)
14608
- }).strict();
14609
- var InspectorTabEntrySchema = external_exports.union([
14610
- CustomInspectorTabEntrySchema,
14611
- HideInspectorTabEntrySchema
14612
- ]);
14613
- var ActorInspectorConfigSchema = external_exports.object({
14614
- tabs: external_exports.array(InspectorTabEntrySchema).default(() => [])
14615
- }).strict().refine(
14616
- (data) => {
14617
- const ids = data.tabs.map((t) => t.id);
14618
- return new Set(ids).size === ids.length;
14619
- },
14620
- { message: "Duplicate id in inspector.tabs", path: ["tabs"] }
14621
- ).refine(
14622
- (data) => {
14623
- const builtinSet = new Set(BUILTIN_INSPECTOR_TAB_IDS);
14624
- return data.tabs.every(
14625
- (t) => t.hidden === true || !builtinSet.has(t.id)
14431
+ function writeUintSafe32(bc, x) {
14432
+ if (DEV) {
14433
+ assert2(isU32(x), TOO_LARGE_NUMBER);
14434
+ }
14435
+ let zigZag = x >>> 0;
14436
+ while (zigZag >= 128) {
14437
+ writeU8(bc, 128 | zigZag & 127);
14438
+ zigZag >>>= 7;
14439
+ }
14440
+ writeU8(bc, zigZag);
14441
+ }
14442
+ function readUintSafe(bc) {
14443
+ let result = readU8(bc);
14444
+ if (result >= 128) {
14445
+ result &= 127;
14446
+ let shiftMul = (
14447
+ /* 2**7 */
14448
+ 128
14626
14449
  );
14627
- },
14628
- {
14629
- message: "Custom inspector tab id collides with a built-in (use hidden: true to hide a built-in)",
14630
- path: ["tabs"]
14450
+ let byteCount = 1;
14451
+ let byte;
14452
+ do {
14453
+ byte = readU8(bc);
14454
+ result += (byte & 127) * shiftMul;
14455
+ shiftMul *= /* 2**7 */
14456
+ 128;
14457
+ byteCount++;
14458
+ } while (byte >= 128 && byteCount < INT_SAFE_MAX_BYTE_COUNT);
14459
+ if (byte === 0) {
14460
+ bc.offset -= byteCount - 1;
14461
+ throw new BareError(bc.offset - byteCount + 1, NON_CANONICAL_REPRESENTATION);
14462
+ }
14463
+ if (byteCount === INT_SAFE_MAX_BYTE_COUNT && byte > 15) {
14464
+ bc.offset -= byteCount - 1;
14465
+ throw new BareError(bc.offset, TOO_LARGE_NUMBER);
14466
+ }
14631
14467
  }
14632
- );
14633
- var RunConfigSchema = external_exports.object({
14634
- /** Display name for the actor in the Inspector UI. */
14635
- name: external_exports.string().optional(),
14636
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
14637
- icon: external_exports.string().optional(),
14638
- /** The run handler function. */
14639
- run: zFunction(),
14640
- /** Inspector integration for long-running run handlers. */
14641
- inspector: RunInspectorConfigSchema.optional()
14642
- });
14643
- var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for(
14644
- "rivetkit.run_function_config"
14645
- );
14646
- var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
14647
- function getRunFunction(run) {
14648
- if (!run) return void 0;
14649
- if (typeof run === "function") return run;
14650
- return run.run;
14468
+ return result;
14651
14469
  }
14652
- function getRunMetadata(run) {
14653
- if (!run) return {};
14654
- if (typeof run === "function") {
14655
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
14656
- if (!config3) return {};
14657
- return { name: config3.name, icon: config3.icon };
14470
+
14471
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/u8-array.js
14472
+ function readU8Array(bc) {
14473
+ return readU8FixedArray(bc, readUintSafe32(bc));
14474
+ }
14475
+ function writeU8Array(bc, x) {
14476
+ writeUintSafe32(bc, x.length);
14477
+ writeU8FixedArray(bc, x);
14478
+ }
14479
+ function readU8FixedArray(bc, len) {
14480
+ return readUnsafeU8FixedArray(bc, len).slice();
14481
+ }
14482
+ function writeU8FixedArray(bc, x) {
14483
+ const len = x.length;
14484
+ if (len > 0) {
14485
+ reserve(bc, len);
14486
+ bc.bytes.set(x, bc.offset);
14487
+ bc.offset += len;
14658
14488
  }
14659
- return { name: run.name, icon: run.icon };
14660
14489
  }
14661
- function getRunInspectorConfig(run, actor2) {
14662
- if (!run) return void 0;
14663
- if (typeof run === "function") {
14664
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
14665
- return (config3 == null ? void 0 : config3.inspectorFactory) ? config3.inspectorFactory(actor2) : config3 == null ? void 0 : config3.inspector;
14490
+ function readUnsafeU8FixedArray(bc, len) {
14491
+ if (DEV) {
14492
+ assert2(isU32(len));
14666
14493
  }
14667
- return run.inspector;
14494
+ check2(bc, len);
14495
+ const offset = bc.offset;
14496
+ bc.offset += len;
14497
+ return bc.bytes.subarray(offset, offset + len);
14668
14498
  }
14669
- function disposeRunInspector(run, actorId) {
14670
- var _a2;
14671
- if (!run || typeof run !== "function") {
14672
- return;
14499
+
14500
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/data.js
14501
+ function readData(bc) {
14502
+ return readU8Array(bc).buffer;
14503
+ }
14504
+ function writeData(bc, x) {
14505
+ writeU8Array(bc, new Uint8Array(x));
14506
+ }
14507
+
14508
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/string.js
14509
+ function readString(bc) {
14510
+ return readFixedString(bc, readUintSafe32(bc));
14511
+ }
14512
+ function writeString(bc, x) {
14513
+ if (x.length < TEXT_ENCODER_THRESHOLD) {
14514
+ const byteLen = utf8ByteLength(x);
14515
+ writeUintSafe32(bc, byteLen);
14516
+ reserve(bc, byteLen);
14517
+ writeUtf8Js(bc, x);
14518
+ } else {
14519
+ const strBytes = UTF8_ENCODER.encode(x);
14520
+ writeUintSafe32(bc, strBytes.length);
14521
+ writeU8FixedArray(bc, strBytes);
14673
14522
  }
14674
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
14675
- (_a2 = config3 == null ? void 0 : config3.disposeInspector) == null ? void 0 : _a2.call(config3, actorId);
14676
14523
  }
14677
- var GlobalActorOptionsBaseSchema = external_exports.object({
14678
- /** Display name for the actor in the Inspector UI. */
14679
- name: external_exports.string().optional(),
14680
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
14681
- icon: external_exports.string().optional(),
14682
- /** Enables the experimental Actor Runtime Socket for this actor. */
14683
- enableActorRuntimeSocket: external_exports.boolean().default(false),
14684
- /**
14685
- * Can hibernate WebSockets for onWebSocket.
14686
- *
14687
- * WebSockets using actions/events are hibernatable by default.
14688
- *
14689
- * @experimental
14690
- **/
14691
- canHibernateWebSocket: external_exports.union([external_exports.boolean(), zFunction()]).default(false)
14692
- }).strict();
14693
- var GlobalActorOptionsSchema = GlobalActorOptionsBaseSchema.prefault(
14694
- () => ({})
14695
- );
14696
- var InstanceActorOptionsBaseSchema = external_exports.object({
14697
- createVarsTimeout: external_exports.number().positive().default(5e3),
14698
- createConnStateTimeout: external_exports.number().positive().default(5e3),
14699
- onBeforeConnectTimeout: external_exports.number().positive().default(5e3),
14700
- onConnectTimeout: external_exports.number().positive().default(5e3),
14701
- onMigrateTimeout: external_exports.number().positive().default(3e4),
14702
- sleepGracePeriod: external_exports.number().positive().default(DEFAULT_SLEEP_GRACE_PERIOD),
14703
- /** @deprecated `onDestroyTimeout` is folded into `sleepGracePeriod`, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0. */
14704
- onDestroyTimeout: external_exports.number().positive().optional(),
14705
- /** @deprecated `waitUntilTimeout` is folded into `sleepGracePeriod`, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0. */
14706
- waitUntilTimeout: external_exports.number().positive().optional(),
14707
- stateSaveInterval: external_exports.number().positive().default(1e3),
14708
- actionTimeout: external_exports.number().positive().default(6e4),
14709
- connectionLivenessTimeout: external_exports.number().positive().default(2500),
14710
- connectionLivenessInterval: external_exports.number().positive().default(5e3),
14711
- /** @deprecated Use `c.keepAwake(promise)` to scope keep-awake to a specific operation, or keep `noSleep` for actors that must stay awake indefinitely. Will be removed in 2.2.0. */
14712
- noSleep: external_exports.boolean().default(false),
14713
- sleepTimeout: external_exports.number().positive().default(3e4),
14714
- maxQueueSize: external_exports.number().positive().default(1e3),
14715
- maxQueueMessageSize: external_exports.number().positive().default(64 * 1024),
14716
- /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
14717
- preloadMaxWorkflowBytes: external_exports.number().nonnegative().optional(),
14718
- /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
14719
- preloadMaxConnectionsBytes: external_exports.number().nonnegative().optional()
14720
- }).strict();
14721
- var InstanceActorOptionsSchema = InstanceActorOptionsBaseSchema.prefault(() => ({}));
14722
- var ActorOptionsSchema = GlobalActorOptionsBaseSchema.extend(
14723
- InstanceActorOptionsBaseSchema.shape
14724
- ).strict().prefault(() => ({}));
14725
- var ActorConfigSchema = external_exports.object({
14726
- onCreate: zFunction().optional(),
14727
- onDestroy: zFunction().optional(),
14728
- onMigrate: zFunction().optional(),
14729
- onWake: zFunction().optional(),
14730
- onSleep: zFunction().optional(),
14731
- run: zRunHandler,
14732
- onStateChange: zFunction().optional(),
14733
- onBeforeConnect: zFunction().optional(),
14734
- onConnect: zFunction().optional(),
14735
- onDisconnect: zFunction().optional(),
14736
- onBeforeActionResponse: zFunction().optional(),
14737
- onRequest: zFunction().optional(),
14738
- onWebSocket: zFunction().optional(),
14739
- actions: external_exports.record(external_exports.string(), zFunction()).default(() => ({})),
14740
- actionInputSchemas: external_exports.record(external_exports.string(), external_exports.any()).optional(),
14741
- connParamsSchema: external_exports.any().optional(),
14742
- events: external_exports.record(external_exports.string(), external_exports.any()).optional(),
14743
- queues: external_exports.record(external_exports.string(), external_exports.any()).optional(),
14744
- state: external_exports.any().optional(),
14745
- createState: zFunction().optional(),
14746
- connState: external_exports.any().optional(),
14747
- createConnState: zFunction().optional(),
14748
- vars: external_exports.any().optional(),
14749
- db: external_exports.any().optional(),
14750
- createVars: zFunction().optional(),
14751
- options: ActorOptionsSchema,
14752
- inspector: ActorInspectorConfigSchema.optional()
14753
- }).strict().refine(
14754
- (data) => !(data.state !== void 0 && data.createState !== void 0),
14755
- {
14756
- message: "Cannot define both 'state' and 'createState'",
14757
- path: ["state"]
14758
- }
14759
- ).refine(
14760
- (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
14761
- {
14762
- message: "Cannot define both 'connState' and 'createConnState'",
14763
- path: ["connState"]
14524
+ function readFixedString(bc, byteLen) {
14525
+ if (DEV) {
14526
+ assert2(isU32(byteLen));
14764
14527
  }
14765
- ).refine(
14766
- (data) => !(data.vars !== void 0 && data.createVars !== void 0),
14767
- {
14768
- message: "Cannot define both 'vars' and 'createVars'",
14769
- path: ["vars"]
14528
+ if (byteLen < TEXT_DECODER_THRESHOLD) {
14529
+ return readUtf8Js(bc, byteLen);
14770
14530
  }
14771
- );
14772
- var DocActorOptionsSchema = external_exports.object({
14773
- name: external_exports.string().optional().describe("Display name for the actor in the Inspector UI."),
14774
- icon: external_exports.string().optional().describe(
14775
- "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
14776
- ),
14777
- enableActorRuntimeSocket: external_exports.boolean().optional().describe(
14778
- "Enables the experimental Actor Runtime Socket for this actor. Default: false"
14779
- ),
14780
- createVarsTimeout: external_exports.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
14781
- createConnStateTimeout: external_exports.number().optional().describe(
14782
- "Timeout in ms for createConnState handler. Default: 5000"
14783
- ),
14784
- onMigrateTimeout: external_exports.number().optional().describe("Timeout in ms for onMigrate handler. Default: 30000"),
14785
- onBeforeConnectTimeout: external_exports.number().optional().describe(
14786
- "Timeout in ms for onBeforeConnect handler. Default: 5000"
14787
- ),
14788
- onConnectTimeout: external_exports.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
14789
- sleepGracePeriod: external_exports.number().optional().describe(
14790
- `Max time in ms for the graceful shutdown window. Covers lifecycle hooks (onSleep, onDestroy), the run handler wait, async raw WebSocket handlers, disconnect callbacks, and final state serialization. Default: ${DEFAULT_SLEEP_GRACE_PERIOD}.`
14791
- ),
14792
- onDestroyTimeout: external_exports.number().optional().describe(
14793
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
14794
- ),
14795
- waitUntilTimeout: external_exports.number().optional().describe(
14796
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
14797
- ),
14798
- stateSaveInterval: external_exports.number().optional().describe(
14799
- "Interval in ms between automatic state saves. Default: 1000"
14800
- ),
14801
- actionTimeout: external_exports.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
14802
- connectionLivenessTimeout: external_exports.number().optional().describe(
14803
- "Timeout in ms for connection liveness checks. Default: 2500"
14804
- ),
14805
- connectionLivenessInterval: external_exports.number().optional().describe(
14806
- "Interval in ms between connection liveness checks. Default: 5000"
14807
- ),
14808
- noSleep: external_exports.boolean().optional().describe(
14809
- "Deprecated. If true, the actor will never sleep. Use c.keepAwake(promise) to scope keep-awake to a specific operation instead. Default: false"
14810
- ),
14811
- sleepTimeout: external_exports.number().optional().describe(
14812
- "Time in ms of inactivity before the actor sleeps. Default: 30000"
14813
- ),
14814
- maxQueueSize: external_exports.number().optional().describe(
14815
- "Maximum number of queue messages before rejecting new messages. Default: 1000"
14816
- ),
14817
- maxQueueMessageSize: external_exports.number().optional().describe(
14818
- "Maximum size of each queue message in bytes. Default: 65536"
14819
- ),
14820
- canHibernateWebSocket: external_exports.boolean().optional().describe(
14821
- "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
14822
- )
14823
- }).describe("Actor options for timeouts and behavior configuration.");
14824
- var DocActorConfigSchema = external_exports.object({
14825
- state: external_exports.unknown().optional().describe(
14826
- "Initial state value for the actor. Cannot be used with createState."
14827
- ),
14828
- createState: external_exports.unknown().optional().describe(
14829
- "Function to create initial state. Receives context and input. Cannot be used with state."
14830
- ),
14831
- connState: external_exports.unknown().optional().describe(
14832
- "Initial connection state value. Cannot be used with createConnState."
14833
- ),
14834
- createConnState: external_exports.unknown().optional().describe(
14835
- "Function to create connection state. Receives context and connection params. The pending connection is not visible in c.conns until this succeeds. Cannot be used with connState."
14836
- ),
14837
- vars: external_exports.unknown().optional().describe(
14838
- "Initial ephemeral variables value. Cannot be used with createVars."
14839
- ),
14840
- createVars: external_exports.unknown().optional().describe(
14841
- "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
14842
- ),
14843
- db: external_exports.unknown().optional().describe("Database provider instance for the actor."),
14844
- onCreate: external_exports.unknown().optional().describe(
14845
- "Called when the actor is first initialized. Use to initialize state."
14846
- ),
14847
- onDestroy: external_exports.unknown().optional().describe("Called when the actor is destroyed."),
14848
- onMigrate: external_exports.unknown().optional().describe(
14849
- "Called on every actor start after persisted state loads and before onWake. Use for repeatable schema migrations."
14850
- ),
14851
- onWake: external_exports.unknown().optional().describe(
14852
- "Called when the actor wakes up and is ready to receive connections and actions."
14853
- ),
14854
- onSleep: external_exports.unknown().optional().describe(
14855
- "Called when the actor is stopping or sleeping. Use to clean up resources."
14856
- ),
14857
- run: external_exports.unknown().optional().describe(
14858
- "Called after actor starts. Does not block startup. Use for background tasks like queue processing or tick loops. If it exits, the actor follows the normal idle sleep timeout once idle. If it throws, the actor logs the error and then follows the normal idle sleep timeout once idle."
14859
- ),
14860
- onStateChange: external_exports.unknown().optional().describe(
14861
- "Called when the actor's state changes. State changes within this hook won't trigger recursion."
14862
- ),
14863
- onBeforeConnect: external_exports.unknown().optional().describe(
14864
- "Called before a client connects. Throw an error to reject the connection. The pending connection is not visible in c.conns while this runs."
14865
- ),
14866
- onConnect: external_exports.unknown().optional().describe(
14867
- "Called when a client successfully connects. The connection is visible in c.conns before this runs."
14868
- ),
14869
- onDisconnect: external_exports.unknown().optional().describe("Called when a client disconnects."),
14870
- onBeforeActionResponse: external_exports.unknown().optional().describe(
14871
- "Called before sending an action response. Use to transform output."
14872
- ),
14873
- onRequest: external_exports.unknown().optional().describe(
14874
- "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
14875
- ),
14876
- onWebSocket: external_exports.unknown().optional().describe(
14877
- "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
14878
- ),
14879
- actions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
14880
- "Map of action name to handler function. Defaults to an empty object."
14881
- ),
14882
- actionInputSchemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
14883
- "Optional schema map for validating action argument tuples in native runtimes."
14884
- ),
14885
- connParamsSchema: external_exports.unknown().optional().describe(
14886
- "Optional schema for validating connection params in native runtimes."
14887
- ),
14888
- events: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of event names to schemas."),
14889
- queues: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of queue names to schemas."),
14890
- options: DocActorOptionsSchema.optional()
14891
- }).describe("Actor configuration passed to the actor() function.");
14892
-
14893
- // ../rivetkit/dist/tsup/chunk-JI6GZ2C2.js
14894
- var EMPTY_KEY = "/";
14895
- var KEY_SEPARATOR = "/";
14896
- var KEYS = {
14897
- PERSIST_DATA: Uint8Array.from([1]),
14898
- CONN_PREFIX: Uint8Array.from([2]),
14899
- INSPECTOR_TOKEN: Uint8Array.from([3]),
14900
- KV: Uint8Array.from([4]),
14901
- QUEUE_PREFIX: Uint8Array.from([5]),
14902
- LAST_PUSHED_ALARM: Uint8Array.from([6]),
14903
- WORKFLOW_PREFIX: Uint8Array.from([6]),
14904
- TRACES_PREFIX: Uint8Array.from([7])
14905
- };
14906
- var STORAGE_VERSION = {
14907
- QUEUE: 1,
14908
- WORKFLOW: 1,
14909
- TRACES: 1
14910
- };
14911
- var STORAGE_VERSION_BYTES = {
14912
- QUEUE: Uint8Array.from([STORAGE_VERSION.QUEUE]),
14913
- WORKFLOW: Uint8Array.from([STORAGE_VERSION.WORKFLOW]),
14914
- TRACES: Uint8Array.from([STORAGE_VERSION.TRACES])
14915
- };
14916
- var QUEUE_NAMESPACE = {
14917
- METADATA: Uint8Array.from([1]),
14918
- MESSAGES: Uint8Array.from([2])
14919
- };
14920
- function concatPrefix(prefix, suffix) {
14921
- const merged = new Uint8Array(prefix.length + suffix.length);
14922
- merged.set(prefix, 0);
14923
- merged.set(suffix, prefix.length);
14924
- return merged;
14925
- }
14926
- var QUEUE_STORAGE_PREFIX = concatPrefix(
14927
- KEYS.QUEUE_PREFIX,
14928
- STORAGE_VERSION_BYTES.QUEUE
14929
- );
14930
- var QUEUE_METADATA_KEY = concatPrefix(
14931
- QUEUE_STORAGE_PREFIX,
14932
- QUEUE_NAMESPACE.METADATA
14933
- );
14934
- var QUEUE_MESSAGES_PREFIX = concatPrefix(
14935
- QUEUE_STORAGE_PREFIX,
14936
- QUEUE_NAMESPACE.MESSAGES
14937
- );
14938
- var WORKFLOW_STORAGE_PREFIX = concatPrefix(
14939
- KEYS.WORKFLOW_PREFIX,
14940
- STORAGE_VERSION_BYTES.WORKFLOW
14941
- );
14942
- var TRACES_STORAGE_PREFIX = concatPrefix(
14943
- KEYS.TRACES_PREFIX,
14944
- STORAGE_VERSION_BYTES.TRACES
14945
- );
14946
- function serializeActorKey(key) {
14947
- if (key.length === 0) {
14948
- return EMPTY_KEY;
14531
+ try {
14532
+ return UTF8_DECODER.decode(readUnsafeU8FixedArray(bc, byteLen));
14533
+ } catch (_cause) {
14534
+ throw new BareError(bc.offset, INVALID_UTF8_STRING);
14949
14535
  }
14950
- const escapedParts = key.map((part) => {
14951
- if (part === "") {
14952
- return "\\0";
14953
- }
14954
- let escaped = part.replace(/\\/g, "\\\\");
14955
- escaped = escaped.replace(/\//g, `\\${KEY_SEPARATOR}`);
14956
- return escaped;
14957
- });
14958
- return escapedParts.join(KEY_SEPARATOR);
14959
14536
  }
14960
- function deserializeActorKey(keyString) {
14961
- if (keyString === void 0 || keyString === null || keyString === EMPTY_KEY) {
14962
- return [];
14963
- }
14964
- const parts = [];
14965
- let currentPart = "";
14966
- let escaping = false;
14967
- let isEmptyStringMarker = false;
14968
- for (let i = 0; i < keyString.length; i++) {
14969
- const char = keyString[i];
14970
- if (escaping) {
14971
- if (char === "0") {
14972
- isEmptyStringMarker = true;
14973
- } else {
14974
- currentPart += char;
14975
- }
14976
- escaping = false;
14977
- } else if (char === "\\") {
14978
- escaping = true;
14979
- } else if (char === KEY_SEPARATOR) {
14980
- if (isEmptyStringMarker) {
14981
- parts.push("");
14982
- isEmptyStringMarker = false;
14983
- } else {
14984
- parts.push(currentPart);
14537
+ function readUtf8Js(bc, byteLen) {
14538
+ check2(bc, byteLen);
14539
+ let result = "";
14540
+ const bytes = bc.bytes;
14541
+ let offset = bc.offset;
14542
+ const upperOffset = offset + byteLen;
14543
+ while (offset < upperOffset) {
14544
+ let codePoint = bytes[offset++];
14545
+ if (codePoint > 127) {
14546
+ let malformed = true;
14547
+ const byte1 = codePoint;
14548
+ if (offset < upperOffset && codePoint < 224) {
14549
+ const byte2 = bytes[offset++];
14550
+ codePoint = (byte1 & 31) << 6 | byte2 & 63;
14551
+ malformed = codePoint >> 7 === 0 || // non-canonical char
14552
+ byte1 >> 5 !== 6 || // invalid tag
14553
+ byte2 >> 6 !== 2;
14554
+ } else if (offset + 1 < upperOffset && codePoint < 240) {
14555
+ const byte2 = bytes[offset++];
14556
+ const byte3 = bytes[offset++];
14557
+ codePoint = (byte1 & 15) << 12 | (byte2 & 63) << 6 | byte3 & 63;
14558
+ malformed = codePoint >> 11 === 0 || // non-canonical char or missing data
14559
+ codePoint >> 11 === 27 || // surrogate char (0xD800 <= codePoint <= 0xDFFF)
14560
+ byte1 >> 4 !== 14 || // invalid tag
14561
+ byte2 >> 6 !== 2 || // invalid tag
14562
+ byte3 >> 6 !== 2;
14563
+ } else if (offset + 2 < upperOffset) {
14564
+ const byte2 = bytes[offset++];
14565
+ const byte3 = bytes[offset++];
14566
+ const byte4 = bytes[offset++];
14567
+ codePoint = (byte1 & 7) << 18 | (byte2 & 63) << 12 | (byte3 & 63) << 6 | byte4 & 63;
14568
+ malformed = codePoint >> 16 === 0 || // non-canonical char or missing data
14569
+ codePoint > 1114111 || // too large code point
14570
+ byte1 >> 3 !== 30 || // invalid tag
14571
+ byte2 >> 6 !== 2 || // invalid tag
14572
+ byte3 >> 6 !== 2 || // invalid tag
14573
+ byte4 >> 6 !== 2;
14574
+ }
14575
+ if (malformed) {
14576
+ throw new BareError(bc.offset, INVALID_UTF8_STRING);
14985
14577
  }
14986
- currentPart = "";
14987
- } else {
14988
- currentPart += char;
14989
14578
  }
14579
+ result += String.fromCodePoint(codePoint);
14990
14580
  }
14991
- if (escaping) {
14992
- parts.push(`${currentPart}\\`);
14993
- } else if (isEmptyStringMarker) {
14994
- parts.push("");
14995
- } else if (currentPart !== "" || parts.length > 0) {
14996
- parts.push(currentPart);
14581
+ bc.offset = offset;
14582
+ return result;
14583
+ }
14584
+ function writeUtf8Js(bc, s) {
14585
+ const bytes = bc.bytes;
14586
+ let offset = bc.offset;
14587
+ let i = 0;
14588
+ while (i < s.length) {
14589
+ const codePoint = s.codePointAt(i++);
14590
+ if (codePoint < 128) {
14591
+ bytes[offset++] = codePoint;
14592
+ } else {
14593
+ if (codePoint < 2048) {
14594
+ bytes[offset++] = 192 | codePoint >> 6;
14595
+ } else {
14596
+ if (codePoint < 65536) {
14597
+ bytes[offset++] = 224 | codePoint >> 12;
14598
+ } else {
14599
+ bytes[offset++] = 240 | codePoint >> 18;
14600
+ bytes[offset++] = 128 | codePoint >> 12 & 63;
14601
+ i++;
14602
+ }
14603
+ bytes[offset++] = 128 | codePoint >> 6 & 63;
14604
+ }
14605
+ bytes[offset++] = 128 | codePoint & 63;
14606
+ }
14997
14607
  }
14998
- return parts;
14608
+ bc.offset = offset;
14999
14609
  }
15000
- function makePrefixedKey(key) {
15001
- const prefixed = new Uint8Array(KEYS.KV.length + key.length);
15002
- prefixed.set(KEYS.KV, 0);
15003
- prefixed.set(key, KEYS.KV.length);
15004
- return prefixed;
14610
+ function utf8ByteLength(s) {
14611
+ let result = s.length;
14612
+ for (let i = 0; i < s.length; i++) {
14613
+ const codePoint = s.codePointAt(i);
14614
+ if (codePoint > 127) {
14615
+ result++;
14616
+ if (codePoint > 2047) {
14617
+ result++;
14618
+ if (codePoint > 65535) {
14619
+ i++;
14620
+ }
14621
+ }
14622
+ }
14623
+ }
14624
+ return result;
15005
14625
  }
15006
- function removePrefixFromKey(prefixedKey) {
15007
- return prefixedKey.slice(KEYS.KV.length);
14626
+ var UTF8_DECODER = /* @__PURE__ */ new TextDecoder("utf-8", { fatal: true });
14627
+ var UTF8_ENCODER = /* @__PURE__ */ new TextEncoder();
14628
+
14629
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/core/config.js
14630
+ function Config({ initialBufferLength = 1024, maxBufferLength = 1024 * 1024 * 32 }) {
14631
+ if (DEV) {
14632
+ assert2(isU32(initialBufferLength), TOO_LARGE_NUMBER);
14633
+ assert2(isU32(maxBufferLength), TOO_LARGE_NUMBER);
14634
+ assert2(initialBufferLength <= maxBufferLength, "initialBufferLength must be lower than or equal to maxBufferLength");
14635
+ }
14636
+ return {
14637
+ initialBufferLength,
14638
+ maxBufferLength
14639
+ };
15008
14640
  }
15009
14641
 
15010
- // ../rivetkit/dist/tsup/chunk-PM4ACAVN.js
15011
- var cbor = __toESM(require("cbor-x"), 1);
15012
- var import_invariant = __toESM(require_invariant(), 1);
15013
- var JSON_COMPAT_BIGINT = "$BigInt";
15014
- var JSON_COMPAT_ARRAY_BUFFER = "$ArrayBuffer";
15015
- var JSON_COMPAT_UINT8_ARRAY = "$Uint8Array";
15016
- var JSON_COMPAT_UNDEFINED = "$Undefined";
15017
- var JSON_COMPAT_SET = "$Set";
15018
- function isTypedArray(value) {
15019
- return value instanceof Uint8ClampedArray || value instanceof Uint16Array || value instanceof Uint32Array || value instanceof BigUint64Array || value instanceof Int8Array || value instanceof Int16Array || value instanceof Int32Array || value instanceof BigInt64Array || value instanceof Float32Array || value instanceof Float64Array;
14642
+ // ../rivetkit/dist/tsup/chunk-ULYPJPHB.js
14643
+ var config2 = /* @__PURE__ */ Config({});
14644
+ function readWorkflowCbor(bc) {
14645
+ return readData(bc);
15020
14646
  }
15021
- function assertJsonCompatValue(value, path2 = "") {
15022
- var _a2;
15023
- if (value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
15024
- return;
15025
- }
15026
- if (typeof value === "function") {
15027
- throw new TypeError(
15028
- `Value at ${path2 || "root"} is a function and is not CBOR serializable`
15029
- );
15030
- }
15031
- if (typeof value === "symbol") {
15032
- throw new TypeError(
15033
- `Value at ${path2 || "root"} is a symbol and is not CBOR serializable`
15034
- );
15035
- }
15036
- if (value instanceof Date || value instanceof RegExp || value instanceof Error || value instanceof ArrayBuffer || value instanceof Uint8Array || isTypedArray(value)) {
15037
- return;
15038
- }
15039
- if (value instanceof WeakMap) {
15040
- throw new TypeError(
15041
- `Value at ${path2 || "root"} is a WeakMap and is not CBOR serializable`
15042
- );
15043
- }
15044
- if (value instanceof WeakSet) {
15045
- throw new TypeError(
15046
- `Value at ${path2 || "root"} is a WeakSet and is not CBOR serializable`
15047
- );
15048
- }
15049
- if (value instanceof WeakRef) {
15050
- throw new TypeError(
15051
- `Value at ${path2 || "root"} is a WeakRef and is not CBOR serializable`
15052
- );
15053
- }
15054
- if (value instanceof Promise) {
15055
- throw new TypeError(
15056
- `Value at ${path2 || "root"} is a Promise and is not CBOR serializable`
15057
- );
15058
- }
15059
- if (value instanceof Map) {
15060
- for (const [k, v] of value.entries()) {
15061
- assertJsonCompatValue(k, `${path2 || "root"}.key(${String(k)})`);
15062
- assertJsonCompatValue(v, `${path2 || "root"}.value(${String(k)})`);
14647
+ function readWorkflowNameIndex(bc) {
14648
+ return readU32(bc);
14649
+ }
14650
+ function readWorkflowLoopIterationMarker(bc) {
14651
+ return {
14652
+ loop: readWorkflowNameIndex(bc),
14653
+ iteration: readU32(bc)
14654
+ };
14655
+ }
14656
+ function readWorkflowPathSegment(bc) {
14657
+ const offset = bc.offset;
14658
+ const tag = readU8(bc);
14659
+ switch (tag) {
14660
+ case 0:
14661
+ return { tag: "WorkflowNameIndex", val: readWorkflowNameIndex(bc) };
14662
+ case 1:
14663
+ return {
14664
+ tag: "WorkflowLoopIterationMarker",
14665
+ val: readWorkflowLoopIterationMarker(bc)
14666
+ };
14667
+ default: {
14668
+ bc.offset = offset;
14669
+ throw new BareError(offset, "invalid tag");
15063
14670
  }
15064
- return;
15065
14671
  }
15066
- if (value instanceof Set) {
15067
- let index = 0;
15068
- for (const item of value.values()) {
15069
- assertJsonCompatValue(item, `${path2 || "root"}.set[${index}]`);
15070
- index++;
15071
- }
15072
- return;
14672
+ }
14673
+ function readWorkflowLocation(bc) {
14674
+ const len = readUintSafe(bc);
14675
+ if (len === 0) {
14676
+ return [];
15073
14677
  }
15074
- if (Array.isArray(value)) {
15075
- for (let i = 0; i < value.length; i++) {
15076
- assertJsonCompatValue(value[i], `${path2 || "root"}[${i}]`);
15077
- }
15078
- return;
14678
+ const result = [readWorkflowPathSegment(bc)];
14679
+ for (let i = 1; i < len; i++) {
14680
+ result[i] = readWorkflowPathSegment(bc);
15079
14681
  }
15080
- if (isPlainObject2(value)) {
15081
- for (const key in value) {
15082
- assertJsonCompatValue(
15083
- value[key],
15084
- path2 ? `${path2}.${key}` : key
15085
- );
14682
+ return result;
14683
+ }
14684
+ function readWorkflowEntryStatus(bc) {
14685
+ const offset = bc.offset;
14686
+ const tag = readU8(bc);
14687
+ switch (tag) {
14688
+ case 0:
14689
+ return "PENDING";
14690
+ case 1:
14691
+ return "RUNNING";
14692
+ case 2:
14693
+ return "COMPLETED";
14694
+ case 3:
14695
+ return "FAILED";
14696
+ case 4:
14697
+ return "EXHAUSTED";
14698
+ default: {
14699
+ bc.offset = offset;
14700
+ throw new BareError(offset, "invalid tag");
15086
14701
  }
15087
- return;
15088
14702
  }
15089
- const typeName = typeof value === "object" && value !== null ? ((_a2 = value.constructor) == null ? void 0 : _a2.name) ?? typeof value : typeof value;
15090
- throw new TypeError(
15091
- `Value at ${path2 || "root"} of type "${typeName}" is not CBOR serializable`
15092
- );
15093
14703
  }
15094
- var EncodingSchema = external_exports.enum(["json", "cbor", "bare"]);
15095
- async function inputDataToBuffer(data) {
15096
- if (typeof data === "string") {
15097
- return data;
15098
- }
15099
- if (data instanceof Blob) {
15100
- return new Uint8Array(await data.arrayBuffer());
15101
- }
15102
- if (data instanceof Uint8Array) {
15103
- return data;
15104
- }
15105
- if (data instanceof ArrayBuffer || data instanceof SharedArrayBuffer) {
15106
- return new Uint8Array(data);
14704
+ function readWorkflowSleepState(bc) {
14705
+ const offset = bc.offset;
14706
+ const tag = readU8(bc);
14707
+ switch (tag) {
14708
+ case 0:
14709
+ return "PENDING";
14710
+ case 1:
14711
+ return "COMPLETED";
14712
+ case 2:
14713
+ return "INTERRUPTED";
14714
+ default: {
14715
+ bc.offset = offset;
14716
+ throw new BareError(offset, "invalid tag");
14717
+ }
15107
14718
  }
15108
- throw new Error("Malformed message");
15109
14719
  }
15110
- function base64EncodeUint8Array(uint8Array) {
15111
- let binary = "";
15112
- for (const value of uint8Array) {
15113
- binary += String.fromCharCode(value);
14720
+ function readWorkflowBranchStatusType(bc) {
14721
+ const offset = bc.offset;
14722
+ const tag = readU8(bc);
14723
+ switch (tag) {
14724
+ case 0:
14725
+ return "PENDING";
14726
+ case 1:
14727
+ return "RUNNING";
14728
+ case 2:
14729
+ return "COMPLETED";
14730
+ case 3:
14731
+ return "FAILED";
14732
+ case 4:
14733
+ return "CANCELLED";
14734
+ default: {
14735
+ bc.offset = offset;
14736
+ throw new BareError(offset, "invalid tag");
14737
+ }
15114
14738
  }
15115
- return btoa(binary);
15116
14739
  }
15117
- function base64EncodeArrayBuffer(arrayBuffer) {
15118
- return base64EncodeUint8Array(new Uint8Array(arrayBuffer));
14740
+ function read0(bc) {
14741
+ return readBool(bc) ? readWorkflowCbor(bc) : null;
15119
14742
  }
15120
- function isPlainObject2(value) {
15121
- if (value === null || typeof value !== "object") {
15122
- return false;
15123
- }
15124
- const proto = Object.getPrototypeOf(value);
15125
- return proto === Object.prototype || proto === null;
14743
+ function read1(bc) {
14744
+ return readBool(bc) ? readString(bc) : null;
15126
14745
  }
15127
- function encodeJsonCompatValue(input) {
15128
- var _a2;
15129
- if (input === null) {
15130
- return input;
14746
+ function readWorkflowStepEntry(bc) {
14747
+ return {
14748
+ output: read0(bc),
14749
+ error: read1(bc)
14750
+ };
14751
+ }
14752
+ function readWorkflowLoopEntry(bc) {
14753
+ return {
14754
+ state: readWorkflowCbor(bc),
14755
+ iteration: readU32(bc),
14756
+ output: read0(bc)
14757
+ };
14758
+ }
14759
+ function readWorkflowSleepEntry(bc) {
14760
+ return {
14761
+ deadline: readU64(bc),
14762
+ state: readWorkflowSleepState(bc)
14763
+ };
14764
+ }
14765
+ function readWorkflowMessageEntry(bc) {
14766
+ return {
14767
+ name: readString(bc),
14768
+ messageData: readWorkflowCbor(bc)
14769
+ };
14770
+ }
14771
+ function readWorkflowRollbackCheckpointEntry(bc) {
14772
+ return {
14773
+ name: readString(bc)
14774
+ };
14775
+ }
14776
+ function readWorkflowBranchStatus(bc) {
14777
+ return {
14778
+ status: readWorkflowBranchStatusType(bc),
14779
+ output: read0(bc),
14780
+ error: read1(bc)
14781
+ };
14782
+ }
14783
+ function read2(bc) {
14784
+ const len = readUintSafe(bc);
14785
+ const result = /* @__PURE__ */ new Map();
14786
+ for (let i = 0; i < len; i++) {
14787
+ const offset = bc.offset;
14788
+ const key = readString(bc);
14789
+ if (result.has(key)) {
14790
+ bc.offset = offset;
14791
+ throw new BareError(offset, "duplicated key");
14792
+ }
14793
+ result.set(key, readWorkflowBranchStatus(bc));
15131
14794
  }
15132
- if (input === void 0) {
15133
- return [JSON_COMPAT_UNDEFINED, 0];
14795
+ return result;
14796
+ }
14797
+ function readWorkflowJoinEntry(bc) {
14798
+ return {
14799
+ branches: read2(bc)
14800
+ };
14801
+ }
14802
+ function readWorkflowRaceEntry(bc) {
14803
+ return {
14804
+ winner: read1(bc),
14805
+ branches: read2(bc)
14806
+ };
14807
+ }
14808
+ function readWorkflowRemovedEntry(bc) {
14809
+ return {
14810
+ originalType: readString(bc),
14811
+ originalName: read1(bc)
14812
+ };
14813
+ }
14814
+ function readWorkflowVersionCheckEntry(bc) {
14815
+ return {
14816
+ resolved: readU32(bc),
14817
+ latest: readU32(bc)
14818
+ };
14819
+ }
14820
+ function readWorkflowEntryKind(bc) {
14821
+ const offset = bc.offset;
14822
+ const tag = readU8(bc);
14823
+ switch (tag) {
14824
+ case 0:
14825
+ return { tag: "WorkflowStepEntry", val: readWorkflowStepEntry(bc) };
14826
+ case 1:
14827
+ return { tag: "WorkflowLoopEntry", val: readWorkflowLoopEntry(bc) };
14828
+ case 2:
14829
+ return {
14830
+ tag: "WorkflowSleepEntry",
14831
+ val: readWorkflowSleepEntry(bc)
14832
+ };
14833
+ case 3:
14834
+ return {
14835
+ tag: "WorkflowMessageEntry",
14836
+ val: readWorkflowMessageEntry(bc)
14837
+ };
14838
+ case 4:
14839
+ return {
14840
+ tag: "WorkflowRollbackCheckpointEntry",
14841
+ val: readWorkflowRollbackCheckpointEntry(bc)
14842
+ };
14843
+ case 5:
14844
+ return { tag: "WorkflowJoinEntry", val: readWorkflowJoinEntry(bc) };
14845
+ case 6:
14846
+ return { tag: "WorkflowRaceEntry", val: readWorkflowRaceEntry(bc) };
14847
+ case 7:
14848
+ return {
14849
+ tag: "WorkflowRemovedEntry",
14850
+ val: readWorkflowRemovedEntry(bc)
14851
+ };
14852
+ case 8:
14853
+ return {
14854
+ tag: "WorkflowVersionCheckEntry",
14855
+ val: readWorkflowVersionCheckEntry(bc)
14856
+ };
14857
+ default: {
14858
+ bc.offset = offset;
14859
+ throw new BareError(offset, "invalid tag");
14860
+ }
15134
14861
  }
15135
- if (typeof input === "string" || typeof input === "number" || typeof input === "boolean") {
15136
- return input;
14862
+ }
14863
+ function readWorkflowEntry(bc) {
14864
+ return {
14865
+ id: readString(bc),
14866
+ location: readWorkflowLocation(bc),
14867
+ kind: readWorkflowEntryKind(bc)
14868
+ };
14869
+ }
14870
+ function read3(bc) {
14871
+ return readBool(bc) ? readU64(bc) : null;
14872
+ }
14873
+ function readWorkflowEntryMetadata(bc) {
14874
+ return {
14875
+ status: readWorkflowEntryStatus(bc),
14876
+ error: read1(bc),
14877
+ attempts: readU32(bc),
14878
+ lastAttemptAt: readU64(bc),
14879
+ createdAt: readU64(bc),
14880
+ completedAt: read3(bc),
14881
+ rollbackCompletedAt: read3(bc),
14882
+ rollbackError: read1(bc)
14883
+ };
14884
+ }
14885
+ function read4(bc) {
14886
+ const len = readUintSafe(bc);
14887
+ if (len === 0) {
14888
+ return [];
15137
14889
  }
15138
- if (typeof input === "bigint") {
15139
- return [JSON_COMPAT_BIGINT, input.toString()];
14890
+ const result = [readString(bc)];
14891
+ for (let i = 1; i < len; i++) {
14892
+ result[i] = readString(bc);
15140
14893
  }
15141
- if (input instanceof ArrayBuffer) {
15142
- return [JSON_COMPAT_ARRAY_BUFFER, base64EncodeArrayBuffer(input)];
14894
+ return result;
14895
+ }
14896
+ function read5(bc) {
14897
+ const len = readUintSafe(bc);
14898
+ if (len === 0) {
14899
+ return [];
15143
14900
  }
15144
- if (input instanceof Uint8Array) {
15145
- return [JSON_COMPAT_UINT8_ARRAY, base64EncodeUint8Array(input)];
14901
+ const result = [readWorkflowEntry(bc)];
14902
+ for (let i = 1; i < len; i++) {
14903
+ result[i] = readWorkflowEntry(bc);
15146
14904
  }
15147
- if (isTypedArray(input)) {
15148
- return input;
14905
+ return result;
14906
+ }
14907
+ function read6(bc) {
14908
+ const len = readUintSafe(bc);
14909
+ const result = /* @__PURE__ */ new Map();
14910
+ for (let i = 0; i < len; i++) {
14911
+ const offset = bc.offset;
14912
+ const key = readString(bc);
14913
+ if (result.has(key)) {
14914
+ bc.offset = offset;
14915
+ throw new BareError(offset, "duplicated key");
14916
+ }
14917
+ result.set(key, readWorkflowEntryMetadata(bc));
15149
14918
  }
15150
- if (input instanceof Date || input instanceof RegExp || input instanceof Error) {
15151
- return input;
14919
+ return result;
14920
+ }
14921
+ function readWorkflowHistory(bc) {
14922
+ return {
14923
+ nameRegistry: read4(bc),
14924
+ entries: read5(bc),
14925
+ entryMetadata: read6(bc)
14926
+ };
14927
+ }
14928
+ function decodeWorkflowHistory(bytes) {
14929
+ const bc = new ByteCursor(bytes, config2);
14930
+ const result = readWorkflowHistory(bc);
14931
+ if (bc.offset < bc.view.byteLength) {
14932
+ throw new BareError(bc.offset, "remaining bytes");
15152
14933
  }
15153
- if (input instanceof Set) {
15154
- const encoded = [...input.values()].map(
15155
- (v) => encodeJsonCompatValue(v)
15156
- );
15157
- return [JSON_COMPAT_SET, encoded];
15158
- }
15159
- if (input instanceof Map) {
15160
- const encoded = /* @__PURE__ */ new Map();
15161
- for (const [k, v] of input.entries()) {
15162
- encoded.set(
15163
- encodeJsonCompatValue(k),
15164
- encodeJsonCompatValue(v)
14934
+ return result;
14935
+ }
14936
+ function decodeWorkflowHistoryTransport(data) {
14937
+ return decodeWorkflowHistory(toUint8Array(data));
14938
+ }
14939
+
14940
+ // ../rivetkit/dist/tsup/chunk-QWLJCP3X.js
14941
+ function flattenActionHandlers(actions) {
14942
+ const flattened = /* @__PURE__ */ Object.create(null);
14943
+ for (const { name, handler } of collectActionEntries(actions)) {
14944
+ flattened[name] = handler;
14945
+ }
14946
+ return flattened;
14947
+ }
14948
+ function flattenActionInputSchemas(actions, schemas) {
14949
+ if (schemas === void 0) return void 0;
14950
+ if (!isRecord(schemas)) {
14951
+ throw new TypeError("actionInputSchemas must be an object");
14952
+ }
14953
+ const flattened = /* @__PURE__ */ Object.create(null);
14954
+ for (const { name, path: path2 } of collectActionEntries(actions)) {
14955
+ const nestedSchema = lookupNestedSchema(schemas, path2);
14956
+ const flatSchema = schemas[name];
14957
+ if (nestedSchema !== void 0 && flatSchema !== void 0 && nestedSchema !== flatSchema) {
14958
+ throw new TypeError(
14959
+ `Action input schema \`${name}\` is defined by both a nested path and a dotted key`
15165
14960
  );
15166
14961
  }
15167
- return encoded;
14962
+ const schema = nestedSchema ?? flatSchema;
14963
+ if (schema !== void 0) {
14964
+ flattened[name] = schema;
14965
+ }
15168
14966
  }
15169
- if (Array.isArray(input)) {
15170
- const encoded = input.map(
15171
- (value) => encodeJsonCompatValue(value)
14967
+ return flattened;
14968
+ }
14969
+ function collectActionEntries(actions) {
14970
+ const entries = [];
14971
+ const names = /* @__PURE__ */ new Set();
14972
+ visitActionGroup(actions ?? {}, [], entries, names);
14973
+ return entries;
14974
+ }
14975
+ function visitActionGroup(value, path2, entries, names) {
14976
+ if (!isRecord(value)) {
14977
+ throw new TypeError(
14978
+ `${formatActionPath(path2)} must be an action handler or group`
15172
14979
  );
15173
- if (encoded.length === 2 && typeof encoded[0] === "string" && encoded[0].startsWith("$")) {
15174
- return [`$${encoded[0]}`, encoded[1]];
15175
- }
15176
- return encoded;
15177
14980
  }
15178
- if (isPlainObject2(input)) {
15179
- const encoded = {};
15180
- for (const [key, value] of Object.entries(input)) {
15181
- encoded[key] = encodeJsonCompatValue(value);
14981
+ for (const [segment, child] of Object.entries(value)) {
14982
+ const childPath = [...path2, segment];
14983
+ if (typeof child === "function") {
14984
+ const name = childPath.join(".");
14985
+ if (names.has(name)) {
14986
+ throw new TypeError(
14987
+ `Multiple action definitions flatten to \`${name}\``
14988
+ );
14989
+ }
14990
+ names.add(name);
14991
+ entries.push({
14992
+ name,
14993
+ path: childPath,
14994
+ handler: child
14995
+ });
14996
+ } else {
14997
+ visitActionGroup(child, childPath, entries, names);
15182
14998
  }
15183
- return encoded;
15184
14999
  }
15185
- const typeName = typeof input === "object" && input !== null ? ((_a2 = input.constructor) == null ? void 0 : _a2.name) ?? typeof input : typeof input;
15186
- throw new TypeError(`Value of type "${typeName}" is not CBOR serializable`);
15187
15000
  }
15188
- function reviveJsonCompatValue(input, options = {}) {
15189
- if (typeof input === "bigint") {
15190
- if (options.coerceSafeIntegerBigInts && input >= BigInt(Number.MIN_SAFE_INTEGER) && input <= BigInt(Number.MAX_SAFE_INTEGER)) {
15191
- return Number(input);
15001
+ function lookupNestedSchema(schemas, path2) {
15002
+ let value = schemas;
15003
+ for (const segment of path2) {
15004
+ if (!isRecord(value) || !Object.hasOwn(value, segment)) {
15005
+ return void 0;
15192
15006
  }
15193
- return input;
15007
+ value = value[segment];
15194
15008
  }
15195
- if (input instanceof Map) {
15196
- const revived = /* @__PURE__ */ new Map();
15197
- for (const [k, v] of input.entries()) {
15198
- revived.set(
15199
- reviveJsonCompatValue(k, options),
15200
- reviveJsonCompatValue(v, options)
15201
- );
15202
- }
15203
- return revived;
15009
+ return value;
15010
+ }
15011
+ function isRecord(value) {
15012
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
15013
+ return false;
15204
15014
  }
15205
- if (Array.isArray(input)) {
15206
- if (input.length === 2 && typeof input[0] === "string" && input[0].startsWith("$")) {
15207
- if (input[0] === JSON_COMPAT_BIGINT) {
15208
- return BigInt(input[1]);
15209
- }
15210
- if (input[0] === JSON_COMPAT_ARRAY_BUFFER) {
15211
- return base64DecodeToArrayBuffer(input[1]);
15212
- }
15213
- if (input[0] === JSON_COMPAT_UINT8_ARRAY) {
15214
- return base64DecodeToUint8Array(input[1]);
15215
- }
15216
- if (input[0] === JSON_COMPAT_UNDEFINED) {
15217
- return void 0;
15218
- }
15219
- if (input[0] === JSON_COMPAT_SET) {
15220
- const items = input[1].map(
15221
- (v) => reviveJsonCompatValue(v, options)
15222
- );
15223
- return new Set(items);
15224
- }
15225
- if (input[0].startsWith("$$")) {
15226
- return [
15227
- input[0].substring(1),
15228
- reviveJsonCompatValue(input[1], options)
15229
- ];
15230
- }
15231
- throw new Error(
15232
- `Unknown JSON encoding type: ${input[0]}. This may indicate corrupted data or a version mismatch.`
15233
- );
15234
- }
15235
- return input.map((value) => reviveJsonCompatValue(value, options));
15015
+ const prototype = Object.getPrototypeOf(value);
15016
+ return prototype === Object.prototype || prototype === null;
15017
+ }
15018
+ function formatActionPath(path2) {
15019
+ return path2.length === 0 ? "actions" : `Action \`${path2.join(".")}\``;
15020
+ }
15021
+ var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
15022
+ var ACTOR_CONTEXT_INTERNAL_SYMBOL = /* @__PURE__ */ Symbol(
15023
+ "rivetkit.actor_context_internal"
15024
+ );
15025
+ var RAW_STATE_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.raw_state");
15026
+ var CONN_STATE_MANAGER_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.conn_state_manager");
15027
+ var zFunction = () => external_exports.custom((val) => typeof val === "function");
15028
+ var zActionTree = external_exports.custom((value) => {
15029
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
15030
+ return false;
15236
15031
  }
15237
- if (isPlainObject2(input)) {
15238
- const decoded = {};
15239
- for (const [key, value] of Object.entries(input)) {
15240
- decoded[key] = reviveJsonCompatValue(value, options);
15241
- }
15242
- return decoded;
15032
+ const prototype = Object.getPrototypeOf(value);
15033
+ return prototype === Object.prototype || prototype === null;
15034
+ }).superRefine((actions, ctx) => {
15035
+ try {
15036
+ flattenActionHandlers(actions);
15037
+ } catch (error46) {
15038
+ ctx.addIssue({
15039
+ code: "custom",
15040
+ message: error46 instanceof Error ? error46.message : "Invalid action definition"
15041
+ });
15243
15042
  }
15244
- return input;
15043
+ });
15044
+ var WorkflowInspectorConfigSchema = external_exports.object({
15045
+ getHistory: zFunction(),
15046
+ onHistoryUpdated: zFunction().optional(),
15047
+ replayFromStep: zFunction().optional()
15048
+ });
15049
+ var RunInspectorConfigSchema = external_exports.object({
15050
+ workflow: WorkflowInspectorConfigSchema.optional()
15051
+ }).optional();
15052
+ var BUILTIN_INSPECTOR_TAB_IDS = [
15053
+ "workflow",
15054
+ "database",
15055
+ "state",
15056
+ "queue",
15057
+ "schedules",
15058
+ "connections",
15059
+ "console"
15060
+ ];
15061
+ var BuiltinInspectorTabIdSchema = external_exports.enum(BUILTIN_INSPECTOR_TAB_IDS);
15062
+ var CUSTOM_INSPECTOR_TAB_ID_RE = /^[A-Za-z0-9_-]+$/;
15063
+ var CustomInspectorTabEntrySchema = external_exports.object({
15064
+ id: external_exports.string().regex(
15065
+ CUSTOM_INSPECTOR_TAB_ID_RE,
15066
+ "inspector.tabs[].id must contain only letters, digits, underscore, or dash"
15067
+ ),
15068
+ label: external_exports.string().min(1),
15069
+ source: external_exports.string().min(1),
15070
+ /**
15071
+ * Optional icon id. The dashboard maps strings to glyphs (see its
15072
+ * icon registry); unknown ids fall back to a generic icon.
15073
+ */
15074
+ icon: external_exports.string().min(1).optional(),
15075
+ hidden: external_exports.literal(false).optional()
15076
+ }).strict();
15077
+ var HideInspectorTabEntrySchema = external_exports.object({
15078
+ id: BuiltinInspectorTabIdSchema,
15079
+ hidden: external_exports.literal(true)
15080
+ }).strict();
15081
+ var InspectorTabEntrySchema = external_exports.union([
15082
+ CustomInspectorTabEntrySchema,
15083
+ HideInspectorTabEntrySchema
15084
+ ]);
15085
+ var ActorInspectorConfigSchema = external_exports.object({
15086
+ tabs: external_exports.array(InspectorTabEntrySchema).default(() => [])
15087
+ }).strict().refine(
15088
+ (data) => {
15089
+ const ids = data.tabs.map((t) => t.id);
15090
+ return new Set(ids).size === ids.length;
15091
+ },
15092
+ { message: "Duplicate id in inspector.tabs", path: ["tabs"] }
15093
+ ).refine(
15094
+ (data) => {
15095
+ const builtinSet = new Set(BUILTIN_INSPECTOR_TAB_IDS);
15096
+ return data.tabs.every(
15097
+ (t) => t.hidden === true || !builtinSet.has(t.id)
15098
+ );
15099
+ },
15100
+ {
15101
+ message: "Custom inspector tab id collides with a built-in (use hidden: true to hide a built-in)",
15102
+ path: ["tabs"]
15103
+ }
15104
+ );
15105
+ var RunConfigSchema = external_exports.object({
15106
+ /** Display name for the actor in the Inspector UI. */
15107
+ name: external_exports.string().optional(),
15108
+ /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
15109
+ icon: external_exports.string().optional(),
15110
+ /** The run handler function. */
15111
+ run: zFunction(),
15112
+ /** Inspector integration for long-running run handlers. */
15113
+ inspector: RunInspectorConfigSchema.optional()
15114
+ });
15115
+ var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for(
15116
+ "rivetkit.run_function_config"
15117
+ );
15118
+ var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
15119
+ function getRunFunction(run) {
15120
+ if (!run) return void 0;
15121
+ if (typeof run === "function") return run;
15122
+ return run.run;
15123
+ }
15124
+ function getRunMetadata(run) {
15125
+ if (!run) return {};
15126
+ if (typeof run === "function") {
15127
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15128
+ if (!config3) return {};
15129
+ return { name: config3.name, icon: config3.icon };
15130
+ }
15131
+ return { name: run.name, icon: run.icon };
15132
+ }
15133
+ function getRunInspectorConfig(run, actor2) {
15134
+ if (!run) return void 0;
15135
+ if (typeof run === "function") {
15136
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15137
+ return (config3 == null ? void 0 : config3.inspectorFactory) ? config3.inspectorFactory(actor2) : config3 == null ? void 0 : config3.inspector;
15138
+ }
15139
+ return run.inspector;
15140
+ }
15141
+ function disposeRunInspector(run, actorId) {
15142
+ var _a2;
15143
+ if (!run || typeof run !== "function") {
15144
+ return;
15145
+ }
15146
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15147
+ (_a2 = config3 == null ? void 0 : config3.disposeInspector) == null ? void 0 : _a2.call(config3, actorId);
15148
+ }
15149
+ var GlobalActorOptionsBaseSchema = external_exports.object({
15150
+ /** Display name for the actor in the Inspector UI. */
15151
+ name: external_exports.string().optional(),
15152
+ /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
15153
+ icon: external_exports.string().optional(),
15154
+ /** Enables the experimental Actor Runtime Socket for this actor. */
15155
+ enableActorRuntimeSocket: external_exports.boolean().default(false),
15156
+ /**
15157
+ * Can hibernate WebSockets for onWebSocket.
15158
+ *
15159
+ * WebSockets using actions/events are hibernatable by default.
15160
+ *
15161
+ * @experimental
15162
+ **/
15163
+ canHibernateWebSocket: external_exports.union([external_exports.boolean(), zFunction()]).default(false)
15164
+ }).strict();
15165
+ var GlobalActorOptionsSchema = GlobalActorOptionsBaseSchema.prefault(
15166
+ () => ({})
15167
+ );
15168
+ var InstanceActorOptionsBaseSchema = external_exports.object({
15169
+ createVarsTimeout: external_exports.number().positive().default(5e3),
15170
+ createConnStateTimeout: external_exports.number().positive().default(5e3),
15171
+ onBeforeConnectTimeout: external_exports.number().positive().default(5e3),
15172
+ onConnectTimeout: external_exports.number().positive().default(5e3),
15173
+ onMigrateTimeout: external_exports.number().positive().default(3e4),
15174
+ sleepGracePeriod: external_exports.number().positive().default(DEFAULT_SLEEP_GRACE_PERIOD),
15175
+ /** @deprecated `onDestroyTimeout` is folded into `sleepGracePeriod`, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0. */
15176
+ onDestroyTimeout: external_exports.number().positive().optional(),
15177
+ /** @deprecated `waitUntilTimeout` is folded into `sleepGracePeriod`, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0. */
15178
+ waitUntilTimeout: external_exports.number().positive().optional(),
15179
+ stateSaveInterval: external_exports.number().positive().default(1e3),
15180
+ actionTimeout: external_exports.number().positive().default(6e4),
15181
+ connectionLivenessTimeout: external_exports.number().positive().default(2500),
15182
+ connectionLivenessInterval: external_exports.number().positive().default(5e3),
15183
+ /** @deprecated Use `c.keepAwake(promise)` to scope keep-awake to a specific operation, or keep `noSleep` for actors that must stay awake indefinitely. Will be removed in 2.2.0. */
15184
+ noSleep: external_exports.boolean().default(false),
15185
+ sleepTimeout: external_exports.number().positive().default(3e4),
15186
+ maxQueueSize: external_exports.number().positive().default(1e3),
15187
+ /** Maximum pending one-shot and recurring schedules. */
15188
+ maxSchedules: external_exports.number().int().nonnegative().default(1e3),
15189
+ maxQueueMessageSize: external_exports.number().positive().default(64 * 1024),
15190
+ /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
15191
+ preloadMaxWorkflowBytes: external_exports.number().nonnegative().optional(),
15192
+ /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
15193
+ preloadMaxConnectionsBytes: external_exports.number().nonnegative().optional()
15194
+ }).strict();
15195
+ var InstanceActorOptionsSchema = InstanceActorOptionsBaseSchema.prefault(() => ({}));
15196
+ var ActorOptionsSchema = GlobalActorOptionsBaseSchema.extend(
15197
+ InstanceActorOptionsBaseSchema.shape
15198
+ ).strict().prefault(() => ({}));
15199
+ var ActorConfigSchema = external_exports.object({
15200
+ onCreate: zFunction().optional(),
15201
+ onDestroy: zFunction().optional(),
15202
+ onMigrate: zFunction().optional(),
15203
+ onWake: zFunction().optional(),
15204
+ onSleep: zFunction().optional(),
15205
+ run: zRunHandler,
15206
+ onStateChange: zFunction().optional(),
15207
+ onBeforeConnect: zFunction().optional(),
15208
+ onConnect: zFunction().optional(),
15209
+ onDisconnect: zFunction().optional(),
15210
+ onBeforeActionResponse: zFunction().optional(),
15211
+ onRequest: zFunction().optional(),
15212
+ onWebSocket: zFunction().optional(),
15213
+ actions: zActionTree.default(() => ({})),
15214
+ actionInputSchemas: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15215
+ connParamsSchema: external_exports.any().optional(),
15216
+ events: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15217
+ queues: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15218
+ state: external_exports.any().optional(),
15219
+ createState: zFunction().optional(),
15220
+ connState: external_exports.any().optional(),
15221
+ createConnState: zFunction().optional(),
15222
+ vars: external_exports.any().optional(),
15223
+ db: external_exports.any().optional(),
15224
+ createVars: zFunction().optional(),
15225
+ options: ActorOptionsSchema,
15226
+ inspector: ActorInspectorConfigSchema.optional()
15227
+ }).strict().refine(
15228
+ (data) => !(data.state !== void 0 && data.createState !== void 0),
15229
+ {
15230
+ message: "Cannot define both 'state' and 'createState'",
15231
+ path: ["state"]
15232
+ }
15233
+ ).refine(
15234
+ (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
15235
+ {
15236
+ message: "Cannot define both 'connState' and 'createConnState'",
15237
+ path: ["connState"]
15238
+ }
15239
+ ).refine(
15240
+ (data) => !(data.vars !== void 0 && data.createVars !== void 0),
15241
+ {
15242
+ message: "Cannot define both 'vars' and 'createVars'",
15243
+ path: ["vars"]
15244
+ }
15245
+ );
15246
+ var DocActorOptionsSchema = external_exports.object({
15247
+ name: external_exports.string().optional().describe("Display name for the actor in the Inspector UI."),
15248
+ icon: external_exports.string().optional().describe(
15249
+ "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
15250
+ ),
15251
+ enableActorRuntimeSocket: external_exports.boolean().optional().describe(
15252
+ "Enables the experimental Actor Runtime Socket for this actor. Default: false"
15253
+ ),
15254
+ createVarsTimeout: external_exports.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
15255
+ createConnStateTimeout: external_exports.number().optional().describe(
15256
+ "Timeout in ms for createConnState handler. Default: 5000"
15257
+ ),
15258
+ onMigrateTimeout: external_exports.number().optional().describe("Timeout in ms for onMigrate handler. Default: 30000"),
15259
+ onBeforeConnectTimeout: external_exports.number().optional().describe(
15260
+ "Timeout in ms for onBeforeConnect handler. Default: 5000"
15261
+ ),
15262
+ onConnectTimeout: external_exports.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
15263
+ sleepGracePeriod: external_exports.number().optional().describe(
15264
+ `Max time in ms for the graceful shutdown window. Covers lifecycle hooks (onSleep, onDestroy), the run handler wait, async raw WebSocket handlers, disconnect callbacks, and final state serialization. Default: ${DEFAULT_SLEEP_GRACE_PERIOD}.`
15265
+ ),
15266
+ onDestroyTimeout: external_exports.number().optional().describe(
15267
+ "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
15268
+ ),
15269
+ waitUntilTimeout: external_exports.number().optional().describe(
15270
+ "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
15271
+ ),
15272
+ stateSaveInterval: external_exports.number().optional().describe(
15273
+ "Interval in ms between automatic state saves. Default: 1000"
15274
+ ),
15275
+ actionTimeout: external_exports.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
15276
+ connectionLivenessTimeout: external_exports.number().optional().describe(
15277
+ "Timeout in ms for connection liveness checks. Default: 2500"
15278
+ ),
15279
+ connectionLivenessInterval: external_exports.number().optional().describe(
15280
+ "Interval in ms between connection liveness checks. Default: 5000"
15281
+ ),
15282
+ noSleep: external_exports.boolean().optional().describe(
15283
+ "Deprecated. If true, the actor will never sleep. Use c.keepAwake(promise) to scope keep-awake to a specific operation instead. Default: false"
15284
+ ),
15285
+ sleepTimeout: external_exports.number().optional().describe(
15286
+ "Time in ms of inactivity before the actor sleeps. Default: 30000"
15287
+ ),
15288
+ maxQueueSize: external_exports.number().optional().describe(
15289
+ "Maximum number of queue messages before rejecting new messages. Default: 1000"
15290
+ ),
15291
+ maxSchedules: external_exports.number().int().nonnegative().optional().describe(
15292
+ "Maximum pending one-shot and recurring schedules before rejecting new schedules. Default: 1000"
15293
+ ),
15294
+ maxQueueMessageSize: external_exports.number().optional().describe(
15295
+ "Maximum size of each queue message in bytes. Default: 65536"
15296
+ ),
15297
+ canHibernateWebSocket: external_exports.boolean().optional().describe(
15298
+ "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
15299
+ )
15300
+ }).describe("Actor options for timeouts and behavior configuration.");
15301
+ var DocActorConfigSchema = external_exports.object({
15302
+ state: external_exports.unknown().optional().describe(
15303
+ "Initial state value for the actor. Cannot be used with createState."
15304
+ ),
15305
+ createState: external_exports.unknown().optional().describe(
15306
+ "Function to create initial state. Receives context and input. Cannot be used with state."
15307
+ ),
15308
+ connState: external_exports.unknown().optional().describe(
15309
+ "Initial connection state value. Cannot be used with createConnState."
15310
+ ),
15311
+ createConnState: external_exports.unknown().optional().describe(
15312
+ "Function to create connection state. Receives context and connection params. The pending connection is not visible in c.conns until this succeeds. Cannot be used with connState."
15313
+ ),
15314
+ vars: external_exports.unknown().optional().describe(
15315
+ "Initial ephemeral variables value. Cannot be used with createVars."
15316
+ ),
15317
+ createVars: external_exports.unknown().optional().describe(
15318
+ "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
15319
+ ),
15320
+ db: external_exports.unknown().optional().describe("Database provider instance for the actor."),
15321
+ onCreate: external_exports.unknown().optional().describe(
15322
+ "Called when the actor is first initialized. Use to initialize state."
15323
+ ),
15324
+ onDestroy: external_exports.unknown().optional().describe("Called when the actor is destroyed."),
15325
+ onMigrate: external_exports.unknown().optional().describe(
15326
+ "Called on every actor start after persisted state loads and before onWake. Use for repeatable schema migrations."
15327
+ ),
15328
+ onWake: external_exports.unknown().optional().describe(
15329
+ "Called when the actor wakes up and is ready to receive connections and actions."
15330
+ ),
15331
+ onSleep: external_exports.unknown().optional().describe(
15332
+ "Called when the actor is stopping or sleeping. Use to clean up resources."
15333
+ ),
15334
+ run: external_exports.unknown().optional().describe(
15335
+ "Called after actor starts. Does not block startup. Use for background tasks like queue processing or tick loops. If it exits, the actor follows the normal idle sleep timeout once idle. If it throws, the actor logs the error and then follows the normal idle sleep timeout once idle."
15336
+ ),
15337
+ onStateChange: external_exports.unknown().optional().describe(
15338
+ "Called when the actor's state changes. State changes within this hook won't trigger recursion."
15339
+ ),
15340
+ onBeforeConnect: external_exports.unknown().optional().describe(
15341
+ "Called before a client connects. Throw an error to reject the connection. The pending connection is not visible in c.conns while this runs."
15342
+ ),
15343
+ onConnect: external_exports.unknown().optional().describe(
15344
+ "Called when a client successfully connects. The connection is visible in c.conns before this runs."
15345
+ ),
15346
+ onDisconnect: external_exports.unknown().optional().describe("Called when a client disconnects."),
15347
+ onBeforeActionResponse: external_exports.unknown().optional().describe(
15348
+ "Called before sending an action response. Use to transform output."
15349
+ ),
15350
+ onRequest: external_exports.unknown().optional().describe(
15351
+ "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
15352
+ ),
15353
+ onWebSocket: external_exports.unknown().optional().describe(
15354
+ "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
15355
+ ),
15356
+ actions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
15357
+ "Tree of action names or nested groups to handler functions. Nested paths use dot-separated low-level action names. Defaults to an empty object."
15358
+ ),
15359
+ actionInputSchemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
15360
+ "Optional schemas for validating action argument tuples in native runtimes. May mirror nested action groups or use dot-separated low-level action names."
15361
+ ),
15362
+ connParamsSchema: external_exports.unknown().optional().describe(
15363
+ "Optional schema for validating connection params in native runtimes."
15364
+ ),
15365
+ events: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of event names to schemas."),
15366
+ queues: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of queue names to schemas."),
15367
+ options: DocActorOptionsSchema.optional()
15368
+ }).describe("Actor configuration passed to the actor() function.");
15369
+
15370
+ // ../rivetkit/dist/tsup/chunk-JI6GZ2C2.js
15371
+ var EMPTY_KEY = "/";
15372
+ var KEY_SEPARATOR = "/";
15373
+ var KEYS = {
15374
+ PERSIST_DATA: Uint8Array.from([1]),
15375
+ CONN_PREFIX: Uint8Array.from([2]),
15376
+ INSPECTOR_TOKEN: Uint8Array.from([3]),
15377
+ KV: Uint8Array.from([4]),
15378
+ QUEUE_PREFIX: Uint8Array.from([5]),
15379
+ LAST_PUSHED_ALARM: Uint8Array.from([6]),
15380
+ WORKFLOW_PREFIX: Uint8Array.from([6]),
15381
+ TRACES_PREFIX: Uint8Array.from([7])
15382
+ };
15383
+ var STORAGE_VERSION = {
15384
+ QUEUE: 1,
15385
+ WORKFLOW: 1,
15386
+ TRACES: 1
15387
+ };
15388
+ var STORAGE_VERSION_BYTES = {
15389
+ QUEUE: Uint8Array.from([STORAGE_VERSION.QUEUE]),
15390
+ WORKFLOW: Uint8Array.from([STORAGE_VERSION.WORKFLOW]),
15391
+ TRACES: Uint8Array.from([STORAGE_VERSION.TRACES])
15392
+ };
15393
+ var QUEUE_NAMESPACE = {
15394
+ METADATA: Uint8Array.from([1]),
15395
+ MESSAGES: Uint8Array.from([2])
15396
+ };
15397
+ function concatPrefix(prefix, suffix) {
15398
+ const merged = new Uint8Array(prefix.length + suffix.length);
15399
+ merged.set(prefix, 0);
15400
+ merged.set(suffix, prefix.length);
15401
+ return merged;
15245
15402
  }
15246
- function base64DecodeToUint8Array(base643) {
15247
- if (typeof Buffer !== "undefined") {
15248
- return new Uint8Array(Buffer.from(base643, "base64"));
15249
- }
15250
- const binary = atob(base643);
15251
- const bytes = new Uint8Array(binary.length);
15252
- for (let i = 0; i < binary.length; i++) {
15253
- bytes[i] = binary.charCodeAt(i);
15403
+ var QUEUE_STORAGE_PREFIX = concatPrefix(
15404
+ KEYS.QUEUE_PREFIX,
15405
+ STORAGE_VERSION_BYTES.QUEUE
15406
+ );
15407
+ var QUEUE_METADATA_KEY = concatPrefix(
15408
+ QUEUE_STORAGE_PREFIX,
15409
+ QUEUE_NAMESPACE.METADATA
15410
+ );
15411
+ var QUEUE_MESSAGES_PREFIX = concatPrefix(
15412
+ QUEUE_STORAGE_PREFIX,
15413
+ QUEUE_NAMESPACE.MESSAGES
15414
+ );
15415
+ var WORKFLOW_STORAGE_PREFIX = concatPrefix(
15416
+ KEYS.WORKFLOW_PREFIX,
15417
+ STORAGE_VERSION_BYTES.WORKFLOW
15418
+ );
15419
+ var TRACES_STORAGE_PREFIX = concatPrefix(
15420
+ KEYS.TRACES_PREFIX,
15421
+ STORAGE_VERSION_BYTES.TRACES
15422
+ );
15423
+ function serializeActorKey(key) {
15424
+ if (key.length === 0) {
15425
+ return EMPTY_KEY;
15254
15426
  }
15255
- return bytes;
15256
- }
15257
- function base64DecodeToArrayBuffer(base643) {
15258
- return base64DecodeToUint8Array(base643).buffer;
15259
- }
15260
- function jsonStringifyCompat(input) {
15261
- return JSON.stringify(input, (_key, value) => {
15262
- if (typeof value === "bigint") {
15263
- return [JSON_COMPAT_BIGINT, value.toString()];
15264
- }
15265
- if (value instanceof ArrayBuffer) {
15266
- return [JSON_COMPAT_ARRAY_BUFFER, base64EncodeArrayBuffer(value)];
15267
- }
15268
- if (value instanceof Uint8Array) {
15269
- return [JSON_COMPAT_UINT8_ARRAY, base64EncodeUint8Array(value)];
15270
- }
15271
- if (Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && value[0].startsWith("$")) {
15272
- return [`$${value[0]}`, value[1]];
15427
+ const escapedParts = key.map((part) => {
15428
+ if (part === "") {
15429
+ return "\\0";
15273
15430
  }
15274
- return value;
15431
+ let escaped = part.replace(/\\/g, "\\\\");
15432
+ escaped = escaped.replace(/\//g, `\\${KEY_SEPARATOR}`);
15433
+ return escaped;
15275
15434
  });
15435
+ return escapedParts.join(KEY_SEPARATOR);
15276
15436
  }
15277
- function jsonParseCompat(input) {
15278
- return reviveJsonCompatValue(JSON.parse(input));
15279
- }
15280
- function uint8ArrayToBase642(uint8Array) {
15281
- if (typeof Buffer !== "undefined") {
15282
- return Buffer.from(uint8Array).toString("base64");
15437
+ function deserializeActorKey(keyString) {
15438
+ if (keyString === void 0 || keyString === null || keyString === EMPTY_KEY) {
15439
+ return [];
15283
15440
  }
15284
- let binary = "";
15285
- const len = uint8Array.byteLength;
15286
- for (let i = 0; i < len; i++) {
15287
- binary += String.fromCharCode(uint8Array[i]);
15441
+ const parts = [];
15442
+ let currentPart = "";
15443
+ let escaping = false;
15444
+ let isEmptyStringMarker = false;
15445
+ for (let i = 0; i < keyString.length; i++) {
15446
+ const char = keyString[i];
15447
+ if (escaping) {
15448
+ if (char === "0") {
15449
+ isEmptyStringMarker = true;
15450
+ } else {
15451
+ currentPart += char;
15452
+ }
15453
+ escaping = false;
15454
+ } else if (char === "\\") {
15455
+ escaping = true;
15456
+ } else if (char === KEY_SEPARATOR) {
15457
+ if (isEmptyStringMarker) {
15458
+ parts.push("");
15459
+ isEmptyStringMarker = false;
15460
+ } else {
15461
+ parts.push(currentPart);
15462
+ }
15463
+ currentPart = "";
15464
+ } else {
15465
+ currentPart += char;
15466
+ }
15288
15467
  }
15289
- return btoa(binary);
15290
- }
15291
- function contentTypeForEncoding(encoding) {
15292
- if (encoding === "json") {
15293
- return "application/json";
15294
- } else if (encoding === "cbor" || encoding === "bare") {
15295
- return "application/octet-stream";
15296
- } else {
15297
- assertUnreachable(encoding);
15468
+ if (escaping) {
15469
+ parts.push(`${currentPart}\\`);
15470
+ } else if (isEmptyStringMarker) {
15471
+ parts.push("");
15472
+ } else if (currentPart !== "" || parts.length > 0) {
15473
+ parts.push(currentPart);
15298
15474
  }
15475
+ return parts;
15299
15476
  }
15300
- function encodeCborCompat(value) {
15301
- return cbor.encode(encodeJsonCompatValue(value));
15477
+ function makePrefixedKey(key) {
15478
+ const prefixed = new Uint8Array(KEYS.KV.length + key.length);
15479
+ prefixed.set(KEYS.KV, 0);
15480
+ prefixed.set(key, KEYS.KV.length);
15481
+ return prefixed;
15302
15482
  }
15303
- function decodeCborCompat(buffer) {
15304
- return reviveJsonCompatValue(cbor.decode(buffer));
15483
+ function removePrefixFromKey(prefixedKey) {
15484
+ return prefixedKey.slice(KEYS.KV.length);
15305
15485
  }
15306
- function serializeWithEncoding(encoding, value, versionedDataHandler, version2, zodSchema, toJson, toBare) {
15307
- if (encoding === "json") {
15308
- const jsonValue = toJson(value);
15309
- const validated = zodSchema.parse(jsonValue);
15310
- return jsonStringifyCompat(validated);
15311
- } else if (encoding === "cbor") {
15312
- const jsonValue = toJson(value);
15313
- const validated = zodSchema.parse(jsonValue);
15314
- return cbor.encode(validated);
15315
- } else if (encoding === "bare") {
15316
- if (!versionedDataHandler) {
15317
- throw new Error(
15318
- "VersionedDataHandler is required for 'bare' encoding"
15319
- );
15320
- }
15321
- if (version2 === void 0) {
15322
- throw new Error("version is required for 'bare' encoding");
15486
+
15487
+ // ../rivetkit/dist/tsup/chunk-7AFZMFPQ.js
15488
+ var MIGRATION_TRANSACTION_TIMEOUT_MS = 5 * 6e4;
15489
+ var AsyncMutex = class {
15490
+ #locked = false;
15491
+ #waiting = [];
15492
+ async acquire() {
15493
+ while (this.#locked) {
15494
+ await new Promise((resolve) => this.#waiting.push(resolve));
15323
15495
  }
15324
- const bareValue = toBare(value);
15325
- return versionedDataHandler.serializeWithEmbeddedVersion(
15326
- bareValue,
15327
- version2
15328
- );
15329
- } else {
15330
- assertUnreachable(encoding);
15496
+ this.#locked = true;
15331
15497
  }
15332
- }
15333
- function deserializeWithEncoding(encoding, buffer, versionedDataHandler, zodSchema, fromJson, fromBare) {
15334
- if (encoding === "json") {
15335
- let parsed;
15336
- if (typeof buffer === "string") {
15337
- parsed = jsonParseCompat(buffer);
15338
- } else {
15339
- const decoder = new TextDecoder("utf-8");
15340
- const jsonString = decoder.decode(buffer);
15341
- parsed = jsonParseCompat(jsonString);
15498
+ release() {
15499
+ this.#locked = false;
15500
+ const next = this.#waiting.shift();
15501
+ if (next) {
15502
+ next();
15342
15503
  }
15343
- const validated = zodSchema.parse(parsed);
15344
- return fromJson(validated);
15345
- } else if (encoding === "cbor") {
15346
- (0, import_invariant.default)(
15347
- typeof buffer !== "string",
15348
- "buffer cannot be string for cbor encoding"
15349
- );
15350
- const decoded = decodeCborCompat(buffer);
15351
- const validated = zodSchema.parse(decoded);
15352
- return fromJson(validated);
15353
- } else if (encoding === "bare") {
15354
- (0, import_invariant.default)(
15355
- typeof buffer !== "string",
15356
- "buffer cannot be string for bare encoding"
15357
- );
15358
- if (!versionedDataHandler) {
15359
- throw new Error(
15360
- "VersionedDataHandler is required for 'bare' encoding"
15361
- );
15504
+ }
15505
+ async run(fn) {
15506
+ await this.acquire();
15507
+ try {
15508
+ return await fn();
15509
+ } finally {
15510
+ this.release();
15362
15511
  }
15363
- const bareValue = versionedDataHandler.deserializeWithEmbeddedVersion(buffer);
15364
- return fromBare(bareValue);
15365
- } else {
15366
- assertUnreachable(encoding);
15367
15512
  }
15368
- }
15513
+ };
15369
15514
 
15370
- // ../rivetkit/dist/tsup/chunk-HTXJT6DN.js
15515
+ // ../rivetkit/dist/tsup/chunk-KUWK4UNH.js
15371
15516
  function logger() {
15372
15517
  return getLogger("actor-client");
15373
15518
  }
@@ -15390,50 +15535,22 @@ async function importWebSocket() {
15390
15535
  _WebSocket = ws.default;
15391
15536
  logger().debug("using websocket from npm");
15392
15537
  } catch {
15393
- _WebSocket = class MockWebSocket {
15394
- constructor() {
15395
- throw new Error(
15396
- 'WebSocket support requires installing the "ws" peer dependency.'
15397
- );
15398
- }
15399
- };
15400
- logger().debug("using mock websocket");
15401
- }
15402
- }
15403
- return _WebSocket;
15404
- })();
15405
- return webSocketPromise;
15406
- }
15407
-
15408
- // ../rivetkit/dist/tsup/chunk-7AFZMFPQ.js
15409
- var MIGRATION_TRANSACTION_TIMEOUT_MS = 5 * 6e4;
15410
- var AsyncMutex = class {
15411
- #locked = false;
15412
- #waiting = [];
15413
- async acquire() {
15414
- while (this.#locked) {
15415
- await new Promise((resolve) => this.#waiting.push(resolve));
15416
- }
15417
- this.#locked = true;
15418
- }
15419
- release() {
15420
- this.#locked = false;
15421
- const next = this.#waiting.shift();
15422
- if (next) {
15423
- next();
15424
- }
15425
- }
15426
- async run(fn) {
15427
- await this.acquire();
15428
- try {
15429
- return await fn();
15430
- } finally {
15431
- this.release();
15538
+ _WebSocket = class MockWebSocket {
15539
+ constructor() {
15540
+ throw new Error(
15541
+ 'WebSocket support requires installing the "ws" peer dependency.'
15542
+ );
15543
+ }
15544
+ };
15545
+ logger().debug("using mock websocket");
15546
+ }
15432
15547
  }
15433
- }
15434
- };
15548
+ return _WebSocket;
15549
+ })();
15550
+ return webSocketPromise;
15551
+ }
15435
15552
 
15436
- // ../rivetkit/dist/tsup/chunk-2Y5LK2Q3.js
15553
+ // ../rivetkit/dist/tsup/chunk-J2TA4HLA.js
15437
15554
  var import_invariant2 = __toESM(require_invariant(), 1);
15438
15555
 
15439
15556
  // ../../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
@@ -15611,7 +15728,7 @@ function createVersionedDataHandler(config3) {
15611
15728
  return new VersionedDataHandler(config3);
15612
15729
  }
15613
15730
 
15614
- // ../rivetkit/dist/tsup/chunk-2Y5LK2Q3.js
15731
+ // ../rivetkit/dist/tsup/chunk-J2TA4HLA.js
15615
15732
  var import_invariant3 = __toESM(require_invariant(), 1);
15616
15733
  var import_invariant4 = __toESM(require_invariant(), 1);
15617
15734
  var PATH_CONNECT = "/connect";
@@ -15620,6 +15737,7 @@ var PATH_WEBSOCKET_PREFIX = "/websocket/";
15620
15737
  var HEADER_ACTOR_QUERY = "x-rivet-query";
15621
15738
  var HEADER_ENCODING = "x-rivet-encoding";
15622
15739
  var HEADER_CONN_PARAMS = "x-rivet-conn-params";
15740
+ var HEADER_ORIGINAL_REQUEST_URL = "x-rivet-internal-original-request-url";
15623
15741
  var HEADER_ACTOR_ID = "x-rivet-actor";
15624
15742
  var HEADER_ACTOR_GENERATION = "x-rivet-actor-generation";
15625
15743
  var HEADER_ACTOR_KEY = "x-rivet-actor-key";
@@ -17672,6 +17790,18 @@ async function checkForSchedulingError(group, code, actorId, query, driver) {
17672
17790
  }
17673
17791
  return null;
17674
17792
  }
17793
+ function isUrlLike(value) {
17794
+ return typeof value === "object" && value !== null && typeof value.href === "string" && typeof value.pathname === "string" && typeof value.search === "string";
17795
+ }
17796
+ function isRequestLike(value) {
17797
+ return typeof value === "object" && value !== null && typeof value.url === "string" && typeof value.method === "string" && isHeadersLike(value.headers);
17798
+ }
17799
+ function isResponseLike(value) {
17800
+ return typeof value === "object" && value !== null && typeof value.status === "number" && isHeadersLike(value.headers) && typeof value.arrayBuffer === "function";
17801
+ }
17802
+ function isHeadersLike(value) {
17803
+ return typeof value === "object" && value !== null && typeof value.entries === "function";
17804
+ }
17675
17805
  function* walkErrorChain(error46, maxDepth = 8) {
17676
17806
  let current = error46;
17677
17807
  let depth = 0;
@@ -18097,14 +18227,17 @@ function createQueueSender(senderOptions) {
18097
18227
  }
18098
18228
  async function rawHttpFetch(driver, target, params, input, init, options = {}) {
18099
18229
  let path2;
18230
+ let originalUrl;
18100
18231
  let mergedInit = init || {};
18101
18232
  if (typeof input === "string") {
18102
18233
  path2 = input;
18103
- } else if (input instanceof URL) {
18234
+ } else if (isUrlLike(input)) {
18104
18235
  path2 = input.pathname + input.search;
18105
- } else if (input instanceof Request) {
18236
+ originalUrl = input.toString();
18237
+ } else if (isRequestLike(input)) {
18106
18238
  const url2 = new URL(input.url);
18107
18239
  path2 = url2.pathname + url2.search;
18240
+ originalUrl = url2.toString();
18108
18241
  const requestHeaders = new Headers(input.headers);
18109
18242
  const initHeaders = new Headers((init == null ? void 0 : init.headers) || {});
18110
18243
  const mergedHeaders = new Headers(requestHeaders);
@@ -18146,6 +18279,10 @@ async function rawHttpFetch(driver, target, params, input, init, options = {}) {
18146
18279
  const normalizedPath = path2.startsWith("/") ? path2.slice(1) : path2;
18147
18280
  const url2 = new URL(`http://actor/request/${normalizedPath}`);
18148
18281
  const proxyRequestHeaders = new Headers(mergedInit.headers);
18282
+ proxyRequestHeaders.delete(HEADER_ORIGINAL_REQUEST_URL);
18283
+ if (originalUrl) {
18284
+ proxyRequestHeaders.set(HEADER_ORIGINAL_REQUEST_URL, originalUrl);
18285
+ }
18149
18286
  if (params) {
18150
18287
  proxyRequestHeaders.set(HEADER_CONN_PARAMS, JSON.stringify(params));
18151
18288
  }
@@ -18614,6 +18751,7 @@ var ActorHandleRaw = class {
18614
18751
  async #fetchWithResolvedActor(input, init) {
18615
18752
  const maxAttempts = this.#getDynamicQueryMaxAttempts();
18616
18753
  let useQueryTarget = false;
18754
+ const retryableRequest = isRequestLike(input) ? input.clone() : void 0;
18617
18755
  const { skipReadyWait, ...requestInit } = init ?? {};
18618
18756
  const gatewayOptions = resolveActorGatewayOptions(
18619
18757
  this.#gatewayOptions,
@@ -18633,7 +18771,7 @@ var ActorHandleRaw = class {
18633
18771
  this.#driver,
18634
18772
  target,
18635
18773
  this.#params,
18636
- input,
18774
+ retryableRequest ? retryableRequest.clone() : input,
18637
18775
  requestInit,
18638
18776
  gatewayOptions
18639
18777
  );
@@ -19058,6 +19196,23 @@ function createClientWithDriver(driver, config3 = {}) {
19058
19196
  }
19059
19197
  function createActorProxy(handle) {
19060
19198
  const methodCache = /* @__PURE__ */ new Map();
19199
+ const actionPath = (name) => {
19200
+ let method2 = methodCache.get(name);
19201
+ if (method2) return method2;
19202
+ method2 = new Proxy(
19203
+ (...args) => handle.action({ name, args }),
19204
+ {
19205
+ get(target, prop) {
19206
+ if (typeof prop === "symbol")
19207
+ return Reflect.get(target, prop);
19208
+ if (prop === "then") return void 0;
19209
+ return actionPath(`${name}.${prop}`);
19210
+ }
19211
+ }
19212
+ );
19213
+ methodCache.set(name, method2);
19214
+ return method2;
19215
+ };
19061
19216
  return new Proxy(handle, {
19062
19217
  get(target, prop, receiver) {
19063
19218
  if (typeof prop === "symbol") {
@@ -19072,12 +19227,7 @@ function createActorProxy(handle) {
19072
19227
  }
19073
19228
  if (typeof prop === "string") {
19074
19229
  if (prop === "then") return void 0;
19075
- let method2 = methodCache.get(prop);
19076
- if (!method2) {
19077
- method2 = (...args) => target.action({ name: prop, args });
19078
- methodCache.set(prop, method2);
19079
- }
19080
- return method2;
19230
+ return actionPath(prop);
19081
19231
  }
19082
19232
  },
19083
19233
  // Support for 'in' operator
@@ -19095,6 +19245,7 @@ function createActorProxy(handle) {
19095
19245
  },
19096
19246
  // Support proper property descriptors
19097
19247
  getOwnPropertyDescriptor(target, prop) {
19248
+ if (prop === "then") return void 0;
19098
19249
  const targetDescriptor = Reflect.getOwnPropertyDescriptor(
19099
19250
  target,
19100
19251
  prop
@@ -19107,7 +19258,7 @@ function createActorProxy(handle) {
19107
19258
  configurable: true,
19108
19259
  enumerable: false,
19109
19260
  writable: false,
19110
- value: (...args) => target.action({ name: prop, args })
19261
+ value: actionPath(prop)
19111
19262
  };
19112
19263
  }
19113
19264
  return void 0;
@@ -20343,103 +20494,6 @@ function convertRegistryConfigToClientConfig(config3) {
20343
20494
  devtools: typeof window !== "undefined" && (((_a2 = window == null ? void 0 : window.location) == null ? void 0 : _a2.hostname) === "127.0.0.1" || ((_b = window == null ? void 0 : window.location) == null ? void 0 : _b.hostname) === "localhost")
20344
20495
  };
20345
20496
  }
20346
- function logger2() {
20347
- return getLogger("engine-client");
20348
- }
20349
- function getEndpoint(config3) {
20350
- return config3.endpoint ?? "http://127.0.0.1:6420";
20351
- }
20352
- async function apiCall(config3, method2, path2, body) {
20353
- const endpoint = getEndpoint(config3);
20354
- const url2 = combineUrlPath(endpoint, path2, {
20355
- namespace: config3.namespace
20356
- });
20357
- logger2().debug({ msg: "making api call", method: method2, url: url2 });
20358
- const headers = {
20359
- ...config3.headers
20360
- };
20361
- if (config3.token) {
20362
- headers.Authorization = `Bearer ${config3.token}`;
20363
- }
20364
- return await sendHttpRequest({
20365
- method: method2,
20366
- url: url2,
20367
- headers,
20368
- body,
20369
- encoding: "json",
20370
- skipParseResponse: false,
20371
- requestVersionedDataHandler: void 0,
20372
- requestVersion: void 0,
20373
- responseVersionedDataHandler: void 0,
20374
- responseVersion: void 0,
20375
- requestZodSchema: external_exports.any(),
20376
- responseZodSchema: external_exports.any(),
20377
- // Identity conversions (passthrough for generic API calls)
20378
- requestToJson: (value) => value,
20379
- requestToBare: (value) => value,
20380
- responseFromJson: (value) => value,
20381
- responseFromBare: (value) => value
20382
- });
20383
- }
20384
- async function getActor(config3, _, actorId) {
20385
- return apiCall(
20386
- config3,
20387
- "GET",
20388
- `/actors?actor_ids=${encodeURIComponent(actorId)}`
20389
- );
20390
- }
20391
- async function getActorByKey(config3, name, key) {
20392
- const serializedKey = serializeActorKey(key);
20393
- return apiCall(
20394
- config3,
20395
- "GET",
20396
- `/actors?name=${encodeURIComponent(name)}&key=${encodeURIComponent(serializedKey)}`
20397
- );
20398
- }
20399
- async function listActorsByName(config3, name) {
20400
- return apiCall(
20401
- config3,
20402
- "GET",
20403
- `/actors?name=${encodeURIComponent(name)}`
20404
- );
20405
- }
20406
- async function getOrCreateActor(config3, request) {
20407
- return apiCall(
20408
- config3,
20409
- "PUT",
20410
- `/actors`,
20411
- request
20412
- );
20413
- }
20414
- async function createActor(config3, request) {
20415
- return apiCall(
20416
- config3,
20417
- "POST",
20418
- `/actors`,
20419
- request
20420
- );
20421
- }
20422
- async function destroyActor(config3, actorId) {
20423
- return apiCall(
20424
- config3,
20425
- "DELETE",
20426
- `/actors/${encodeURIComponent(actorId)}`
20427
- );
20428
- }
20429
- async function getMetadata(config3) {
20430
- return apiCall(config3, "GET", `/metadata`);
20431
- }
20432
- async function getDatacenters(config3) {
20433
- return apiCall(config3, "GET", `/datacenters`);
20434
- }
20435
- async function updateRunnerConfig(config3, runnerName, request) {
20436
- return apiCall(
20437
- config3,
20438
- "PUT",
20439
- `/runner-configs/${runnerName}`,
20440
- request
20441
- );
20442
- }
20443
20497
  function shouldSkipReadyWait(options = {}) {
20444
20498
  return options.skipReadyWait === true;
20445
20499
  }
@@ -20450,23 +20504,19 @@ async function sendHttpRequestToGateway(runConfig, gatewayUrl, actorRequest, opt
20450
20504
  if (actorRequest.bodyUsed) {
20451
20505
  throw new Error("Request body has already been consumed");
20452
20506
  }
20453
- const reqBody = await actorRequest.arrayBuffer();
20454
- if (reqBody.byteLength !== 0) {
20455
- bodyToSend = reqBody;
20507
+ if (actorRequest.body) {
20508
+ bodyToSend = actorRequest.body;
20456
20509
  guardHeaders.delete("transfer-encoding");
20457
20510
  guardHeaders.delete("content-length");
20458
20511
  }
20459
20512
  }
20460
- const guardRequest = new Request(gatewayUrl, {
20513
+ return fetch(gatewayUrl, {
20461
20514
  method: actorRequest.method,
20462
20515
  headers: guardHeaders,
20463
20516
  body: bodyToSend,
20464
- signal: actorRequest.signal
20517
+ signal: actorRequest.signal,
20518
+ ...bodyToSend ? { duplex: "half" } : {}
20465
20519
  });
20466
- return mutableResponse(await fetch(guardRequest));
20467
- }
20468
- function mutableResponse(fetchRes) {
20469
- return new Response(fetchRes.body, fetchRes);
20470
20520
  }
20471
20521
  function buildGuardHeaders(runConfig, actorRequest, options) {
20472
20522
  const headers = new Headers();
@@ -20527,6 +20577,9 @@ function setRemoteHibernatableWebSocketAckTestHooks(websocket, token, enabled) {
20527
20577
  enabled
20528
20578
  );
20529
20579
  }
20580
+ function logger2() {
20581
+ return getLogger("engine-client");
20582
+ }
20530
20583
  var BufferedRemoteWebSocket = class {
20531
20584
  CONNECTING = 0;
20532
20585
  OPEN = 1;
@@ -20804,6 +20857,100 @@ function buildWebSocketProtocols(runConfig, encoding, params, ackHookToken, targ
20804
20857
  }
20805
20858
  return protocols;
20806
20859
  }
20860
+ function getEndpoint(config3) {
20861
+ return config3.endpoint ?? "http://127.0.0.1:6420";
20862
+ }
20863
+ async function apiCall(config3, method2, path2, body) {
20864
+ const endpoint = getEndpoint(config3);
20865
+ const url2 = combineUrlPath(endpoint, path2, {
20866
+ namespace: config3.namespace
20867
+ });
20868
+ logger2().debug({ msg: "making api call", method: method2, url: url2 });
20869
+ const headers = {
20870
+ ...config3.headers
20871
+ };
20872
+ if (config3.token) {
20873
+ headers.Authorization = `Bearer ${config3.token}`;
20874
+ }
20875
+ return await sendHttpRequest({
20876
+ method: method2,
20877
+ url: url2,
20878
+ headers,
20879
+ body,
20880
+ encoding: "json",
20881
+ skipParseResponse: false,
20882
+ requestVersionedDataHandler: void 0,
20883
+ requestVersion: void 0,
20884
+ responseVersionedDataHandler: void 0,
20885
+ responseVersion: void 0,
20886
+ requestZodSchema: external_exports.any(),
20887
+ responseZodSchema: external_exports.any(),
20888
+ // Identity conversions (passthrough for generic API calls)
20889
+ requestToJson: (value) => value,
20890
+ requestToBare: (value) => value,
20891
+ responseFromJson: (value) => value,
20892
+ responseFromBare: (value) => value
20893
+ });
20894
+ }
20895
+ async function getActor(config3, _, actorId) {
20896
+ return apiCall(
20897
+ config3,
20898
+ "GET",
20899
+ `/actors?actor_ids=${encodeURIComponent(actorId)}`
20900
+ );
20901
+ }
20902
+ async function getActorByKey(config3, name, key) {
20903
+ const serializedKey = serializeActorKey(key);
20904
+ return apiCall(
20905
+ config3,
20906
+ "GET",
20907
+ `/actors?name=${encodeURIComponent(name)}&key=${encodeURIComponent(serializedKey)}`
20908
+ );
20909
+ }
20910
+ async function listActorsByName(config3, name) {
20911
+ return apiCall(
20912
+ config3,
20913
+ "GET",
20914
+ `/actors?name=${encodeURIComponent(name)}`
20915
+ );
20916
+ }
20917
+ async function getOrCreateActor(config3, request) {
20918
+ return apiCall(
20919
+ config3,
20920
+ "PUT",
20921
+ `/actors`,
20922
+ request
20923
+ );
20924
+ }
20925
+ async function createActor(config3, request) {
20926
+ return apiCall(
20927
+ config3,
20928
+ "POST",
20929
+ `/actors`,
20930
+ request
20931
+ );
20932
+ }
20933
+ async function destroyActor(config3, actorId) {
20934
+ return apiCall(
20935
+ config3,
20936
+ "DELETE",
20937
+ `/actors/${encodeURIComponent(actorId)}`
20938
+ );
20939
+ }
20940
+ async function getMetadata(config3) {
20941
+ return apiCall(config3, "GET", `/metadata`);
20942
+ }
20943
+ async function getDatacenters(config3) {
20944
+ return apiCall(config3, "GET", `/datacenters`);
20945
+ }
20946
+ async function updateRunnerConfig(config3, runnerName, request) {
20947
+ return apiCall(
20948
+ config3,
20949
+ "PUT",
20950
+ `/runner-configs/${runnerName}`,
20951
+ request
20952
+ );
20953
+ }
20807
20954
  var metadataLookupCache = /* @__PURE__ */ new Map();
20808
20955
  async function lookupMetadataCached(config3) {
20809
20956
  const endpoint = getEndpoint(config3);
@@ -22563,6 +22710,8 @@ function actor(input) {
22563
22710
  input == null ? void 0 : input.options
22564
22711
  );
22565
22712
  const config3 = ActorConfigSchema.parse(input);
22713
+ flattenActionHandlers(config3.actions);
22714
+ flattenActionInputSchemas(config3.actions, config3.actionInputSchemas);
22566
22715
  return new ActorDefinition(config3);
22567
22716
  }
22568
22717
  function isStaticActorDefinition(definition) {
@@ -23219,7 +23368,7 @@ var RegistryConfigSchema = external_exports.object({
23219
23368
  config3.engineHost,
23220
23369
  config3.enginePort
23221
23370
  );
23222
- const endpoint = config3.startEngine ? localEngineEndpoint : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? buildEngineEndpoint(ENGINE_HOST, ENGINE_PORT) : void 0);
23371
+ const endpoint = config3.startEngine ? localEngineEndpoint : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? localEngineEndpoint : void 0);
23223
23372
  const validateServerlessEndpoint = Boolean(
23224
23373
  config3.startEngine || parsedEndpoint
23225
23374
  );
@@ -23236,7 +23385,7 @@ var RegistryConfigSchema = external_exports.object({
23236
23385
  path: ["serverless", "publicEndpoint"]
23237
23386
  });
23238
23387
  }
23239
- const publicEndpoint = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.endpoint) ?? (isDevEnv && config3.startEngine ? endpoint : void 0);
23388
+ const publicEndpoint = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.endpoint) ?? (isDevEnv && !parsedEndpoint ? endpoint : void 0);
23240
23389
  const publicNamespace = parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.namespace;
23241
23390
  const publicToken = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.token) ?? config3.serverless.publicToken;
23242
23391
  return {
@@ -23842,6 +23991,36 @@ function toNapiSqlBatchStatement(statement) {
23842
23991
  function toNapiBuffer(value) {
23843
23992
  return Buffer.from(value);
23844
23993
  }
23994
+ function toNapiApplication(application) {
23995
+ return async (error46, request) => {
23996
+ if (error46) throw error46;
23997
+ if (!request) {
23998
+ throw new Error("application fetch callback received no request");
23999
+ }
24000
+ const response = await application(
24001
+ {
24002
+ ...request,
24003
+ body: new Uint8Array(request.body),
24004
+ cancelToken: request.cancelToken
24005
+ },
24006
+ request.responseBodyStream ? fromNapiHttpResponseBodyStream(
24007
+ request.responseBodyStream
24008
+ ) : void 0
24009
+ );
24010
+ return {
24011
+ ...response,
24012
+ body: response.body === void 0 ? void 0 : toNapiBuffer(response.body)
24013
+ };
24014
+ };
24015
+ }
24016
+ function fromNapiHttpResponseBodyStream(stream) {
24017
+ return {
24018
+ cancelled: () => stream.cancelled(),
24019
+ write: (chunk) => stream.write(Buffer.from(chunk)),
24020
+ end: () => stream.end(),
24021
+ error: (message) => stream.error(message)
24022
+ };
24023
+ }
23845
24024
  function toNapiHttpRequest(request) {
23846
24025
  if (!request) {
23847
24026
  return request;
@@ -23906,6 +24085,9 @@ var NapiCoreRuntime = class {
23906
24085
  async serveRegistry(registry2, config3) {
23907
24086
  await asNativeRegistry(registry2).serve(config3);
23908
24087
  }
24088
+ async waitRegistryReady(registry2) {
24089
+ await asNativeRegistry(registry2).waitReady();
24090
+ }
23909
24091
  async shutdownRegistry(registry2) {
23910
24092
  await asNativeRegistry(registry2).shutdown();
23911
24093
  }
@@ -23945,12 +24127,25 @@ var NapiCoreRuntime = class {
23945
24127
  );
23946
24128
  }
23947
24129
  async serveListener(registry2, listener, config3) {
24130
+ const application = listener.application ? toNapiApplication(listener.application) : void 0;
23948
24131
  await asNativeRegistry(registry2).serveListener(
23949
24132
  {
23950
24133
  port: listener.port,
23951
24134
  host: listener.host,
23952
24135
  publicDir: listener.publicDir
23953
24136
  },
24137
+ config3,
24138
+ application
24139
+ );
24140
+ }
24141
+ async serveApplicationListener(registry2, listener, config3) {
24142
+ await asNativeRegistry(registry2).serveApplicationListener(
24143
+ {
24144
+ port: listener.port,
24145
+ host: listener.host,
24146
+ publicDir: listener.publicDir
24147
+ },
24148
+ toNapiApplication(listener.application),
23954
24149
  config3
23955
24150
  );
23956
24151
  }
@@ -24247,17 +24442,57 @@ var NapiCoreRuntime = class {
24247
24442
  actorQueueMaxSize(ctx) {
24248
24443
  return asNativeActorContext(ctx).queue().maxSize();
24249
24444
  }
24250
- async actorQueueInspectMessages(ctx) {
24251
- return await asNativeActorContext(ctx).queue().inspectMessages();
24445
+ async actorQueueInspectMessages(ctx) {
24446
+ return await asNativeActorContext(ctx).queue().inspectMessages();
24447
+ }
24448
+ async actorQueueReset(ctx) {
24449
+ await asNativeActorContext(ctx).queue().reset();
24450
+ }
24451
+ async actorScheduleAfter(ctx, durationMs, actionName, args) {
24452
+ return await asNativeActorContext(ctx).schedule().after(durationMs, actionName, toNapiBuffer(args));
24453
+ }
24454
+ async actorScheduleAt(ctx, timestampMs, actionName, args) {
24455
+ return await asNativeActorContext(ctx).schedule().at(timestampMs, actionName, toNapiBuffer(args));
24456
+ }
24457
+ async actorScheduleCancel(ctx, id) {
24458
+ return await asNativeActorContext(ctx).schedule().cancel(id);
24459
+ }
24460
+ async actorScheduleGet(ctx, id) {
24461
+ return await asNativeActorContext(ctx).schedule().get(id) ?? void 0;
24462
+ }
24463
+ async actorScheduleList(ctx) {
24464
+ return await asNativeActorContext(ctx).schedule().list();
24465
+ }
24466
+ async actorCronSet(ctx, name, expression, timezone, actionName, args, maxHistory) {
24467
+ await asNativeActorContext(ctx).schedule().cronSet(
24468
+ name,
24469
+ expression,
24470
+ timezone,
24471
+ actionName,
24472
+ toNapiBuffer(args),
24473
+ maxHistory
24474
+ );
24475
+ }
24476
+ async actorCronEvery(ctx, name, intervalMs, actionName, args, maxHistory) {
24477
+ await asNativeActorContext(ctx).schedule().cronEvery(
24478
+ name,
24479
+ intervalMs,
24480
+ actionName,
24481
+ toNapiBuffer(args),
24482
+ maxHistory
24483
+ );
24484
+ }
24485
+ async actorCronGet(ctx, name) {
24486
+ return await asNativeActorContext(ctx).schedule().cronGet(name) ?? void 0;
24252
24487
  }
24253
- async actorQueueReset(ctx) {
24254
- await asNativeActorContext(ctx).queue().reset();
24488
+ async actorCronList(ctx) {
24489
+ return await asNativeActorContext(ctx).schedule().cronList();
24255
24490
  }
24256
- actorScheduleAfter(ctx, durationMs, actionName, args) {
24257
- asNativeActorContext(ctx).schedule().after(durationMs, actionName, toNapiBuffer(args));
24491
+ async actorCronDelete(ctx, name) {
24492
+ return await asNativeActorContext(ctx).schedule().cronDelete(name);
24258
24493
  }
24259
- actorScheduleAt(ctx, timestampMs, actionName, args) {
24260
- asNativeActorContext(ctx).schedule().at(timestampMs, actionName, toNapiBuffer(args));
24494
+ async actorCronHistory(ctx, name, limit) {
24495
+ return await asNativeActorContext(ctx).schedule().cronHistory(name, limit);
24261
24496
  }
24262
24497
  connId(conn) {
24263
24498
  return asNativeConn(conn).id();
@@ -24297,6 +24532,135 @@ async function loadNapiRuntime() {
24297
24532
  runtime: new NapiCoreRuntime(bindings)
24298
24533
  };
24299
24534
  }
24535
+ var HTTP_BODY_CHUNK_SIZE = 64 * 1024;
24536
+ function runtimeBytesToArrayBuffer(value) {
24537
+ return value.buffer.slice(
24538
+ value.byteOffset,
24539
+ value.byteOffset + value.byteLength
24540
+ );
24541
+ }
24542
+ function buildNativeHttpRequest(init) {
24543
+ var _a2;
24544
+ const headers = new Headers(init.headers);
24545
+ const originalUrl = headers.get(HEADER_ORIGINAL_REQUEST_URL);
24546
+ headers.delete(HEADER_ORIGINAL_REQUEST_URL);
24547
+ const url2 = originalUrl ?? (init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString());
24548
+ const method2 = init.method.toUpperCase();
24549
+ const bodyForbidden = method2 === "GET" || method2 === "HEAD";
24550
+ const body = bodyForbidden ? void 0 : init.bodyStream ? new ReadableStream({
24551
+ async pull(controller) {
24552
+ var _a22, _b;
24553
+ try {
24554
+ if (init.body && init.body.length > 0) {
24555
+ controller.enqueue(new Uint8Array(init.body));
24556
+ init.body = void 0;
24557
+ return;
24558
+ }
24559
+ const chunk = await ((_a22 = init.bodyStream) == null ? void 0 : _a22.read());
24560
+ if (!chunk) {
24561
+ controller.close();
24562
+ } else {
24563
+ controller.enqueue(new Uint8Array(chunk));
24564
+ }
24565
+ } catch (error46) {
24566
+ (_b = init.abortController) == null ? void 0 : _b.abort(error46);
24567
+ controller.error(error46);
24568
+ }
24569
+ },
24570
+ async cancel() {
24571
+ var _a22;
24572
+ await ((_a22 = init.bodyStream) == null ? void 0 : _a22.cancel());
24573
+ }
24574
+ }) : init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
24575
+ const streamInit = init.bodyStream && !bodyForbidden ? { duplex: "half" } : {};
24576
+ return new Request(url2, {
24577
+ method: method2,
24578
+ headers,
24579
+ body,
24580
+ signal: ((_a2 = init.abortController) == null ? void 0 : _a2.signal) ?? init.signal,
24581
+ ...streamInit
24582
+ });
24583
+ }
24584
+ async function cancelNativeHttpRequestBody(bodyStream) {
24585
+ await (bodyStream == null ? void 0 : bodyStream.cancel());
24586
+ }
24587
+ async function writeResponseChunk(stream, chunk) {
24588
+ for (let offset = 0; offset < chunk.byteLength; offset += HTTP_BODY_CHUNK_SIZE) {
24589
+ await stream.write(
24590
+ chunk.subarray(offset, offset + HTTP_BODY_CHUNK_SIZE)
24591
+ );
24592
+ }
24593
+ }
24594
+ async function pumpResponseBody(reader, stream) {
24595
+ var _a2;
24596
+ const cancelled = stream.cancelled().then(() => ({ cancelled: true }));
24597
+ try {
24598
+ for (; ; ) {
24599
+ const read = reader.read().then((next2) => ({ cancelled: false, next: next2 }));
24600
+ const result = await Promise.race([read, cancelled]);
24601
+ if (result.cancelled) {
24602
+ await reader.cancel(
24603
+ new Error("native http response stream receiver dropped")
24604
+ );
24605
+ return;
24606
+ }
24607
+ const { next } = result;
24608
+ if (next.done) {
24609
+ await stream.end();
24610
+ return;
24611
+ }
24612
+ if ((_a2 = next.value) == null ? void 0 : _a2.byteLength) {
24613
+ await writeResponseChunk(stream, next.value);
24614
+ }
24615
+ }
24616
+ } catch (error46) {
24617
+ try {
24618
+ await stream.error(stringifyError(error46));
24619
+ } catch (streamError) {
24620
+ logger22().debug({
24621
+ msg: "failed to report native http response stream error",
24622
+ error: streamError
24623
+ });
24624
+ }
24625
+ try {
24626
+ await reader.cancel(error46);
24627
+ } catch {
24628
+ }
24629
+ } finally {
24630
+ reader.releaseLock();
24631
+ }
24632
+ }
24633
+ async function convertNativeHttpResponse(response, responseBodyStream) {
24634
+ const headers = Object.fromEntries(response.headers.entries());
24635
+ if (!response.body) {
24636
+ return {
24637
+ response: {
24638
+ status: response.status,
24639
+ headers,
24640
+ body: new Uint8Array()
24641
+ }
24642
+ };
24643
+ }
24644
+ if (responseBodyStream) {
24645
+ const reader = response.body.getReader();
24646
+ const bodyCompletion = pumpResponseBody(reader, responseBodyStream);
24647
+ return {
24648
+ response: {
24649
+ status: response.status,
24650
+ headers,
24651
+ stream: true
24652
+ },
24653
+ bodyCompletion
24654
+ };
24655
+ }
24656
+ return {
24657
+ response: {
24658
+ status: response.status,
24659
+ headers,
24660
+ body: new Uint8Array(await response.arrayBuffer())
24661
+ }
24662
+ };
24663
+ }
24300
24664
  var CONN_PARAMS_KEY = "__conn_params__";
24301
24665
  function validateActionArgs(schemas, name, args) {
24302
24666
  if (!(schemas == null ? void 0 : schemas[name])) {
@@ -24530,6 +24894,11 @@ var WasmCoreRuntime = class {
24530
24894
  async serveRegistry(registry2, config3) {
24531
24895
  await callWasm(() => asWasmRegistry(registry2).serve(config3));
24532
24896
  }
24897
+ async waitRegistryReady() {
24898
+ throw new Error(
24899
+ "registry.startAndWait() is not supported by the WASM runtime"
24900
+ );
24901
+ }
24533
24902
  async shutdownRegistry(registry2) {
24534
24903
  await callWasm(() => asWasmRegistry(registry2).shutdown());
24535
24904
  }
@@ -24561,6 +24930,11 @@ var WasmCoreRuntime = class {
24561
24930
  "registry.listen() is not supported on the wasm runtime; use registry.serve() and mount the handler in your platform's HTTP server instead"
24562
24931
  );
24563
24932
  }
24933
+ async serveApplicationListener(_registry, _listener, _config) {
24934
+ throw new Error(
24935
+ "registry.listen() is not supported on the wasm runtime; use an application-owned HTTP server instead"
24936
+ );
24937
+ }
24564
24938
  createActorFactory(callbacks, config3) {
24565
24939
  return callWasmSync(
24566
24940
  () => asActorFactoryHandle2(
@@ -24950,13 +25324,97 @@ var WasmCoreRuntime = class {
24950
25324
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
24951
25325
  await callHandleAsync(queue2, "reset");
24952
25326
  }
24953
- actorScheduleAfter(ctx, durationMs, actionName, args) {
25327
+ async actorScheduleAfter(ctx, durationMs, actionName, args) {
25328
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25329
+ return await callHandleAsync(
25330
+ schedule,
25331
+ "after",
25332
+ wasmNumber(durationMs),
25333
+ actionName,
25334
+ args
25335
+ );
25336
+ }
25337
+ async actorScheduleAt(ctx, timestampMs, actionName, args) {
25338
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25339
+ return await callHandleAsync(
25340
+ schedule,
25341
+ "at",
25342
+ wasmNumber(timestampMs),
25343
+ actionName,
25344
+ args
25345
+ );
25346
+ }
25347
+ async actorScheduleCancel(ctx, id) {
25348
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25349
+ return await callHandleAsync(schedule, "cancel", id);
25350
+ }
25351
+ async actorScheduleGet(ctx, id) {
25352
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25353
+ return await callHandleAsync(
25354
+ schedule,
25355
+ "get",
25356
+ id
25357
+ );
25358
+ }
25359
+ async actorScheduleList(ctx) {
25360
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25361
+ return await callHandleAsync(
25362
+ schedule,
25363
+ "list"
25364
+ );
25365
+ }
25366
+ async actorCronSet(ctx, name, expression, timezone, actionName, args, maxHistory) {
25367
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25368
+ await callHandleAsync(
25369
+ schedule,
25370
+ "cronSet",
25371
+ name,
25372
+ expression,
25373
+ timezone,
25374
+ actionName,
25375
+ args,
25376
+ maxHistory
25377
+ );
25378
+ }
25379
+ async actorCronEvery(ctx, name, intervalMs, actionName, args, maxHistory) {
25380
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25381
+ await callHandleAsync(
25382
+ schedule,
25383
+ "cronEvery",
25384
+ name,
25385
+ intervalMs,
25386
+ actionName,
25387
+ args,
25388
+ maxHistory
25389
+ );
25390
+ }
25391
+ async actorCronGet(ctx, name) {
25392
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25393
+ return await callHandleAsync(
25394
+ schedule,
25395
+ "cronGet",
25396
+ name
25397
+ );
25398
+ }
25399
+ async actorCronList(ctx) {
25400
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25401
+ return await callHandleAsync(
25402
+ schedule,
25403
+ "cronList"
25404
+ );
25405
+ }
25406
+ async actorCronDelete(ctx, name) {
24954
25407
  const schedule = childHandle(asWasmActorContext(ctx), "schedule");
24955
- callHandle(schedule, "after", wasmNumber(durationMs), actionName, args);
25408
+ return await callHandleAsync(schedule, "cronDelete", name);
24956
25409
  }
24957
- actorScheduleAt(ctx, timestampMs, actionName, args) {
25410
+ async actorCronHistory(ctx, name, limit) {
24958
25411
  const schedule = childHandle(asWasmActorContext(ctx), "schedule");
24959
- callHandle(schedule, "at", wasmNumber(timestampMs), actionName, args);
25412
+ return await callHandleAsync(
25413
+ schedule,
25414
+ "cronHistory",
25415
+ name,
25416
+ limit
25417
+ );
24960
25418
  }
24961
25419
  connId(conn) {
24962
25420
  return callHandle(asWasmConn(conn), "id");
@@ -25329,7 +25787,7 @@ function toRuntimeBytes(value) {
25329
25787
  function arrayBufferViewToRuntimeBytes(value) {
25330
25788
  return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
25331
25789
  }
25332
- function runtimeBytesToArrayBuffer(value) {
25790
+ function runtimeBytesToArrayBuffer2(value) {
25333
25791
  return value.buffer.slice(
25334
25792
  value.byteOffset,
25335
25793
  value.byteOffset + value.byteLength
@@ -25659,24 +26117,6 @@ function decodeArgs(value) {
25659
26117
  const decoded = decodeValue(value);
25660
26118
  return normalizeArgs(decoded);
25661
26119
  }
25662
- function buildRequest(init) {
25663
- const url2 = init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString();
25664
- const body = init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
25665
- return new Request(url2, {
25666
- method: init.method,
25667
- headers: init.headers,
25668
- body
25669
- });
25670
- }
25671
- async function toRuntimeHttpResponse(response) {
25672
- const headers = Object.fromEntries(response.headers.entries());
25673
- const body = new Uint8Array(await response.arrayBuffer());
25674
- return {
25675
- status: response.status,
25676
- headers,
25677
- body
25678
- };
25679
- }
25680
26120
  function toActorKey(segments) {
25681
26121
  return segments.map(
25682
26122
  (segment) => segment.kind === "number" ? String(segment.numberValue ?? 0) : segment.stringValue ?? ""
@@ -25801,26 +26241,116 @@ var NativeScheduleAdapter = class {
25801
26241
  this.#ctx = ctx;
25802
26242
  }
25803
26243
  async after(duration3, action, ...args) {
25804
- callNativeSync(
25805
- () => this.#runtime.actorScheduleAfter(
25806
- this.#ctx,
25807
- duration3,
25808
- action,
25809
- encodeValue(args)
25810
- )
26244
+ return await this.#runtime.actorScheduleAfter(
26245
+ this.#ctx,
26246
+ duration3,
26247
+ action,
26248
+ encodeValue(args)
25811
26249
  );
25812
26250
  }
25813
26251
  async at(timestamp, action, ...args) {
25814
- callNativeSync(
25815
- () => this.#runtime.actorScheduleAt(
25816
- this.#ctx,
25817
- timestamp,
25818
- action,
25819
- encodeValue(args)
25820
- )
26252
+ return await this.#runtime.actorScheduleAt(
26253
+ this.#ctx,
26254
+ timestamp,
26255
+ action,
26256
+ encodeValue(args)
26257
+ );
26258
+ }
26259
+ async cancel(id) {
26260
+ return await this.#runtime.actorScheduleCancel(this.#ctx, id);
26261
+ }
26262
+ async get(id) {
26263
+ const event2 = await this.#runtime.actorScheduleGet(this.#ctx, id);
26264
+ return event2 ? decodeScheduledEventInfo(event2) : void 0;
26265
+ }
26266
+ async list() {
26267
+ return (await this.#runtime.actorScheduleList(this.#ctx)).map(
26268
+ decodeScheduledEventInfo
26269
+ );
26270
+ }
26271
+ };
26272
+ var NativeCronAdapter = class {
26273
+ #runtime;
26274
+ #ctx;
26275
+ constructor(runtime, ctx) {
26276
+ this.#runtime = runtime;
26277
+ this.#ctx = ctx;
26278
+ }
26279
+ async set(options) {
26280
+ await this.#runtime.actorCronSet(
26281
+ this.#ctx,
26282
+ options.name,
26283
+ options.expression,
26284
+ options.timezone,
26285
+ options.action,
26286
+ encodeValue(options.args ?? []),
26287
+ options.maxHistory
25821
26288
  );
25822
26289
  }
26290
+ async every(options) {
26291
+ await this.#runtime.actorCronEvery(
26292
+ this.#ctx,
26293
+ options.name,
26294
+ options.interval,
26295
+ options.action,
26296
+ encodeValue(options.args ?? []),
26297
+ options.maxHistory
26298
+ );
26299
+ }
26300
+ async get(name) {
26301
+ const job = await this.#runtime.actorCronGet(this.#ctx, name);
26302
+ return job ? decodeCronJobInfo(job) : void 0;
26303
+ }
26304
+ async list() {
26305
+ return (await this.#runtime.actorCronList(this.#ctx)).map(
26306
+ decodeCronJobInfo
26307
+ );
26308
+ }
26309
+ async delete(name) {
26310
+ return await this.#runtime.actorCronDelete(this.#ctx, name);
26311
+ }
26312
+ async history(name, options) {
26313
+ return (await this.#runtime.actorCronHistory(
26314
+ this.#ctx,
26315
+ name,
26316
+ options == null ? void 0 : options.limit
26317
+ )).map(decodeCronFire);
26318
+ }
25823
26319
  };
26320
+ function decodeScheduledEventInfo(event2) {
26321
+ return {
26322
+ id: event2.id,
26323
+ action: event2.action,
26324
+ args: decodeArgs(event2.args),
26325
+ runAt: event2.runAt
26326
+ };
26327
+ }
26328
+ function decodeCronJobInfo(job) {
26329
+ const base = {
26330
+ name: job.name,
26331
+ action: job.action,
26332
+ args: decodeArgs(job.args),
26333
+ nextRunAt: job.nextRunAt,
26334
+ lastRunAt: job.lastRunAt,
26335
+ maxHistory: job.maxHistory
26336
+ };
26337
+ if (job.kind === "cron") {
26338
+ return {
26339
+ ...base,
26340
+ kind: "cron",
26341
+ expression: job.expression,
26342
+ timezone: job.timezone
26343
+ };
26344
+ }
26345
+ return {
26346
+ ...base,
26347
+ kind: "every",
26348
+ interval: job.intervalMs
26349
+ };
26350
+ }
26351
+ function decodeCronFire(fire) {
26352
+ return { ...fire };
26353
+ }
25824
26354
  var NativeKvAdapter = class {
25825
26355
  #runtime;
25826
26356
  #ctx;
@@ -26251,7 +26781,7 @@ var NativeWebSocketAdapter = class {
26251
26781
  this.#runtime.webSocketSetEventCallback(this.#ws, (event2) => {
26252
26782
  if (event2.kind === "message") {
26253
26783
  this.#virtual.triggerMessage(
26254
- event2.binary ? runtimeBytesToArrayBuffer(event2.data) : event2.data,
26784
+ event2.binary ? runtimeBytesToArrayBuffer2(event2.data) : event2.data,
26255
26785
  event2.messageIndex
26256
26786
  );
26257
26787
  return;
@@ -26601,6 +27131,7 @@ var ActorContextHandleAdapter = class {
26601
27131
  #client;
26602
27132
  #clientFactory;
26603
27133
  #connMap;
27134
+ #cron;
26604
27135
  #databaseProvider;
26605
27136
  #db;
26606
27137
  #dispatchCancelToken;
@@ -26735,6 +27266,12 @@ var ActorContextHandleAdapter = class {
26735
27266
  }
26736
27267
  return this.#schedule;
26737
27268
  }
27269
+ get cron() {
27270
+ if (!this.#cron) {
27271
+ this.#cron = new NativeCronAdapter(this.#runtime, this.#ctx);
27272
+ }
27273
+ return this.#cron;
27274
+ }
26738
27275
  get actorId() {
26739
27276
  return callNativeSync(() => this.#runtime.actorId(this.#ctx));
26740
27277
  }
@@ -27332,12 +27869,13 @@ function buildActorConfig(definition, registryConfig, runtimeKind) {
27332
27869
  connectionLivenessTimeoutMs: options.connectionLivenessTimeout,
27333
27870
  connectionLivenessIntervalMs: options.connectionLivenessInterval,
27334
27871
  maxQueueSize: options.maxQueueSize,
27872
+ maxSchedules: options.maxSchedules,
27335
27873
  maxQueueMessageSize: options.maxQueueMessageSize,
27336
27874
  maxIncomingMessageSize: registryConfig.maxIncomingMessageSize,
27337
27875
  maxOutgoingMessageSize: registryConfig.maxOutgoingMessageSize,
27338
27876
  preloadMaxWorkflowBytes: options.preloadMaxWorkflowBytes,
27339
27877
  preloadMaxConnectionsBytes: options.preloadMaxConnectionsBytes,
27340
- actions: Object.keys(config3.actions ?? {}).sort().map((name) => ({ name })),
27878
+ actions: Object.keys(flattenActionHandlers(config3.actions)).sort().map((name) => ({ name })),
27341
27879
  inspectorTabs: buildInspectorTabs(config3.inspector, runtimeKind)
27342
27880
  };
27343
27881
  }
@@ -27414,15 +27952,16 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27414
27952
  var _a2;
27415
27953
  const config3 = definition.config;
27416
27954
  const databaseProvider = config3.db;
27955
+ const actionHandlers = flattenActionHandlers(config3.actions);
27417
27956
  const schemaConfig = {
27418
- actionInputSchemas: config3.actionInputSchemas,
27957
+ actionInputSchemas: flattenActionInputSchemas(
27958
+ config3.actions,
27959
+ config3.actionInputSchemas
27960
+ ),
27419
27961
  connParamsSchema: config3.connParamsSchema,
27420
27962
  events: config3.events,
27421
27963
  queues: config3.queues
27422
27964
  };
27423
- const actionHandlers = Object.fromEntries(
27424
- Object.entries(config3.actions ?? {}).map(([name, handler]) => [name, handler])
27425
- );
27426
27965
  const createClient = () => createClientWithDriver(
27427
27966
  new RemoteEngineControlClient(
27428
27967
  convertRegistryConfigToClientConfig(registryConfig)
@@ -27474,12 +28013,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27474
28013
  onStateChange,
27475
28014
  cancelToken
27476
28015
  );
27477
- const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
28016
+ const maybeHandleNativeInspectorRequest = async (ctx, rawRequest) => {
27478
28017
  var _a22, _b, _c, _d;
27479
- const url2 = new URL(jsRequest.url);
28018
+ const rawUrl = rawRequest.uri.startsWith("http") ? rawRequest.uri : new URL(rawRequest.uri, "http://127.0.0.1").toString();
28019
+ const url2 = new URL(rawUrl);
27480
28020
  if (!url2.pathname.startsWith("/inspector/")) {
27481
28021
  return void 0;
27482
28022
  }
28023
+ const jsRequest = buildNativeHttpRequest(rawRequest);
27483
28024
  const jsonResponse = (body, init) => new Response(JSON.stringify(body), {
27484
28025
  status: (init == null ? void 0 : init.status) ?? 200,
27485
28026
  headers: {
@@ -28010,7 +28551,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28010
28551
  );
28011
28552
  const actorCtx = makeActorCtx(
28012
28553
  ctx,
28013
- request ? buildRequest(request) : void 0
28554
+ request ? buildNativeHttpRequest(request) : void 0
28014
28555
  );
28015
28556
  try {
28016
28557
  await config3.onBeforeConnect(
@@ -28030,7 +28571,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28030
28571
  const { ctx, conn, params, request } = unwrapTsfnPayload(error46, payload);
28031
28572
  const actorCtx = makeActorCtx(
28032
28573
  ctx,
28033
- request ? buildRequest(request) : void 0
28574
+ request ? buildNativeHttpRequest(request) : void 0
28034
28575
  );
28035
28576
  const connAdapter = new NativeConnAdapter(
28036
28577
  runtime,
@@ -28067,7 +28608,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28067
28608
  );
28068
28609
  const actorCtx = makeActorCtx(
28069
28610
  ctx,
28070
- request ? buildRequest(request) : void 0
28611
+ request ? buildNativeHttpRequest(request) : void 0
28071
28612
  );
28072
28613
  const connAdapter = new NativeConnAdapter(
28073
28614
  runtime,
@@ -28172,27 +28713,45 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28172
28713
  onRequest: wrapNativeCallback(
28173
28714
  async (error46, payload) => {
28174
28715
  try {
28175
- const { ctx, request, cancelToken } = unwrapTsfnPayload(
28176
- error46,
28177
- payload
28178
- );
28179
- const jsRequest = buildRequest(request);
28180
- const inspectorResponse = await maybeHandleNativeInspectorRequest(
28181
- ctx,
28182
- request,
28183
- jsRequest
28184
- );
28716
+ const { ctx, request, cancelToken, responseBodyStream } = unwrapTsfnPayload(error46, payload);
28717
+ const inspectorResponse = await maybeHandleNativeInspectorRequest(ctx, request);
28185
28718
  if (inspectorResponse) {
28186
- return await toRuntimeHttpResponse(inspectorResponse);
28719
+ await cancelNativeHttpRequestBody(request.bodyStream);
28720
+ return (await convertNativeHttpResponse(
28721
+ inspectorResponse,
28722
+ responseBodyStream
28723
+ )).response;
28187
28724
  }
28188
28725
  if (typeof config3.onRequest !== "function") {
28189
- return await toRuntimeHttpResponse(
28190
- new Response(null, { status: 404 })
28191
- );
28726
+ await cancelNativeHttpRequestBody(request.bodyStream);
28727
+ return (await convertNativeHttpResponse(
28728
+ new Response(null, { status: 404 }),
28729
+ responseBodyStream
28730
+ )).response;
28192
28731
  }
28193
- const rawConnParams = jsRequest.headers.get(HEADER_CONN_PARAMS);
28732
+ const requestAbortController = new AbortController();
28733
+ const handlerRequest = buildNativeHttpRequest({
28734
+ ...request,
28735
+ abortController: requestAbortController
28736
+ });
28737
+ const rawConnParams = handlerRequest.headers.get(HEADER_CONN_PARAMS);
28194
28738
  let requestCtx;
28195
28739
  let conn;
28740
+ let removeRequestAbortListener;
28741
+ let cleanupDeferredToBody = false;
28742
+ let cleanedUp = false;
28743
+ const cleanupRequest = async () => {
28744
+ if (cleanedUp) return;
28745
+ cleanedUp = true;
28746
+ removeRequestAbortListener == null ? void 0 : removeRequestAbortListener();
28747
+ try {
28748
+ await (requestCtx == null ? void 0 : requestCtx.dispose());
28749
+ } finally {
28750
+ if (conn) {
28751
+ await runtime.connDisconnect(conn);
28752
+ }
28753
+ }
28754
+ };
28196
28755
  try {
28197
28756
  const connParams = validateConnParams(
28198
28757
  schemaConfig.connParamsSchema,
@@ -28208,23 +28767,56 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28208
28767
  requestCtx = makeConnCtx(
28209
28768
  ctx,
28210
28769
  conn,
28211
- jsRequest,
28770
+ handlerRequest,
28212
28771
  cancelToken
28213
28772
  );
28773
+ const ctxAbortSignal = requestCtx.abortSignal;
28774
+ const abortRequest = () => requestAbortController.abort(ctxAbortSignal.reason);
28775
+ if (ctxAbortSignal.aborted) {
28776
+ abortRequest();
28777
+ } else {
28778
+ ctxAbortSignal.addEventListener(
28779
+ "abort",
28780
+ abortRequest,
28781
+ { once: true }
28782
+ );
28783
+ removeRequestAbortListener = () => ctxAbortSignal.removeEventListener(
28784
+ "abort",
28785
+ abortRequest
28786
+ );
28787
+ }
28214
28788
  const response = await config3.onRequest(
28215
28789
  requestCtx,
28216
- jsRequest
28790
+ handlerRequest
28217
28791
  );
28218
- if (!(response instanceof Response)) {
28792
+ if (!isResponseLike(response)) {
28219
28793
  throw new Error(
28220
28794
  "onRequest handler must return a Response"
28221
28795
  );
28222
28796
  }
28223
- return await toRuntimeHttpResponse(response);
28797
+ const conversion = await convertNativeHttpResponse(
28798
+ response,
28799
+ responseBodyStream
28800
+ );
28801
+ if (conversion.bodyCompletion) {
28802
+ cleanupDeferredToBody = true;
28803
+ void conversion.bodyCompletion.then(cleanupRequest).catch((cleanupError) => {
28804
+ logger22().error({
28805
+ msg: "failed to clean up native streaming http request",
28806
+ error: cleanupError
28807
+ });
28808
+ });
28809
+ }
28810
+ return conversion.response;
28224
28811
  } finally {
28225
- await (requestCtx == null ? void 0 : requestCtx.dispose());
28226
- if (conn) {
28227
- await runtime.connDisconnect(conn);
28812
+ try {
28813
+ await cancelNativeHttpRequestBody(
28814
+ request.bodyStream
28815
+ );
28816
+ } finally {
28817
+ if (!cleanupDeferredToBody) {
28818
+ await cleanupRequest();
28819
+ }
28228
28820
  }
28229
28821
  }
28230
28822
  } catch (error210) {
@@ -28239,7 +28831,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28239
28831
  onWebSocket: typeof config3.onWebSocket === "function" ? wrapNativeCallback(
28240
28832
  async (error46, payload) => {
28241
28833
  const { ctx, conn, ws, request } = unwrapTsfnPayload(error46, payload);
28242
- const jsRequest = request ? buildRequest(request) : void 0;
28834
+ const jsRequest = request ? buildNativeHttpRequest(request) : void 0;
28243
28835
  const actorCtx = makeConnCtx(ctx, conn, jsRequest);
28244
28836
  try {
28245
28837
  await config3.onWebSocket(
@@ -28303,7 +28895,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28303
28895
  name,
28304
28896
  wrapNativeCallback(
28305
28897
  async (error46, payload) => {
28306
- const { ctx, conn, args, cancelToken } = unwrapTsfnPayload(error46, payload);
28898
+ const { ctx, conn, args, scheduledFire, cancelToken } = unwrapTsfnPayload(error46, payload);
28307
28899
  const actorCtx = conn != null ? makeConnCtx(ctx, conn, void 0, cancelToken) : makeActorCtx(ctx, void 0, cancelToken);
28308
28900
  try {
28309
28901
  return encodeValue(
@@ -28313,7 +28905,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28313
28905
  schemaConfig.actionInputSchemas,
28314
28906
  name,
28315
28907
  decodeArgs(args)
28316
- )
28908
+ ),
28909
+ ...scheduledFire ? [scheduledFire] : []
28317
28910
  )
28318
28911
  );
28319
28912
  } finally {
@@ -28335,7 +28928,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28335
28928
  timeoutMs,
28336
28929
  cancelToken
28337
28930
  } = unwrapTsfnPayload(error46, payload);
28338
- const jsRequest = buildRequest(request);
28931
+ const jsRequest = buildNativeHttpRequest(request);
28339
28932
  const actorCtx = withConnContext(
28340
28933
  runtime,
28341
28934
  ctx,
@@ -28469,6 +29062,7 @@ async function buildConfiguredRegistry(config3) {
28469
29062
  runtime
28470
29063
  );
28471
29064
  }
29065
+ var REGISTRY_READY_TIMEOUT_MS = 3e4;
28472
29066
  function signalExitCode(signal) {
28473
29067
  switch (signal) {
28474
29068
  case "SIGINT":
@@ -28483,6 +29077,54 @@ function finishShutdownSignal(signal) {
28483
29077
  }
28484
29078
  process.kill(process.pid, signal);
28485
29079
  }
29080
+ function createApplicationFetch(application, runtime) {
29081
+ return async (request, responseBodyStream) => {
29082
+ const method2 = request.method.toUpperCase();
29083
+ const body = method2 === "GET" || method2 === "HEAD" || request.body.length === 0 ? void 0 : Uint8Array.from(request.body).buffer;
29084
+ const abortController = new AbortController();
29085
+ if (request.cancelToken) {
29086
+ if (runtime.cancellationTokenAborted(request.cancelToken)) {
29087
+ abortController.abort();
29088
+ } else {
29089
+ runtime.onCancellationTokenCancelled(
29090
+ request.cancelToken,
29091
+ () => abortController.abort()
29092
+ );
29093
+ }
29094
+ }
29095
+ const response = await application.fetch(
29096
+ new Request(request.url, {
29097
+ method: method2,
29098
+ headers: request.headers,
29099
+ body,
29100
+ signal: abortController.signal
29101
+ })
29102
+ );
29103
+ if (!isResponseLike(response)) {
29104
+ throw new TypeError(
29105
+ "registry.listen() application fetch must return a Response"
29106
+ );
29107
+ }
29108
+ const conversion = await convertNativeHttpResponse(
29109
+ response,
29110
+ responseBodyStream
29111
+ );
29112
+ if (conversion.bodyCompletion) {
29113
+ void conversion.bodyCompletion.catch((error46) => {
29114
+ logger22().error({
29115
+ msg: "application response stream failed",
29116
+ error: error46
29117
+ });
29118
+ });
29119
+ }
29120
+ return {
29121
+ status: conversion.response.status ?? response.status,
29122
+ headers: conversion.response.headers ?? Object.fromEntries(response.headers.entries()),
29123
+ body: conversion.response.body,
29124
+ stream: conversion.response.stream
29125
+ };
29126
+ };
29127
+ }
28486
29128
  var Registry = class {
28487
29129
  #config;
28488
29130
  #buildConfiguredRegistry;
@@ -28494,8 +29136,11 @@ var Registry = class {
28494
29136
  return RegistryConfigSchema.parse(this.#config);
28495
29137
  }
28496
29138
  #runtimeServePromise;
29139
+ #runtimeServeLifecyclePromise;
29140
+ #runtimeReadyPromise;
28497
29141
  #runtimeServeConfiguredPromise;
28498
29142
  #runtimeServerlessPromise;
29143
+ #applicationListenerPromise;
28499
29144
  #configureServerlessPoolPromise;
28500
29145
  #welcomePrinted = false;
28501
29146
  #shutdownInstalled = false;
@@ -28721,18 +29366,67 @@ var Registry = class {
28721
29366
  * @param opts.host Address to bind. Defaults to `0.0.0.0`.
28722
29367
  * @param opts.publicDir If set, serves static files from this directory
28723
29368
  * as a fallback below the framework routes.
29369
+ * @param opts.application If set, handles requests that do not match a
29370
+ * framework route.
28724
29371
  *
28725
29372
  * @example
28726
29373
  * ```ts
28727
29374
  * await registry.listen();
28728
- * await registry.listen({ port: 8080, publicDir: "./public" });
29375
+ * await registry.listen({ application: app });
28729
29376
  * ```
28730
29377
  */
28731
29378
  async listen(opts = {}) {
28732
29379
  const port = opts.port ?? parsePortEnv(process.env.RIVET_PORT) ?? 3e3;
28733
29380
  const publicDir = opts.publicDir ?? getRivetkitPublicDir();
28734
29381
  const config3 = this.parseConfig();
28735
- const configuredRegistryPromise = buildConfiguredRegistry(config3);
29382
+ if (opts.application && getRivetkitRuntimeMode() !== "serverless") {
29383
+ if (config3.runtime === "wasm") {
29384
+ throw new Error(
29385
+ "registry.listen() requires the native runtime; use an application-owned HTTP server with WebAssembly"
29386
+ );
29387
+ }
29388
+ this.#installSignalHandlers(config3);
29389
+ this.#printWelcome(config3, "serverful", {
29390
+ port,
29391
+ host: opts.host,
29392
+ publicDir
29393
+ });
29394
+ this.#startEnvoy(config3, true);
29395
+ const readyPromise = this.startAndWait();
29396
+ const configuredRegistryPromise2 = this.#runtimeServeConfiguredPromise;
29397
+ if (!configuredRegistryPromise2) {
29398
+ throw new Error("registry envoy startup did not initialize");
29399
+ }
29400
+ const { runtime: runtime2, registry: registry22, serveConfig: serveConfig2 } = await configuredRegistryPromise2;
29401
+ const application2 = createApplicationFetch(
29402
+ opts.application,
29403
+ runtime2
29404
+ );
29405
+ await readyPromise;
29406
+ const listenerPromise = runtime2.serveApplicationListener(
29407
+ registry22,
29408
+ {
29409
+ port,
29410
+ host: opts.host,
29411
+ publicDir,
29412
+ application: application2
29413
+ },
29414
+ serveConfig2
29415
+ );
29416
+ this.#applicationListenerPromise = listenerPromise;
29417
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
29418
+ if (!serveLifecyclePromise) {
29419
+ throw new Error(
29420
+ "registry envoy serve lifecycle did not initialize"
29421
+ );
29422
+ }
29423
+ await Promise.all([
29424
+ listenerPromise,
29425
+ serveLifecyclePromise
29426
+ ]);
29427
+ return;
29428
+ }
29429
+ const configuredRegistryPromise = this.#buildConfiguredRegistry(config3);
28736
29430
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
28737
29431
  this.#runtimeServerlessPromise = configuredRegistryPromise;
28738
29432
  this.#installSignalHandlers(config3);
@@ -28743,9 +29437,15 @@ var Registry = class {
28743
29437
  });
28744
29438
  this.#ensureServerlessPoolConfigured(config3);
28745
29439
  const { runtime, registry: registry2, serveConfig } = await configuredRegistryPromise;
29440
+ const application = opts.application ? createApplicationFetch(opts.application, runtime) : void 0;
28746
29441
  await runtime.serveListener(
28747
29442
  registry2,
28748
- { port, host: opts.host, publicDir },
29443
+ {
29444
+ port,
29445
+ host: opts.host,
29446
+ publicDir,
29447
+ application
29448
+ },
28749
29449
  serveConfig
28750
29450
  );
28751
29451
  }
@@ -28840,9 +29540,12 @@ var Registry = class {
28840
29540
  if (!this.#runtimeServePromise) {
28841
29541
  const configuredRegistryPromise = this.#buildConfiguredRegistry(config3);
28842
29542
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
28843
- this.#runtimeServePromise = configuredRegistryPromise.then(async ({ runtime, registry: registry2, serveConfig }) => {
28844
- await runtime.serveRegistry(registry2, serveConfig);
28845
- }).catch((error46) => {
29543
+ this.#runtimeServeLifecyclePromise = configuredRegistryPromise.then(
29544
+ async ({ runtime, registry: registry2, serveConfig }) => {
29545
+ await runtime.serveRegistry(registry2, serveConfig);
29546
+ }
29547
+ );
29548
+ this.#runtimeServePromise = this.#runtimeServeLifecyclePromise.catch((error46) => {
28846
29549
  logger22().warn({ error: error46 }, "runtime registry serve errored");
28847
29550
  });
28848
29551
  this.#installSignalHandlers(config3);
@@ -28951,6 +29654,9 @@ var Registry = class {
28951
29654
  if (runtimeServePromise !== void 0) {
28952
29655
  await runtimeServePromise.catch(() => void 0);
28953
29656
  }
29657
+ if (this.#applicationListenerPromise !== void 0) {
29658
+ await this.#applicationListenerPromise.catch(() => void 0);
29659
+ }
28954
29660
  };
28955
29661
  await Promise.race([
28956
29662
  drain(),
@@ -28990,6 +29696,79 @@ var Registry = class {
28990
29696
  startEnvoy() {
28991
29697
  this.#startEnvoy(this.parseConfig(), true);
28992
29698
  }
29699
+ /**
29700
+ * Starts the serverful registry if needed and waits until its envoy has
29701
+ * registered with the Engine. Repeated and concurrent calls share one
29702
+ * startup lifecycle and readiness promise.
29703
+ *
29704
+ * Unlike {@link start}, this reports startup failures and does not resolve
29705
+ * merely because an HTTP health endpoint is listening.
29706
+ */
29707
+ startAndWait() {
29708
+ if (this.#shutdownInFlight !== null) {
29709
+ return Promise.reject(
29710
+ new Error(
29711
+ "registry.startAndWait() cannot run after shutdown has begun"
29712
+ )
29713
+ );
29714
+ }
29715
+ if (this.#runtimeReadyPromise) return this.#runtimeReadyPromise;
29716
+ if (getRivetkitRuntimeMode() === "serverless") {
29717
+ return Promise.reject(
29718
+ new Error(
29719
+ "registry.startAndWait() requires envoy runtime mode; serverless registries become ready per request"
29720
+ )
29721
+ );
29722
+ }
29723
+ const config3 = this.parseConfig();
29724
+ if (config3.runtime === "wasm") {
29725
+ return Promise.reject(
29726
+ new Error(
29727
+ "registry.startAndWait() requires the native runtime; WebAssembly registries do not host an envoy"
29728
+ )
29729
+ );
29730
+ }
29731
+ this.#startEnvoy(config3, true);
29732
+ const configuredRegistryPromise = this.#runtimeServeConfiguredPromise;
29733
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
29734
+ if (!configuredRegistryPromise || !serveLifecyclePromise) {
29735
+ throw new Error("registry envoy startup did not initialize");
29736
+ }
29737
+ let timeout;
29738
+ const timeoutPromise = new Promise((_resolve, reject) => {
29739
+ var _a2;
29740
+ timeout = setTimeout(
29741
+ () => reject(
29742
+ new Error(
29743
+ `RivetKit registry did not register with the Engine within ${REGISTRY_READY_TIMEOUT_MS}ms`
29744
+ )
29745
+ ),
29746
+ REGISTRY_READY_TIMEOUT_MS
29747
+ );
29748
+ (_a2 = timeout.unref) == null ? void 0 : _a2.call(timeout);
29749
+ });
29750
+ const readinessPromise = (async () => {
29751
+ const { runtime, registry: registry2 } = await configuredRegistryPromise;
29752
+ const stoppedBeforeReady = serveLifecyclePromise.then(() => {
29753
+ throw new Error(
29754
+ "RivetKit registry stopped before becoming ready"
29755
+ );
29756
+ });
29757
+ await Promise.race([
29758
+ runtime.waitRegistryReady(registry2),
29759
+ stoppedBeforeReady
29760
+ ]);
29761
+ })();
29762
+ this.#runtimeReadyPromise = Promise.race([
29763
+ readinessPromise,
29764
+ timeoutPromise
29765
+ ]).finally(() => {
29766
+ if (timeout !== void 0) clearTimeout(timeout);
29767
+ });
29768
+ this.#runtimeReadyPromise.catch(() => {
29769
+ });
29770
+ return this.#runtimeReadyPromise;
29771
+ }
28993
29772
  /**
28994
29773
  * Starts the actor envoy for standalone server deployments.
28995
29774
  *