@rivetkit/supabase 0.0.0-main.49693dc → 0.0.0-main.78336a1

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 +1534 -1220
  2. package/dist/mod.mjs +1534 -1220
  3. package/package.json +3 -3
package/dist/mod.js CHANGED
@@ -335,193 +335,6 @@ __export(mod_exports, {
335
335
  module.exports = __toCommonJS(mod_exports);
336
336
  var wasmBindings = __toESM(require("@rivetkit/rivetkit-wasm"));
337
337
 
338
- // ../rivetkit/dist/tsup/chunk-IXBD7BXC.js
339
- var INTERNAL_ERROR_CODE = "internal_error";
340
- var INTERNAL_ERROR_DESCRIPTION = "An internal error occurred";
341
- var USER_ERROR_CODE = "user_error";
342
- var BRIDGE_RIVET_ERROR_PREFIX = "__RIVET_ERROR_JSON__:";
343
- function looksLikeRivetErrorOptions(value) {
344
- return typeof value === "object" && value !== null && ("public" in value || "metadata" in value || "rayId" in value || "statusCode" in value || "actor" in value || "cause" in value);
345
- }
346
- function isTypedErrorTag(value) {
347
- return value === "ActorError" || value === "RivetError";
348
- }
349
- function errorMessage(error46, fallback = String(error46)) {
350
- if (error46 && typeof error46 === "object" && "message" in error46 && typeof error46.message === "string") {
351
- return error46.message;
352
- }
353
- return fallback;
354
- }
355
- function isRivetErrorLike(error46) {
356
- return typeof error46 === "object" && error46 !== null && "group" in error46 && typeof error46.group === "string" && "code" in error46 && typeof error46.code === "string" && "message" in error46 && typeof error46.message === "string" && (!("rayId" in error46) || error46.rayId === void 0 || typeof error46.rayId === "string") && (!("__type" in error46) || isTypedErrorTag(error46.__type));
357
- }
358
- function isActorAbortedError(error46) {
359
- return isRivetErrorLike(error46) && error46.group === "actor" && error46.code === "aborted";
360
- }
361
- function isActorSpecifier(value) {
362
- return typeof value === "object" && value !== null && "actorId" in value && typeof value.actorId === "string" && "generation" in value && typeof value.generation === "number" && (!("key" in value) || value.key === void 0 || typeof value.key === "string");
363
- }
364
- var RivetError = class extends Error {
365
- __type = "RivetError";
366
- public;
367
- metadata;
368
- rayId;
369
- statusCode;
370
- actor;
371
- group;
372
- code;
373
- static isRivetError(error46) {
374
- return isRivetErrorLike(error46);
375
- }
376
- static isActorError(error46) {
377
- return isRivetErrorLike(error46);
378
- }
379
- constructor(group, code, message, options) {
380
- const normalized = looksLikeRivetErrorOptions(options) ? options : { metadata: options };
381
- super(message, { cause: normalized.cause });
382
- this.name = "RivetError";
383
- this.group = group;
384
- this.code = code;
385
- this.public = normalized.public ?? false;
386
- this.metadata = normalized.metadata;
387
- this.rayId = normalized.rayId ?? void 0;
388
- this.statusCode = normalized.statusCode ?? (this.public ? 400 : 500);
389
- this.actor = normalized.actor;
390
- }
391
- toString() {
392
- return this.message;
393
- }
394
- };
395
- var UserError = class extends RivetError {
396
- constructor(message, options) {
397
- super("user", (options == null ? void 0 : options.code) ?? USER_ERROR_CODE, message, {
398
- public: true,
399
- metadata: options == null ? void 0 : options.metadata,
400
- cause: options == null ? void 0 : options.cause
401
- });
402
- }
403
- };
404
- function toRivetError(error46, fallback) {
405
- if (typeof error46 === "string") {
406
- const bridged = decodeBridgeRivetError(error46);
407
- if (bridged) {
408
- return bridged;
409
- }
410
- }
411
- if (error46 instanceof Error) {
412
- const bridged = decodeBridgeRivetError(error46.message);
413
- if (bridged) {
414
- return bridged;
415
- }
416
- }
417
- if (isRivetErrorLike(error46)) {
418
- return new RivetError(error46.group, error46.code, error46.message, {
419
- public: error46.public,
420
- statusCode: error46.statusCode,
421
- metadata: error46.metadata,
422
- rayId: error46.rayId,
423
- actor: error46.actor,
424
- cause: error46 instanceof Error ? error46.cause : void 0
425
- });
426
- }
427
- return new RivetError(
428
- (fallback == null ? void 0 : fallback.group) ?? "actor",
429
- (fallback == null ? void 0 : fallback.code) ?? INTERNAL_ERROR_CODE,
430
- errorMessage(error46, (fallback == null ? void 0 : fallback.message) ?? "Unknown error"),
431
- {
432
- public: fallback == null ? void 0 : fallback.public,
433
- statusCode: fallback == null ? void 0 : fallback.statusCode,
434
- metadata: fallback == null ? void 0 : fallback.metadata,
435
- rayId: fallback == null ? void 0 : fallback.rayId,
436
- actor: fallback == null ? void 0 : fallback.actor,
437
- cause: error46 instanceof Error ? error46 : void 0
438
- }
439
- );
440
- }
441
- function encodeBridgeRivetError(error46) {
442
- return `${BRIDGE_RIVET_ERROR_PREFIX}${JSON.stringify({
443
- group: error46.group,
444
- code: error46.code,
445
- message: error46.message,
446
- metadata: error46.metadata,
447
- rayId: error46.rayId,
448
- public: error46.public,
449
- statusCode: error46.statusCode,
450
- actor: error46.actor
451
- })}`;
452
- }
453
- function decodeBridgeRivetErrorPayload(value) {
454
- if (!value.startsWith(BRIDGE_RIVET_ERROR_PREFIX)) {
455
- return void 0;
456
- }
457
- try {
458
- const raw = JSON.parse(
459
- value.slice(BRIDGE_RIVET_ERROR_PREFIX.length)
460
- );
461
- const payload = {
462
- ...raw,
463
- rayId: raw.rayId ?? void 0
464
- };
465
- if (!isRivetErrorLike(payload)) {
466
- return void 0;
467
- }
468
- if (payload.actor !== void 0 && payload.actor !== null && !isActorSpecifier(payload.actor)) {
469
- return void 0;
470
- }
471
- return payload;
472
- } catch {
473
- return void 0;
474
- }
475
- }
476
- function decodeBridgeRivetError(value) {
477
- const payload = decodeBridgeRivetErrorPayload(value);
478
- if (!payload) {
479
- return void 0;
480
- }
481
- return new RivetError(payload.group, payload.code, payload.message, {
482
- metadata: payload.metadata,
483
- rayId: payload.rayId,
484
- public: payload.public,
485
- statusCode: payload.statusCode,
486
- actor: payload.actor ?? void 0
487
- });
488
- }
489
- function invalidRequest(error46) {
490
- return new RivetError(
491
- "request",
492
- "invalid",
493
- `Invalid request: ${errorMessage(error46, String(error46))}`,
494
- {
495
- public: true,
496
- cause: error46 instanceof Error ? error46 : void 0
497
- }
498
- );
499
- }
500
- function actorNotFound(identifier) {
501
- return new RivetError(
502
- "actor",
503
- "not_found",
504
- identifier ? `Actor not found: ${identifier} (https://www.rivet.dev/docs/clients/javascript)` : "Actor not found (https://www.rivet.dev/docs/clients/javascript)",
505
- { public: true }
506
- );
507
- }
508
- function forbiddenError() {
509
- return new RivetError("auth", "forbidden", "Forbidden", {
510
- public: true,
511
- statusCode: 403
512
- });
513
- }
514
- function unsupportedFeature(feature) {
515
- return new RivetError(
516
- "feature",
517
- "unsupported",
518
- `Unsupported feature: ${feature}`
519
- );
520
- }
521
-
522
- // ../rivetkit/dist/tsup/chunk-5IU3MI7X.js
523
- var import_pino = require("pino");
524
-
525
338
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/classic/external.js
526
339
  var external_exports = {};
527
340
  __export(external_exports, {
@@ -13192,284 +13005,937 @@ var classic_default = external_exports;
13192
13005
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/index.js
13193
13006
  var v4_default = classic_default;
13194
13007
 
13195
- // ../rivetkit/dist/tsup/chunk-5IU3MI7X.js
13196
- var cbor = __toESM(require("cbor-x"), 1);
13197
- var import_invariant = __toESM(require_invariant(), 1);
13198
- var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
13199
- var getRivetEndpoint = () => getEnvUniversal("RIVET_ENDPOINT");
13200
- var getRivetToken = () => getEnvUniversal("RIVET_TOKEN");
13201
- var getRivetNamespace = () => getEnvUniversal("RIVET_NAMESPACE");
13202
- var getRivetPool = () => getEnvUniversal("RIVET_POOL");
13203
- var getRivetTotalSlots = () => {
13204
- const value = getEnvUniversal("RIVET_TOTAL_SLOTS");
13205
- return value !== void 0 ? parseInt(value, 10) : void 0;
13206
- };
13207
- var getRivetRunEngine = () => getEnvUniversal("RIVET_RUN_ENGINE") === "1";
13208
- var getRivetRunEngineHost = () => getEnvUniversal("RIVET_RUN_ENGINE_HOST");
13209
- var getRivetRunEnginePort = () => {
13210
- const value = getEnvUniversal("RIVET_RUN_ENGINE_PORT");
13211
- return value !== void 0 ? parseInt(value, 10) : void 0;
13212
- };
13213
- var getRivetRunEngineVersion = () => getEnvUniversal("RIVET_RUN_ENGINE_VERSION");
13214
- var getRivetEnvoyVersion = () => {
13215
- const value = getEnvUniversal("RIVET_ENVOY_VERSION");
13216
- return value !== void 0 ? parseInt(value, 10) : void 0;
13217
- };
13218
- var getRivetPublicEndpoint = () => getEnvUniversal("RIVET_PUBLIC_ENDPOINT");
13219
- var getRivetPublicToken = () => getEnvUniversal("RIVET_PUBLIC_TOKEN");
13220
- var getRivetkitRuntime = () => getEnvUniversal("RIVETKIT_RUNTIME");
13221
- var getRivetkitRuntimeMode = () => {
13222
- const value = getEnvUniversal("RIVETKIT_RUNTIME_MODE");
13223
- if (value === void 0) return "envoy";
13224
- if (value === "envoy" || value === "serverless") return value;
13225
- throw new Error(
13226
- `RIVETKIT_RUNTIME_MODE env var must be "envoy" or "serverless"; got "${value}"`
13227
- );
13228
- };
13229
- var getRivetkitPublicDir = () => {
13230
- const value = getEnvUniversal("RIVETKIT_PUBLIC_DIR");
13231
- return value === void 0 || value === "" ? void 0 : value;
13232
- };
13233
- function parsePortEnv(raw) {
13234
- if (raw === void 0 || raw === "") return void 0;
13235
- const parsed = Number.parseInt(raw, 10);
13236
- if (!Number.isFinite(parsed) || parsed < 1 || parsed > 65535 || String(parsed) !== raw.trim()) {
13237
- throw new Error(
13238
- `RIVET_PORT env var must be an integer between 1 and 65535; got "${raw}"`
13239
- );
13008
+ // ../rivetkit/dist/tsup/chunk-6W5VGLFT.js
13009
+ function flattenActionHandlers(actions) {
13010
+ const flattened = /* @__PURE__ */ Object.create(null);
13011
+ for (const { name, handler } of collectActionEntries(actions)) {
13012
+ flattened[name] = handler;
13240
13013
  }
13241
- return parsed;
13242
- }
13243
- var getLogLevel = () => getEnvUniversal("RIVET_LOG_LEVEL") ?? getEnvUniversal("LOG_LEVEL");
13244
- var getLogTarget = () => getEnvUniversal("RIVET_LOG_TARGET") === "1";
13245
- var getLogTimestamp = () => getEnvUniversal("RIVET_LOG_TIMESTAMP") === "1";
13246
- var getLogMessage = () => getEnvUniversal("RIVET_LOG_MESSAGE") === "1";
13247
- var getLogErrorStack = () => getEnvUniversal("RIVET_LOG_ERROR_STACK") === "1";
13248
- var getNodeEnv = () => getEnvUniversal("NODE_ENV");
13249
- var getNextPhase = () => getEnvUniversal("NEXT_PHASE");
13250
- var isDev = () => getNodeEnv() !== "production";
13251
- function assertUnreachable(x) {
13252
- throw new Error(`Unreachable case: ${x}`);
13253
- }
13254
- function isCanonicalStructuredRivetError(error46) {
13255
- return error46 instanceof RivetError || typeof error46 === "object" && error46 !== null && "__type" in error46 && error46.__type === "RivetError" && "group" in error46 && typeof error46.group === "string" && "code" in error46 && typeof error46.code === "string" && "message" in error46 && typeof error46.message === "string";
13014
+ return flattened;
13256
13015
  }
13257
- function deconstructError(error46, exposeInternalError = false) {
13258
- let statusCode;
13259
- let public_;
13260
- let group;
13261
- let code;
13262
- let message;
13263
- let metadata;
13264
- let rayId;
13265
- let actor2;
13266
- if (isCanonicalStructuredRivetError(error46)) {
13267
- statusCode = typeof error46.statusCode === "number" ? error46.statusCode : error46.public ? 400 : 500;
13268
- public_ = error46.public ?? false;
13269
- group = error46.group;
13270
- code = error46.code;
13271
- message = error46.message;
13272
- metadata = error46.metadata;
13273
- rayId = error46.rayId;
13274
- actor2 = error46.actor;
13275
- } else if (RivetError.isActorError(error46) && error46.public) {
13276
- statusCode = "statusCode" in error46 && error46.statusCode ? error46.statusCode : 400;
13277
- public_ = true;
13278
- group = error46.group;
13279
- code = error46.code;
13280
- message = getErrorMessage(error46);
13281
- metadata = error46.metadata;
13282
- rayId = error46.rayId;
13283
- actor2 = error46.actor;
13284
- } else if (exposeInternalError) {
13285
- if (RivetError.isActorError(error46)) {
13286
- statusCode = 500;
13287
- public_ = false;
13288
- group = error46.group;
13289
- code = error46.code;
13290
- message = getErrorMessage(error46);
13291
- metadata = error46.metadata;
13292
- rayId = error46.rayId;
13293
- actor2 = error46.actor;
13294
- } else {
13295
- statusCode = 500;
13296
- public_ = false;
13297
- group = "rivetkit";
13298
- code = INTERNAL_ERROR_CODE;
13299
- message = getErrorMessage(error46);
13016
+ function flattenActionInputSchemas(actions, schemas) {
13017
+ if (schemas === void 0) return void 0;
13018
+ if (!isRecord(schemas)) {
13019
+ throw new TypeError("actionInputSchemas must be an object");
13020
+ }
13021
+ const flattened = /* @__PURE__ */ Object.create(null);
13022
+ for (const { name, path: path2 } of collectActionEntries(actions)) {
13023
+ const nestedSchema = lookupNestedSchema(schemas, path2);
13024
+ const flatSchema = schemas[name];
13025
+ if (nestedSchema !== void 0 && flatSchema !== void 0 && nestedSchema !== flatSchema) {
13026
+ throw new TypeError(
13027
+ `Action input schema \`${name}\` is defined by both a nested path and a dotted key`
13028
+ );
13300
13029
  }
13301
- } else {
13302
- statusCode = 500;
13303
- public_ = false;
13304
- group = "rivetkit";
13305
- code = INTERNAL_ERROR_CODE;
13306
- message = INTERNAL_ERROR_DESCRIPTION;
13307
- if (RivetError.isActorError(error46)) {
13308
- actor2 = error46.actor;
13030
+ const schema = nestedSchema ?? flatSchema;
13031
+ if (schema !== void 0) {
13032
+ flattened[name] = schema;
13309
13033
  }
13310
- metadata = {
13311
- //url: `https://dashboard.rivet.dev/projects/${actorMetadata.project.slug}/environments/${actorMetadata.environment.slug}/actors?actorId=${actorMetadata.actor.id}`,
13312
- };
13313
13034
  }
13314
- return {
13315
- __type: "ActorError",
13316
- statusCode,
13317
- public: public_,
13318
- group,
13319
- code,
13320
- message,
13321
- metadata,
13322
- rayId,
13323
- actor: actor2
13324
- };
13035
+ return flattened;
13325
13036
  }
13326
- function stringifyError(error46) {
13327
- if (error46 instanceof Error) {
13328
- if (typeof process !== "undefined" && getLogErrorStack()) {
13329
- let stack;
13330
- try {
13331
- stack = error46.stack;
13332
- } catch {
13333
- stack = void 0;
13037
+ function collectActionEntries(actions) {
13038
+ const entries = [];
13039
+ const names = /* @__PURE__ */ new Set();
13040
+ visitActionGroup(actions ?? {}, [], entries, names);
13041
+ return entries;
13042
+ }
13043
+ function visitActionGroup(value, path2, entries, names) {
13044
+ if (!isRecord(value)) {
13045
+ throw new TypeError(
13046
+ `${formatActionPath(path2)} must be an action handler or group`
13047
+ );
13048
+ }
13049
+ for (const [segment, child] of Object.entries(value)) {
13050
+ const childPath = [...path2, segment];
13051
+ if (typeof child === "function") {
13052
+ const name = childPath.join(".");
13053
+ if (names.has(name)) {
13054
+ throw new TypeError(
13055
+ `Multiple action definitions flatten to \`${name}\``
13056
+ );
13334
13057
  }
13335
- return `${error46.name}: ${error46.message}${stack ? `
13336
- ${stack}` : ""}`;
13058
+ names.add(name);
13059
+ entries.push({
13060
+ name,
13061
+ path: childPath,
13062
+ handler: child
13063
+ });
13337
13064
  } else {
13338
- return `${error46.name}: ${error46.message}`;
13065
+ visitActionGroup(child, childPath, entries, names);
13339
13066
  }
13340
- } else if (typeof error46 === "string") {
13341
- return error46;
13342
- } else if (typeof error46 === "object" && error46 !== null) {
13343
- try {
13344
- return `${JSON.stringify(error46)}`;
13345
- } catch {
13346
- return "[cannot stringify error]";
13067
+ }
13068
+ }
13069
+ function lookupNestedSchema(schemas, path2) {
13070
+ let value = schemas;
13071
+ for (const segment of path2) {
13072
+ if (!isRecord(value) || !Object.hasOwn(value, segment)) {
13073
+ return void 0;
13347
13074
  }
13348
- } else {
13349
- return `Unknown error: ${getErrorMessage(error46)}`;
13075
+ value = value[segment];
13350
13076
  }
13077
+ return value;
13351
13078
  }
13352
- function getErrorMessage(err) {
13353
- if (err && typeof err === "object" && "message" in err && typeof err.message === "string") {
13354
- return err.message;
13355
- } else {
13356
- return String(err);
13079
+ function isRecord(value) {
13080
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
13081
+ return false;
13357
13082
  }
13083
+ const prototype = Object.getPrototypeOf(value);
13084
+ return prototype === Object.prototype || prototype === null;
13358
13085
  }
13359
- function noopNext() {
13360
- return async () => {
13361
- };
13086
+ function formatActionPath(path2) {
13087
+ return path2.length === 0 ? "actions" : `Action \`${path2.join(".")}\``;
13362
13088
  }
13363
- var package_default = {
13364
- name: "rivetkit",
13365
- version: "0.0.0-main.49693dc",
13366
- description: "Lightweight libraries for building stateful actors on edge platforms",
13367
- license: "Apache-2.0",
13368
- keywords: [
13369
- "rivetkit",
13370
- "stateful",
13371
- "serverless",
13372
- "actors",
13373
- "agents",
13374
- "realtime",
13375
- "websocket",
13376
- "actors",
13377
- "framework"
13378
- ],
13379
- files: [
13380
- "dist",
13381
- "schemas",
13382
- "src",
13383
- "package.json"
13384
- ],
13385
- type: "module",
13386
- exports: {
13387
- ".": {
13388
- import: {
13389
- types: "./dist/tsup/mod.d.ts",
13390
- default: "./dist/tsup/mod.js"
13391
- },
13392
- require: {
13393
- types: "./dist/tsup/mod.d.cts",
13394
- default: "./dist/tsup/mod.cjs"
13395
- }
13396
- },
13397
- "./workflow": {
13398
- import: {
13399
- types: "./dist/tsup/workflow/mod.d.ts",
13400
- default: "./dist/tsup/workflow/mod.js"
13401
- },
13402
- require: {
13403
- types: "./dist/tsup/workflow/mod.d.cts",
13404
- default: "./dist/tsup/workflow/mod.cjs"
13405
- }
13406
- },
13407
- "./test": {
13408
- import: {
13409
- types: "./dist/tsup/test/mod.d.ts",
13410
- default: "./dist/tsup/test/mod.js"
13411
- },
13412
- require: {
13413
- types: "./dist/tsup/test/mod.d.cts",
13414
- default: "./dist/tsup/test/mod.cjs"
13415
- }
13416
- },
13417
- "./db": {
13418
- import: {
13419
- types: "./dist/tsup/db/mod.d.ts",
13420
- default: "./dist/tsup/db/mod.js"
13421
- },
13422
- require: {
13423
- types: "./dist/tsup/db/mod.d.cts",
13424
- default: "./dist/tsup/db/mod.cjs"
13425
- }
13426
- },
13427
- "./db/drizzle": {
13428
- import: {
13429
- types: "./dist/tsup/db/drizzle.d.ts",
13430
- default: "./dist/tsup/db/drizzle.js"
13431
- },
13432
- require: {
13433
- types: "./dist/tsup/db/drizzle.d.cts",
13434
- default: "./dist/tsup/db/drizzle.cjs"
13435
- }
13436
- },
13437
- "./unstable/migrations": {
13438
- import: {
13439
- types: "./dist/tsup/unstable/migrations.d.ts",
13440
- default: "./dist/tsup/unstable/migrations.js"
13441
- },
13442
- require: {
13443
- types: "./dist/tsup/unstable/migrations.d.cts",
13444
- default: "./dist/tsup/unstable/migrations.cjs"
13445
- }
13446
- },
13447
- "./dynamic": {
13448
- import: {
13449
- types: "./dist/tsup/dynamic/mod.d.ts",
13450
- default: "./dist/tsup/dynamic/mod.js"
13451
- },
13452
- require: {
13453
- types: "./dist/tsup/dynamic/mod.d.cts",
13454
- default: "./dist/tsup/dynamic/mod.cjs"
13455
- }
13456
- },
13457
- "./client": {
13458
- import: {
13459
- browser: {
13460
- types: "./dist/browser/client.d.ts",
13461
- default: "./dist/browser/client.js"
13462
- },
13463
- types: "./dist/tsup/client/mod.d.ts",
13464
- default: "./dist/tsup/client/mod.js"
13465
- },
13466
- require: {
13467
- types: "./dist/tsup/client/mod.d.cts",
13468
- default: "./dist/tsup/client/mod.cjs"
13469
- }
13470
- },
13471
- "./log": {
13472
- import: {
13089
+ var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
13090
+ var ACTOR_CONTEXT_INTERNAL_SYMBOL = /* @__PURE__ */ Symbol(
13091
+ "rivetkit.actor_context_internal"
13092
+ );
13093
+ var RAW_STATE_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.raw_state");
13094
+ var CONN_STATE_MANAGER_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.conn_state_manager");
13095
+ var zFunction = () => external_exports.custom((val) => typeof val === "function");
13096
+ var zActionTree = external_exports.custom((value) => {
13097
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
13098
+ return false;
13099
+ }
13100
+ const prototype = Object.getPrototypeOf(value);
13101
+ return prototype === Object.prototype || prototype === null;
13102
+ }).superRefine((actions, ctx) => {
13103
+ try {
13104
+ flattenActionHandlers(actions);
13105
+ } catch (error46) {
13106
+ ctx.addIssue({
13107
+ code: "custom",
13108
+ message: error46 instanceof Error ? error46.message : "Invalid action definition"
13109
+ });
13110
+ }
13111
+ });
13112
+ var WorkflowInspectorConfigSchema = external_exports.object({
13113
+ getHistory: zFunction(),
13114
+ getState: zFunction().optional(),
13115
+ onHistoryUpdated: zFunction().optional(),
13116
+ replayFromStep: zFunction().optional()
13117
+ });
13118
+ var RunInspectorConfigSchema = external_exports.object({
13119
+ workflow: WorkflowInspectorConfigSchema.optional()
13120
+ }).optional();
13121
+ var BUILTIN_INSPECTOR_TAB_IDS = [
13122
+ "workflow",
13123
+ "database",
13124
+ "state",
13125
+ "queue",
13126
+ "schedules",
13127
+ "connections",
13128
+ "console"
13129
+ ];
13130
+ var BuiltinInspectorTabIdSchema = external_exports.enum(BUILTIN_INSPECTOR_TAB_IDS);
13131
+ var CUSTOM_INSPECTOR_TAB_ID_RE = /^[A-Za-z0-9_-]+$/;
13132
+ var CustomInspectorTabEntrySchema = external_exports.object({
13133
+ id: external_exports.string().regex(
13134
+ CUSTOM_INSPECTOR_TAB_ID_RE,
13135
+ "inspector.tabs[].id must contain only letters, digits, underscore, or dash"
13136
+ ),
13137
+ label: external_exports.string().min(1),
13138
+ source: external_exports.string().min(1),
13139
+ /**
13140
+ * Optional icon id. The dashboard maps strings to glyphs (see its
13141
+ * icon registry); unknown ids fall back to a generic icon.
13142
+ */
13143
+ icon: external_exports.string().min(1).optional(),
13144
+ hidden: external_exports.literal(false).optional()
13145
+ }).strict();
13146
+ var HideInspectorTabEntrySchema = external_exports.object({
13147
+ id: BuiltinInspectorTabIdSchema,
13148
+ hidden: external_exports.literal(true)
13149
+ }).strict();
13150
+ var InspectorTabEntrySchema = external_exports.union([
13151
+ CustomInspectorTabEntrySchema,
13152
+ HideInspectorTabEntrySchema
13153
+ ]);
13154
+ var ActorInspectorConfigSchema = external_exports.object({
13155
+ tabs: external_exports.array(InspectorTabEntrySchema).default(() => [])
13156
+ }).strict().refine(
13157
+ (data) => {
13158
+ const ids = data.tabs.map((t) => t.id);
13159
+ return new Set(ids).size === ids.length;
13160
+ },
13161
+ { message: "Duplicate id in inspector.tabs", path: ["tabs"] }
13162
+ ).refine(
13163
+ (data) => {
13164
+ const builtinSet = new Set(BUILTIN_INSPECTOR_TAB_IDS);
13165
+ return data.tabs.every(
13166
+ (t) => t.hidden === true || !builtinSet.has(t.id)
13167
+ );
13168
+ },
13169
+ {
13170
+ message: "Custom inspector tab id collides with a built-in (use hidden: true to hide a built-in)",
13171
+ path: ["tabs"]
13172
+ }
13173
+ );
13174
+ var RunConfigSchema = external_exports.object({
13175
+ /** Display name for the actor in the Inspector UI. */
13176
+ name: external_exports.string().optional(),
13177
+ /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
13178
+ icon: external_exports.string().optional(),
13179
+ /** The run handler function. */
13180
+ run: zFunction(),
13181
+ /** Inspector integration for long-running run handlers. */
13182
+ inspector: RunInspectorConfigSchema.optional()
13183
+ });
13184
+ var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("rivetkit.run_function_config");
13185
+ function defineRunHandler(run, options) {
13186
+ if (options.inspectorKind === void 0 !== (options.createInspector === void 0)) {
13187
+ throw new TypeError(
13188
+ "defineRunHandler requires inspectorKind and createInspector together"
13189
+ );
13190
+ }
13191
+ Object.defineProperty(run, RUN_FUNCTION_CONFIG_SYMBOL, {
13192
+ configurable: false,
13193
+ enumerable: false,
13194
+ writable: false,
13195
+ value: {
13196
+ name: options.name,
13197
+ icon: options.icon,
13198
+ inspectorKind: options.inspectorKind,
13199
+ createInspector: options.createInspector
13200
+ }
13201
+ });
13202
+ return run;
13203
+ }
13204
+ function getRunInspectorKind(run) {
13205
+ var _a2;
13206
+ if (!run || typeof run !== "function") return void 0;
13207
+ return (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.inspectorKind;
13208
+ }
13209
+ function createRunInspector(run, context) {
13210
+ var _a2, _b;
13211
+ if (!run || typeof run !== "function") return void 0;
13212
+ return (_b = (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.createInspector) == null ? void 0 : _b.call(_a2, context);
13213
+ }
13214
+ var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
13215
+ function getRunFunction(run) {
13216
+ if (!run) return void 0;
13217
+ if (typeof run === "function") return run;
13218
+ return run.run;
13219
+ }
13220
+ function getRunMetadata(run) {
13221
+ if (!run) return {};
13222
+ if (typeof run === "function") {
13223
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13224
+ if (!config3) return {};
13225
+ return { name: config3.name, icon: config3.icon };
13226
+ }
13227
+ return { name: run.name, icon: run.icon };
13228
+ }
13229
+ function getRunInspectorConfig(run, actor2) {
13230
+ if (!run) return void 0;
13231
+ if (typeof run === "function") {
13232
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13233
+ return (config3 == null ? void 0 : config3.inspectorFactory) ? config3.inspectorFactory(actor2) : config3 == null ? void 0 : config3.inspector;
13234
+ }
13235
+ return run.inspector;
13236
+ }
13237
+ function hasRunInspectorConfig(run) {
13238
+ if (!run) return false;
13239
+ if (typeof run !== "function") return run.inspector !== void 0;
13240
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13241
+ return (config3 == null ? void 0 : config3.inspectorKind) !== void 0 || (config3 == null ? void 0 : config3.createInspector) !== void 0 || (config3 == null ? void 0 : config3.inspector) !== void 0 || (config3 == null ? void 0 : config3.inspectorFactory) !== void 0;
13242
+ }
13243
+ function disposeRunInspector(run, actorId) {
13244
+ var _a2;
13245
+ if (!run || typeof run !== "function") {
13246
+ return;
13247
+ }
13248
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13249
+ (_a2 = config3 == null ? void 0 : config3.disposeInspector) == null ? void 0 : _a2.call(config3, actorId);
13250
+ }
13251
+ var GlobalActorOptionsBaseSchema = external_exports.object({
13252
+ /** Display name for the actor in the Inspector UI. */
13253
+ name: external_exports.string().optional(),
13254
+ /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
13255
+ icon: external_exports.string().optional(),
13256
+ /** Enables the experimental Actor Runtime Socket for this actor. */
13257
+ enableActorRuntimeSocket: external_exports.boolean().default(false),
13258
+ /**
13259
+ * Can hibernate WebSockets for onWebSocket.
13260
+ *
13261
+ * WebSockets using actions/events are hibernatable by default.
13262
+ *
13263
+ * @experimental
13264
+ **/
13265
+ canHibernateWebSocket: external_exports.union([external_exports.boolean(), zFunction()]).default(false)
13266
+ }).strict();
13267
+ var GlobalActorOptionsSchema = GlobalActorOptionsBaseSchema.prefault(
13268
+ () => ({})
13269
+ );
13270
+ var InstanceActorOptionsBaseSchema = external_exports.object({
13271
+ createVarsTimeout: external_exports.number().positive().default(5e3),
13272
+ createConnStateTimeout: external_exports.number().positive().default(5e3),
13273
+ onBeforeConnectTimeout: external_exports.number().positive().default(5e3),
13274
+ onConnectTimeout: external_exports.number().positive().default(5e3),
13275
+ onMigrateTimeout: external_exports.number().positive().default(3e4),
13276
+ sleepGracePeriod: external_exports.number().positive().default(DEFAULT_SLEEP_GRACE_PERIOD),
13277
+ /** @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. */
13278
+ onDestroyTimeout: external_exports.number().positive().optional(),
13279
+ /** @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. */
13280
+ waitUntilTimeout: external_exports.number().positive().optional(),
13281
+ stateSaveInterval: external_exports.number().positive().default(1e3),
13282
+ actionTimeout: external_exports.number().positive().default(6e4),
13283
+ connectionLivenessTimeout: external_exports.number().positive().default(2500),
13284
+ connectionLivenessInterval: external_exports.number().positive().default(5e3),
13285
+ /** @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. */
13286
+ noSleep: external_exports.boolean().default(false),
13287
+ sleepTimeout: external_exports.number().positive().default(3e4),
13288
+ maxQueueSize: external_exports.number().positive().default(1e3),
13289
+ /** Maximum pending one-shot and recurring schedules. */
13290
+ maxSchedules: external_exports.number().int().nonnegative().default(1e3),
13291
+ maxQueueMessageSize: external_exports.number().positive().default(64 * 1024),
13292
+ /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
13293
+ preloadMaxWorkflowBytes: external_exports.number().nonnegative().optional(),
13294
+ /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
13295
+ preloadMaxConnectionsBytes: external_exports.number().nonnegative().optional()
13296
+ }).strict();
13297
+ var InstanceActorOptionsSchema = InstanceActorOptionsBaseSchema.prefault(() => ({}));
13298
+ var ActorOptionsSchema = GlobalActorOptionsBaseSchema.extend(
13299
+ InstanceActorOptionsBaseSchema.shape
13300
+ ).strict().prefault(() => ({}));
13301
+ var ActorConfigSchema = external_exports.object({
13302
+ onCreate: zFunction().optional(),
13303
+ onDestroy: zFunction().optional(),
13304
+ onMigrate: zFunction().optional(),
13305
+ onWake: zFunction().optional(),
13306
+ onSleep: zFunction().optional(),
13307
+ run: zRunHandler,
13308
+ onStateChange: zFunction().optional(),
13309
+ onBeforeConnect: zFunction().optional(),
13310
+ onConnect: zFunction().optional(),
13311
+ onDisconnect: zFunction().optional(),
13312
+ onBeforeActionResponse: zFunction().optional(),
13313
+ onRequest: zFunction().optional(),
13314
+ onWebSocket: zFunction().optional(),
13315
+ actions: zActionTree.default(() => ({})),
13316
+ actionInputSchemas: external_exports.record(external_exports.string(), external_exports.any()).optional(),
13317
+ connParamsSchema: external_exports.any().optional(),
13318
+ events: external_exports.record(external_exports.string(), external_exports.any()).optional(),
13319
+ queues: external_exports.record(external_exports.string(), external_exports.any()).optional(),
13320
+ state: external_exports.any().optional(),
13321
+ createState: zFunction().optional(),
13322
+ connState: external_exports.any().optional(),
13323
+ createConnState: zFunction().optional(),
13324
+ vars: external_exports.any().optional(),
13325
+ db: external_exports.any().optional(),
13326
+ createVars: zFunction().optional(),
13327
+ options: ActorOptionsSchema,
13328
+ inspector: ActorInspectorConfigSchema.optional()
13329
+ }).strict().refine(
13330
+ (data) => !(data.state !== void 0 && data.createState !== void 0),
13331
+ {
13332
+ message: "Cannot define both 'state' and 'createState'",
13333
+ path: ["state"]
13334
+ }
13335
+ ).refine(
13336
+ (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
13337
+ {
13338
+ message: "Cannot define both 'connState' and 'createConnState'",
13339
+ path: ["connState"]
13340
+ }
13341
+ ).refine(
13342
+ (data) => !(data.vars !== void 0 && data.createVars !== void 0),
13343
+ {
13344
+ message: "Cannot define both 'vars' and 'createVars'",
13345
+ path: ["vars"]
13346
+ }
13347
+ );
13348
+ var DocActorOptionsSchema = external_exports.object({
13349
+ name: external_exports.string().optional().describe("Display name for the actor in the Inspector UI."),
13350
+ icon: external_exports.string().optional().describe(
13351
+ "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
13352
+ ),
13353
+ enableActorRuntimeSocket: external_exports.boolean().optional().describe(
13354
+ "Enables the experimental Actor Runtime Socket for this actor. Default: false"
13355
+ ),
13356
+ createVarsTimeout: external_exports.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
13357
+ createConnStateTimeout: external_exports.number().optional().describe(
13358
+ "Timeout in ms for createConnState handler. Default: 5000"
13359
+ ),
13360
+ onMigrateTimeout: external_exports.number().optional().describe("Timeout in ms for onMigrate handler. Default: 30000"),
13361
+ onBeforeConnectTimeout: external_exports.number().optional().describe(
13362
+ "Timeout in ms for onBeforeConnect handler. Default: 5000"
13363
+ ),
13364
+ onConnectTimeout: external_exports.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
13365
+ sleepGracePeriod: external_exports.number().optional().describe(
13366
+ `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}.`
13367
+ ),
13368
+ onDestroyTimeout: external_exports.number().optional().describe(
13369
+ "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
13370
+ ),
13371
+ waitUntilTimeout: external_exports.number().optional().describe(
13372
+ "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
13373
+ ),
13374
+ stateSaveInterval: external_exports.number().optional().describe(
13375
+ "Interval in ms between automatic state saves. Default: 1000"
13376
+ ),
13377
+ actionTimeout: external_exports.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
13378
+ connectionLivenessTimeout: external_exports.number().optional().describe(
13379
+ "Timeout in ms for connection liveness checks. Default: 2500"
13380
+ ),
13381
+ connectionLivenessInterval: external_exports.number().optional().describe(
13382
+ "Interval in ms between connection liveness checks. Default: 5000"
13383
+ ),
13384
+ noSleep: external_exports.boolean().optional().describe(
13385
+ "Deprecated. If true, the actor will never sleep. Use c.keepAwake(promise) to scope keep-awake to a specific operation instead. Default: false"
13386
+ ),
13387
+ sleepTimeout: external_exports.number().optional().describe(
13388
+ "Time in ms of inactivity before the actor sleeps. Default: 30000"
13389
+ ),
13390
+ maxQueueSize: external_exports.number().optional().describe(
13391
+ "Maximum number of queue messages before rejecting new messages. Default: 1000"
13392
+ ),
13393
+ maxSchedules: external_exports.number().int().nonnegative().optional().describe(
13394
+ "Maximum pending one-shot and recurring schedules before rejecting new schedules. Default: 1000"
13395
+ ),
13396
+ maxQueueMessageSize: external_exports.number().optional().describe(
13397
+ "Maximum size of each queue message in bytes. Default: 65536"
13398
+ ),
13399
+ canHibernateWebSocket: external_exports.boolean().optional().describe(
13400
+ "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
13401
+ )
13402
+ }).describe("Actor options for timeouts and behavior configuration.");
13403
+ var DocActorConfigSchema = external_exports.object({
13404
+ state: external_exports.unknown().optional().describe(
13405
+ "Initial state value for the actor. Cannot be used with createState."
13406
+ ),
13407
+ createState: external_exports.unknown().optional().describe(
13408
+ "Function to create initial state. Receives context and input. Cannot be used with state."
13409
+ ),
13410
+ connState: external_exports.unknown().optional().describe(
13411
+ "Initial connection state value. Cannot be used with createConnState."
13412
+ ),
13413
+ createConnState: external_exports.unknown().optional().describe(
13414
+ "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."
13415
+ ),
13416
+ vars: external_exports.unknown().optional().describe(
13417
+ "Initial ephemeral variables value. Cannot be used with createVars."
13418
+ ),
13419
+ createVars: external_exports.unknown().optional().describe(
13420
+ "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
13421
+ ),
13422
+ db: external_exports.unknown().optional().describe("Database provider instance for the actor."),
13423
+ onCreate: external_exports.unknown().optional().describe(
13424
+ "Called when the actor is first initialized. Use to initialize state."
13425
+ ),
13426
+ onDestroy: external_exports.unknown().optional().describe("Called when the actor is destroyed."),
13427
+ onMigrate: external_exports.unknown().optional().describe(
13428
+ "Called on every actor start after persisted state loads and before onWake. Use for repeatable schema migrations."
13429
+ ),
13430
+ onWake: external_exports.unknown().optional().describe(
13431
+ "Called when the actor wakes up and is ready to receive connections and actions."
13432
+ ),
13433
+ onSleep: external_exports.unknown().optional().describe(
13434
+ "Called when the actor is stopping or sleeping. Use to clean up resources."
13435
+ ),
13436
+ run: external_exports.unknown().optional().describe(
13437
+ "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."
13438
+ ),
13439
+ onStateChange: external_exports.unknown().optional().describe(
13440
+ "Called when the actor's state changes. State changes within this hook won't trigger recursion."
13441
+ ),
13442
+ onBeforeConnect: external_exports.unknown().optional().describe(
13443
+ "Called before a client connects. Throw an error to reject the connection. The pending connection is not visible in c.conns while this runs."
13444
+ ),
13445
+ onConnect: external_exports.unknown().optional().describe(
13446
+ "Called when a client successfully connects. The connection is visible in c.conns before this runs."
13447
+ ),
13448
+ onDisconnect: external_exports.unknown().optional().describe("Called when a client disconnects."),
13449
+ onBeforeActionResponse: external_exports.unknown().optional().describe(
13450
+ "Called before sending an action response. Use to transform output."
13451
+ ),
13452
+ onRequest: external_exports.unknown().optional().describe(
13453
+ "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
13454
+ ),
13455
+ onWebSocket: external_exports.unknown().optional().describe(
13456
+ "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
13457
+ ),
13458
+ actions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
13459
+ "Tree of action names or nested groups to handler functions. Nested paths use dot-separated low-level action names. Defaults to an empty object."
13460
+ ),
13461
+ actionInputSchemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
13462
+ "Optional schemas for validating action argument tuples in native runtimes. May mirror nested action groups or use dot-separated low-level action names."
13463
+ ),
13464
+ connParamsSchema: external_exports.unknown().optional().describe(
13465
+ "Optional schema for validating connection params in native runtimes."
13466
+ ),
13467
+ events: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of event names to schemas."),
13468
+ queues: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of queue names to schemas."),
13469
+ options: DocActorOptionsSchema.optional()
13470
+ }).describe("Actor configuration passed to the actor() function.");
13471
+
13472
+ // ../rivetkit/dist/tsup/chunk-OUQUIBVW.js
13473
+ var INTERNAL_ERROR_CODE = "internal_error";
13474
+ var INTERNAL_ERROR_DESCRIPTION = "An internal error occurred";
13475
+ var USER_ERROR_CODE = "user_error";
13476
+ var BRIDGE_RIVET_ERROR_PREFIX = "__RIVET_ERROR_JSON__:";
13477
+ function looksLikeRivetErrorOptions(value) {
13478
+ return typeof value === "object" && value !== null && ("public" in value || "metadata" in value || "rayId" in value || "statusCode" in value || "actor" in value || "cause" in value);
13479
+ }
13480
+ function isTypedErrorTag(value) {
13481
+ return value === "ActorError" || value === "RivetError";
13482
+ }
13483
+ function errorMessage(error46, fallback = String(error46)) {
13484
+ if (error46 && typeof error46 === "object" && "message" in error46 && typeof error46.message === "string") {
13485
+ return error46.message;
13486
+ }
13487
+ return fallback;
13488
+ }
13489
+ function isRivetErrorLike(error46) {
13490
+ return typeof error46 === "object" && error46 !== null && "group" in error46 && typeof error46.group === "string" && "code" in error46 && typeof error46.code === "string" && "message" in error46 && typeof error46.message === "string" && (!("rayId" in error46) || error46.rayId === void 0 || typeof error46.rayId === "string") && (!("__type" in error46) || isTypedErrorTag(error46.__type));
13491
+ }
13492
+ function isActorAbortedError(error46) {
13493
+ return isRivetErrorLike(error46) && error46.group === "actor" && error46.code === "aborted";
13494
+ }
13495
+ function isActorSpecifier(value) {
13496
+ return typeof value === "object" && value !== null && "actorId" in value && typeof value.actorId === "string" && "generation" in value && typeof value.generation === "number" && (!("key" in value) || value.key === void 0 || typeof value.key === "string");
13497
+ }
13498
+ var RivetError = class extends Error {
13499
+ __type = "RivetError";
13500
+ public;
13501
+ metadata;
13502
+ rayId;
13503
+ statusCode;
13504
+ actor;
13505
+ group;
13506
+ code;
13507
+ static isRivetError(error46) {
13508
+ return isRivetErrorLike(error46);
13509
+ }
13510
+ static isActorError(error46) {
13511
+ return isRivetErrorLike(error46);
13512
+ }
13513
+ constructor(group, code, message, options) {
13514
+ const normalized = looksLikeRivetErrorOptions(options) ? options : { metadata: options };
13515
+ super(message, { cause: normalized.cause });
13516
+ this.name = "RivetError";
13517
+ this.group = group;
13518
+ this.code = code;
13519
+ this.public = normalized.public ?? false;
13520
+ this.metadata = normalized.metadata;
13521
+ this.rayId = normalized.rayId ?? void 0;
13522
+ this.statusCode = normalized.statusCode ?? (this.public ? 400 : 500);
13523
+ this.actor = normalized.actor;
13524
+ }
13525
+ toString() {
13526
+ return this.message;
13527
+ }
13528
+ };
13529
+ var UserError = class extends RivetError {
13530
+ constructor(message, options) {
13531
+ super("user", (options == null ? void 0 : options.code) ?? USER_ERROR_CODE, message, {
13532
+ public: true,
13533
+ metadata: options == null ? void 0 : options.metadata,
13534
+ cause: options == null ? void 0 : options.cause
13535
+ });
13536
+ }
13537
+ };
13538
+ function toRivetError(error46, fallback) {
13539
+ if (typeof error46 === "string") {
13540
+ const bridged = decodeBridgeRivetError(error46);
13541
+ if (bridged) {
13542
+ return bridged;
13543
+ }
13544
+ }
13545
+ if (error46 instanceof Error) {
13546
+ const bridged = decodeBridgeRivetError(error46.message);
13547
+ if (bridged) {
13548
+ return bridged;
13549
+ }
13550
+ }
13551
+ if (isRivetErrorLike(error46)) {
13552
+ return new RivetError(error46.group, error46.code, error46.message, {
13553
+ public: error46.public,
13554
+ statusCode: error46.statusCode,
13555
+ metadata: error46.metadata,
13556
+ rayId: error46.rayId,
13557
+ actor: error46.actor,
13558
+ cause: error46 instanceof Error ? error46.cause : void 0
13559
+ });
13560
+ }
13561
+ return new RivetError(
13562
+ (fallback == null ? void 0 : fallback.group) ?? "actor",
13563
+ (fallback == null ? void 0 : fallback.code) ?? INTERNAL_ERROR_CODE,
13564
+ errorMessage(error46, (fallback == null ? void 0 : fallback.message) ?? "Unknown error"),
13565
+ {
13566
+ public: fallback == null ? void 0 : fallback.public,
13567
+ statusCode: fallback == null ? void 0 : fallback.statusCode,
13568
+ metadata: fallback == null ? void 0 : fallback.metadata,
13569
+ rayId: fallback == null ? void 0 : fallback.rayId,
13570
+ actor: fallback == null ? void 0 : fallback.actor,
13571
+ cause: error46 instanceof Error ? error46 : void 0
13572
+ }
13573
+ );
13574
+ }
13575
+ function encodeBridgeRivetError(error46) {
13576
+ return `${BRIDGE_RIVET_ERROR_PREFIX}${JSON.stringify({
13577
+ group: error46.group,
13578
+ code: error46.code,
13579
+ message: error46.message,
13580
+ metadata: error46.metadata,
13581
+ rayId: error46.rayId,
13582
+ public: error46.public,
13583
+ statusCode: error46.statusCode,
13584
+ actor: error46.actor
13585
+ })}`;
13586
+ }
13587
+ function decodeBridgeRivetErrorPayload(value) {
13588
+ if (!value.startsWith(BRIDGE_RIVET_ERROR_PREFIX)) {
13589
+ return void 0;
13590
+ }
13591
+ try {
13592
+ const raw = JSON.parse(
13593
+ value.slice(BRIDGE_RIVET_ERROR_PREFIX.length)
13594
+ );
13595
+ const payload = {
13596
+ ...raw,
13597
+ rayId: raw.rayId ?? void 0
13598
+ };
13599
+ if (!isRivetErrorLike(payload)) {
13600
+ return void 0;
13601
+ }
13602
+ if (payload.actor !== void 0 && payload.actor !== null && !isActorSpecifier(payload.actor)) {
13603
+ return void 0;
13604
+ }
13605
+ return payload;
13606
+ } catch {
13607
+ return void 0;
13608
+ }
13609
+ }
13610
+ function decodeBridgeRivetError(value) {
13611
+ const payload = decodeBridgeRivetErrorPayload(value);
13612
+ if (!payload) {
13613
+ return void 0;
13614
+ }
13615
+ return new RivetError(payload.group, payload.code, payload.message, {
13616
+ metadata: payload.metadata,
13617
+ rayId: payload.rayId,
13618
+ public: payload.public,
13619
+ statusCode: payload.statusCode,
13620
+ actor: payload.actor ?? void 0
13621
+ });
13622
+ }
13623
+ function invalidRequest(error46) {
13624
+ return new RivetError(
13625
+ "request",
13626
+ "invalid",
13627
+ `Invalid request: ${errorMessage(error46, String(error46))}`,
13628
+ {
13629
+ public: true,
13630
+ cause: error46 instanceof Error ? error46 : void 0
13631
+ }
13632
+ );
13633
+ }
13634
+ function actorNotFound(identifier) {
13635
+ return new RivetError(
13636
+ "actor",
13637
+ "not_found",
13638
+ identifier ? `Actor not found: ${identifier} (https://www.rivet.dev/docs/clients/javascript)` : "Actor not found (https://www.rivet.dev/docs/clients/javascript)",
13639
+ { public: true }
13640
+ );
13641
+ }
13642
+ function forbiddenError() {
13643
+ return new RivetError("auth", "forbidden", "Forbidden", {
13644
+ public: true,
13645
+ statusCode: 403
13646
+ });
13647
+ }
13648
+ function unsupportedFeature(feature) {
13649
+ return new RivetError(
13650
+ "feature",
13651
+ "unsupported",
13652
+ `Unsupported feature: ${feature}`
13653
+ );
13654
+ }
13655
+
13656
+ // ../rivetkit/dist/tsup/chunk-5NBLGMI2.js
13657
+ var import_pino = require("pino");
13658
+ var cbor = __toESM(require("cbor-x"), 1);
13659
+ var import_invariant = __toESM(require_invariant(), 1);
13660
+ var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
13661
+ var getRivetEndpoint = () => getEnvUniversal("RIVET_ENDPOINT");
13662
+ var getRivetToken = () => getEnvUniversal("RIVET_TOKEN");
13663
+ var getRivetNamespace = () => getEnvUniversal("RIVET_NAMESPACE");
13664
+ var getRivetPool = () => getEnvUniversal("RIVET_POOL");
13665
+ var getRivetTotalSlots = () => {
13666
+ const value = getEnvUniversal("RIVET_TOTAL_SLOTS");
13667
+ return value !== void 0 ? parseInt(value, 10) : void 0;
13668
+ };
13669
+ var getRivetRunEngine = () => getEnvUniversal("RIVET_RUN_ENGINE") === "1";
13670
+ var getRivetRunEngineHost = () => getEnvUniversal("RIVET_RUN_ENGINE_HOST");
13671
+ var getRivetRunEnginePort = () => {
13672
+ const value = getEnvUniversal("RIVET_RUN_ENGINE_PORT");
13673
+ return value !== void 0 ? parseInt(value, 10) : void 0;
13674
+ };
13675
+ var getRivetRunEngineVersion = () => getEnvUniversal("RIVET_RUN_ENGINE_VERSION");
13676
+ var getRivetRunServices = () => {
13677
+ const value = getEnvUniversal("RIVET_RUN_SERVICES");
13678
+ return value === void 0 ? void 0 : value === "1";
13679
+ };
13680
+ var getRivetEnvoyVersion = () => {
13681
+ const value = getEnvUniversal("RIVET_ENVOY_VERSION");
13682
+ return value !== void 0 ? parseInt(value, 10) : void 0;
13683
+ };
13684
+ var getRivetPublicEndpoint = () => getEnvUniversal("RIVET_PUBLIC_ENDPOINT");
13685
+ var getRivetPublicToken = () => getEnvUniversal("RIVET_PUBLIC_TOKEN");
13686
+ var getRivetkitRuntime = () => getEnvUniversal("RIVETKIT_RUNTIME");
13687
+ var getRivetkitRuntimeMode = () => {
13688
+ const value = getEnvUniversal("RIVETKIT_RUNTIME_MODE");
13689
+ if (value === void 0) return "envoy";
13690
+ if (value === "envoy" || value === "serverless") return value;
13691
+ throw new Error(
13692
+ `RIVETKIT_RUNTIME_MODE env var must be "envoy" or "serverless"; got "${value}"`
13693
+ );
13694
+ };
13695
+ var getRivetkitPublicDir = () => {
13696
+ const value = getEnvUniversal("RIVETKIT_PUBLIC_DIR");
13697
+ return value === void 0 || value === "" ? void 0 : value;
13698
+ };
13699
+ function parsePortEnv(raw) {
13700
+ if (raw === void 0 || raw === "") return void 0;
13701
+ const parsed = Number.parseInt(raw, 10);
13702
+ if (!Number.isFinite(parsed) || parsed < 1 || parsed > 65535 || String(parsed) !== raw.trim()) {
13703
+ throw new Error(
13704
+ `RIVET_PORT env var must be an integer between 1 and 65535; got "${raw}"`
13705
+ );
13706
+ }
13707
+ return parsed;
13708
+ }
13709
+ var getLogLevel = () => getEnvUniversal("RIVET_LOG_LEVEL") ?? getEnvUniversal("LOG_LEVEL");
13710
+ var getLogTarget = () => getEnvUniversal("RIVET_LOG_TARGET") === "1";
13711
+ var getLogTimestamp = () => getEnvUniversal("RIVET_LOG_TIMESTAMP") === "1";
13712
+ var getLogMessage = () => getEnvUniversal("RIVET_LOG_MESSAGE") === "1";
13713
+ var getLogErrorStack = () => getEnvUniversal("RIVET_LOG_ERROR_STACK") === "1";
13714
+ var getNodeEnv = () => getEnvUniversal("NODE_ENV");
13715
+ var getNextPhase = () => getEnvUniversal("NEXT_PHASE");
13716
+ var isDev = () => getNodeEnv() !== "production";
13717
+ function assertUnreachable(x) {
13718
+ throw new Error(`Unreachable case: ${x}`);
13719
+ }
13720
+ function isCanonicalStructuredRivetError(error46) {
13721
+ return error46 instanceof RivetError || typeof error46 === "object" && error46 !== null && "__type" in error46 && error46.__type === "RivetError" && "group" in error46 && typeof error46.group === "string" && "code" in error46 && typeof error46.code === "string" && "message" in error46 && typeof error46.message === "string";
13722
+ }
13723
+ function deconstructError(error46, exposeInternalError = false) {
13724
+ let statusCode;
13725
+ let public_;
13726
+ let group;
13727
+ let code;
13728
+ let message;
13729
+ let metadata;
13730
+ let rayId;
13731
+ let actor2;
13732
+ if (isCanonicalStructuredRivetError(error46)) {
13733
+ statusCode = typeof error46.statusCode === "number" ? error46.statusCode : error46.public ? 400 : 500;
13734
+ public_ = error46.public ?? false;
13735
+ group = error46.group;
13736
+ code = error46.code;
13737
+ message = error46.message;
13738
+ metadata = error46.metadata;
13739
+ rayId = error46.rayId;
13740
+ actor2 = error46.actor;
13741
+ } else if (RivetError.isActorError(error46) && error46.public) {
13742
+ statusCode = "statusCode" in error46 && error46.statusCode ? error46.statusCode : 400;
13743
+ public_ = true;
13744
+ group = error46.group;
13745
+ code = error46.code;
13746
+ message = getErrorMessage(error46);
13747
+ metadata = error46.metadata;
13748
+ rayId = error46.rayId;
13749
+ actor2 = error46.actor;
13750
+ } else if (exposeInternalError) {
13751
+ if (RivetError.isActorError(error46)) {
13752
+ statusCode = 500;
13753
+ public_ = false;
13754
+ group = error46.group;
13755
+ code = error46.code;
13756
+ message = getErrorMessage(error46);
13757
+ metadata = error46.metadata;
13758
+ rayId = error46.rayId;
13759
+ actor2 = error46.actor;
13760
+ } else {
13761
+ statusCode = 500;
13762
+ public_ = false;
13763
+ group = "rivetkit";
13764
+ code = INTERNAL_ERROR_CODE;
13765
+ message = getErrorMessage(error46);
13766
+ }
13767
+ } else {
13768
+ statusCode = 500;
13769
+ public_ = false;
13770
+ group = "rivetkit";
13771
+ code = INTERNAL_ERROR_CODE;
13772
+ message = INTERNAL_ERROR_DESCRIPTION;
13773
+ if (RivetError.isActorError(error46)) {
13774
+ actor2 = error46.actor;
13775
+ }
13776
+ metadata = {
13777
+ //url: `https://dashboard.rivet.dev/projects/${actorMetadata.project.slug}/environments/${actorMetadata.environment.slug}/actors?actorId=${actorMetadata.actor.id}`,
13778
+ };
13779
+ }
13780
+ return {
13781
+ __type: "ActorError",
13782
+ statusCode,
13783
+ public: public_,
13784
+ group,
13785
+ code,
13786
+ message,
13787
+ metadata,
13788
+ rayId,
13789
+ actor: actor2
13790
+ };
13791
+ }
13792
+ function stringifyError(error46) {
13793
+ if (error46 instanceof Error) {
13794
+ if (typeof process !== "undefined" && getLogErrorStack()) {
13795
+ let stack;
13796
+ try {
13797
+ stack = error46.stack;
13798
+ } catch {
13799
+ stack = void 0;
13800
+ }
13801
+ return `${error46.name}: ${error46.message}${stack ? `
13802
+ ${stack}` : ""}`;
13803
+ } else {
13804
+ return `${error46.name}: ${error46.message}`;
13805
+ }
13806
+ } else if (typeof error46 === "string") {
13807
+ return error46;
13808
+ } else if (typeof error46 === "object" && error46 !== null) {
13809
+ try {
13810
+ return `${JSON.stringify(error46)}`;
13811
+ } catch {
13812
+ return "[cannot stringify error]";
13813
+ }
13814
+ } else {
13815
+ return `Unknown error: ${getErrorMessage(error46)}`;
13816
+ }
13817
+ }
13818
+ function getErrorMessage(err) {
13819
+ if (err && typeof err === "object" && "message" in err && typeof err.message === "string") {
13820
+ return err.message;
13821
+ } else {
13822
+ return String(err);
13823
+ }
13824
+ }
13825
+ function noopNext() {
13826
+ return async () => {
13827
+ };
13828
+ }
13829
+ var package_default = {
13830
+ name: "rivetkit",
13831
+ version: "0.0.0-main.78336a1",
13832
+ description: "Lightweight libraries for building stateful actors on edge platforms",
13833
+ license: "Apache-2.0",
13834
+ keywords: [
13835
+ "rivetkit",
13836
+ "stateful",
13837
+ "serverless",
13838
+ "actors",
13839
+ "agents",
13840
+ "realtime",
13841
+ "websocket",
13842
+ "actors",
13843
+ "framework"
13844
+ ],
13845
+ files: [
13846
+ "dist",
13847
+ "schemas",
13848
+ "src",
13849
+ "package.json"
13850
+ ],
13851
+ type: "module",
13852
+ exports: {
13853
+ ".": {
13854
+ import: {
13855
+ types: "./dist/tsup/mod.d.ts",
13856
+ default: "./dist/tsup/mod.js"
13857
+ },
13858
+ require: {
13859
+ types: "./dist/tsup/mod.d.cts",
13860
+ default: "./dist/tsup/mod.cjs"
13861
+ }
13862
+ },
13863
+ "./workflow": {
13864
+ import: {
13865
+ types: "./dist/tsup/workflow/mod.d.ts",
13866
+ default: "./dist/tsup/workflow/mod.js"
13867
+ },
13868
+ require: {
13869
+ types: "./dist/tsup/workflow/mod.d.cts",
13870
+ default: "./dist/tsup/workflow/mod.cjs"
13871
+ }
13872
+ },
13873
+ "./test": {
13874
+ import: {
13875
+ types: "./dist/tsup/test/mod.d.ts",
13876
+ default: "./dist/tsup/test/mod.js"
13877
+ },
13878
+ require: {
13879
+ types: "./dist/tsup/test/mod.d.cts",
13880
+ default: "./dist/tsup/test/mod.cjs"
13881
+ }
13882
+ },
13883
+ "./db": {
13884
+ import: {
13885
+ types: "./dist/tsup/db/mod.d.ts",
13886
+ default: "./dist/tsup/db/mod.js"
13887
+ },
13888
+ require: {
13889
+ types: "./dist/tsup/db/mod.d.cts",
13890
+ default: "./dist/tsup/db/mod.cjs"
13891
+ }
13892
+ },
13893
+ "./db/drizzle": {
13894
+ import: {
13895
+ types: "./dist/tsup/db/drizzle.d.ts",
13896
+ default: "./dist/tsup/db/drizzle.js"
13897
+ },
13898
+ require: {
13899
+ types: "./dist/tsup/db/drizzle.d.cts",
13900
+ default: "./dist/tsup/db/drizzle.cjs"
13901
+ }
13902
+ },
13903
+ "./unstable/migrations": {
13904
+ import: {
13905
+ types: "./dist/tsup/unstable/migrations.d.ts",
13906
+ default: "./dist/tsup/unstable/migrations.js"
13907
+ },
13908
+ require: {
13909
+ types: "./dist/tsup/unstable/migrations.d.cts",
13910
+ default: "./dist/tsup/unstable/migrations.cjs"
13911
+ }
13912
+ },
13913
+ "./dynamic": {
13914
+ import: {
13915
+ types: "./dist/tsup/dynamic/mod.d.ts",
13916
+ default: "./dist/tsup/dynamic/mod.js"
13917
+ },
13918
+ require: {
13919
+ types: "./dist/tsup/dynamic/mod.d.cts",
13920
+ default: "./dist/tsup/dynamic/mod.cjs"
13921
+ }
13922
+ },
13923
+ "./client": {
13924
+ import: {
13925
+ browser: {
13926
+ types: "./dist/browser/client.d.ts",
13927
+ default: "./dist/browser/client.js"
13928
+ },
13929
+ types: "./dist/tsup/client/mod.d.ts",
13930
+ default: "./dist/tsup/client/mod.js"
13931
+ },
13932
+ require: {
13933
+ types: "./dist/tsup/client/mod.d.cts",
13934
+ default: "./dist/tsup/client/mod.cjs"
13935
+ }
13936
+ },
13937
+ "./log": {
13938
+ import: {
13473
13939
  types: "./dist/tsup/common/log.d.ts",
13474
13940
  default: "./dist/tsup/common/log.js"
13475
13941
  },
@@ -13572,6 +14038,7 @@ var package_default = {
13572
14038
  dependencies: {
13573
14039
  "@hono/zod-openapi": "^1.1.5",
13574
14040
  "@rivet-dev/agent-os-core": "^0.1.1",
14041
+ "@rivet-dev/services": "^0.1.5",
13575
14042
  "@rivetkit/bare-ts": "^0.6.2",
13576
14043
  "@rivetkit/engine-cli": "workspace:*",
13577
14044
  "@rivetkit/engine-envoy-protocol": "workspace:*",
@@ -13582,7 +14049,7 @@ var package_default = {
13582
14049
  "@rivetkit/virtual-websocket": "workspace:*",
13583
14050
  "@rivetkit/workflow-engine": "workspace:*",
13584
14051
  "cbor-x": "^1.6.0",
13585
- "drizzle-orm": "^0.44.2",
14052
+ "drizzle-orm": "catalog:",
13586
14053
  hono: "^4.7.0",
13587
14054
  invariant: "^2.2.4",
13588
14055
  "p-retry": "^6.2.1",
@@ -14665,7 +15132,7 @@ function Config({ initialBufferLength = 1024, maxBufferLength = 1024 * 1024 * 32
14665
15132
  };
14666
15133
  }
14667
15134
 
14668
- // ../rivetkit/dist/tsup/chunk-6W2UIH3X.js
15135
+ // ../rivetkit/dist/tsup/chunk-XCSZTG4H.js
14669
15136
  var config2 = /* @__PURE__ */ Config({});
14670
15137
  function readWorkflowCbor(bc) {
14671
15138
  return readData(bc);
@@ -14777,655 +15244,191 @@ function readWorkflowStepEntry(bc) {
14777
15244
  }
14778
15245
  function readWorkflowLoopEntry(bc) {
14779
15246
  return {
14780
- state: readWorkflowCbor(bc),
14781
- iteration: readU32(bc),
14782
- output: read0(bc)
14783
- };
14784
- }
14785
- function readWorkflowSleepEntry(bc) {
14786
- return {
14787
- deadline: readU64(bc),
14788
- state: readWorkflowSleepState(bc)
14789
- };
14790
- }
14791
- function readWorkflowMessageEntry(bc) {
14792
- return {
14793
- name: readString(bc),
14794
- messageData: readWorkflowCbor(bc)
14795
- };
14796
- }
14797
- function readWorkflowRollbackCheckpointEntry(bc) {
14798
- return {
14799
- name: readString(bc)
14800
- };
14801
- }
14802
- function readWorkflowBranchStatus(bc) {
14803
- return {
14804
- status: readWorkflowBranchStatusType(bc),
14805
- output: read0(bc),
14806
- error: read1(bc)
14807
- };
14808
- }
14809
- function read2(bc) {
14810
- const len = readUintSafe(bc);
14811
- const result = /* @__PURE__ */ new Map();
14812
- for (let i = 0; i < len; i++) {
14813
- const offset = bc.offset;
14814
- const key = readString(bc);
14815
- if (result.has(key)) {
14816
- bc.offset = offset;
14817
- throw new BareError(offset, "duplicated key");
14818
- }
14819
- result.set(key, readWorkflowBranchStatus(bc));
14820
- }
14821
- return result;
14822
- }
14823
- function readWorkflowJoinEntry(bc) {
14824
- return {
14825
- branches: read2(bc)
14826
- };
14827
- }
14828
- function readWorkflowRaceEntry(bc) {
14829
- return {
14830
- winner: read1(bc),
14831
- branches: read2(bc)
14832
- };
14833
- }
14834
- function readWorkflowRemovedEntry(bc) {
14835
- return {
14836
- originalType: readString(bc),
14837
- originalName: read1(bc)
14838
- };
14839
- }
14840
- function readWorkflowVersionCheckEntry(bc) {
14841
- return {
14842
- resolved: readU32(bc),
14843
- latest: readU32(bc)
14844
- };
14845
- }
14846
- function readWorkflowEntryKind(bc) {
14847
- const offset = bc.offset;
14848
- const tag = readU8(bc);
14849
- switch (tag) {
14850
- case 0:
14851
- return { tag: "WorkflowStepEntry", val: readWorkflowStepEntry(bc) };
14852
- case 1:
14853
- return { tag: "WorkflowLoopEntry", val: readWorkflowLoopEntry(bc) };
14854
- case 2:
14855
- return {
14856
- tag: "WorkflowSleepEntry",
14857
- val: readWorkflowSleepEntry(bc)
14858
- };
14859
- case 3:
14860
- return {
14861
- tag: "WorkflowMessageEntry",
14862
- val: readWorkflowMessageEntry(bc)
14863
- };
14864
- case 4:
14865
- return {
14866
- tag: "WorkflowRollbackCheckpointEntry",
14867
- val: readWorkflowRollbackCheckpointEntry(bc)
14868
- };
14869
- case 5:
14870
- return { tag: "WorkflowJoinEntry", val: readWorkflowJoinEntry(bc) };
14871
- case 6:
14872
- return { tag: "WorkflowRaceEntry", val: readWorkflowRaceEntry(bc) };
14873
- case 7:
14874
- return {
14875
- tag: "WorkflowRemovedEntry",
14876
- val: readWorkflowRemovedEntry(bc)
14877
- };
14878
- case 8:
14879
- return {
14880
- tag: "WorkflowVersionCheckEntry",
14881
- val: readWorkflowVersionCheckEntry(bc)
14882
- };
14883
- default: {
14884
- bc.offset = offset;
14885
- throw new BareError(offset, "invalid tag");
14886
- }
14887
- }
14888
- }
14889
- function readWorkflowEntry(bc) {
14890
- return {
14891
- id: readString(bc),
14892
- location: readWorkflowLocation(bc),
14893
- kind: readWorkflowEntryKind(bc)
14894
- };
14895
- }
14896
- function read3(bc) {
14897
- return readBool(bc) ? readU64(bc) : null;
14898
- }
14899
- function readWorkflowEntryMetadata(bc) {
14900
- return {
14901
- status: readWorkflowEntryStatus(bc),
14902
- error: read1(bc),
14903
- attempts: readU32(bc),
14904
- lastAttemptAt: readU64(bc),
14905
- createdAt: readU64(bc),
14906
- completedAt: read3(bc),
14907
- rollbackCompletedAt: read3(bc),
14908
- rollbackError: read1(bc)
14909
- };
14910
- }
14911
- function read4(bc) {
14912
- const len = readUintSafe(bc);
14913
- if (len === 0) {
14914
- return [];
14915
- }
14916
- const result = [readString(bc)];
14917
- for (let i = 1; i < len; i++) {
14918
- result[i] = readString(bc);
14919
- }
14920
- return result;
14921
- }
14922
- function read5(bc) {
14923
- const len = readUintSafe(bc);
14924
- if (len === 0) {
14925
- return [];
14926
- }
14927
- const result = [readWorkflowEntry(bc)];
14928
- for (let i = 1; i < len; i++) {
14929
- result[i] = readWorkflowEntry(bc);
14930
- }
14931
- return result;
14932
- }
14933
- function read6(bc) {
14934
- const len = readUintSafe(bc);
14935
- const result = /* @__PURE__ */ new Map();
14936
- for (let i = 0; i < len; i++) {
14937
- const offset = bc.offset;
14938
- const key = readString(bc);
14939
- if (result.has(key)) {
14940
- bc.offset = offset;
14941
- throw new BareError(offset, "duplicated key");
14942
- }
14943
- result.set(key, readWorkflowEntryMetadata(bc));
14944
- }
14945
- return result;
14946
- }
14947
- function readWorkflowHistory(bc) {
14948
- return {
14949
- nameRegistry: read4(bc),
14950
- entries: read5(bc),
14951
- entryMetadata: read6(bc)
14952
- };
14953
- }
14954
- function decodeWorkflowHistory(bytes) {
14955
- const bc = new ByteCursor(bytes, config2);
14956
- const result = readWorkflowHistory(bc);
14957
- if (bc.offset < bc.view.byteLength) {
14958
- throw new BareError(bc.offset, "remaining bytes");
14959
- }
14960
- return result;
14961
- }
14962
- function decodeWorkflowHistoryTransport(data) {
14963
- return decodeWorkflowHistory(toUint8Array(data));
14964
- }
14965
-
14966
- // ../rivetkit/dist/tsup/chunk-6W5VGLFT.js
14967
- function flattenActionHandlers(actions) {
14968
- const flattened = /* @__PURE__ */ Object.create(null);
14969
- for (const { name, handler } of collectActionEntries(actions)) {
14970
- flattened[name] = handler;
14971
- }
14972
- return flattened;
14973
- }
14974
- function flattenActionInputSchemas(actions, schemas) {
14975
- if (schemas === void 0) return void 0;
14976
- if (!isRecord(schemas)) {
14977
- throw new TypeError("actionInputSchemas must be an object");
14978
- }
14979
- const flattened = /* @__PURE__ */ Object.create(null);
14980
- for (const { name, path: path2 } of collectActionEntries(actions)) {
14981
- const nestedSchema = lookupNestedSchema(schemas, path2);
14982
- const flatSchema = schemas[name];
14983
- if (nestedSchema !== void 0 && flatSchema !== void 0 && nestedSchema !== flatSchema) {
14984
- throw new TypeError(
14985
- `Action input schema \`${name}\` is defined by both a nested path and a dotted key`
14986
- );
14987
- }
14988
- const schema = nestedSchema ?? flatSchema;
14989
- if (schema !== void 0) {
14990
- flattened[name] = schema;
14991
- }
14992
- }
14993
- return flattened;
14994
- }
14995
- function collectActionEntries(actions) {
14996
- const entries = [];
14997
- const names = /* @__PURE__ */ new Set();
14998
- visitActionGroup(actions ?? {}, [], entries, names);
14999
- return entries;
15000
- }
15001
- function visitActionGroup(value, path2, entries, names) {
15002
- if (!isRecord(value)) {
15003
- throw new TypeError(
15004
- `${formatActionPath(path2)} must be an action handler or group`
15005
- );
15006
- }
15007
- for (const [segment, child] of Object.entries(value)) {
15008
- const childPath = [...path2, segment];
15009
- if (typeof child === "function") {
15010
- const name = childPath.join(".");
15011
- if (names.has(name)) {
15012
- throw new TypeError(
15013
- `Multiple action definitions flatten to \`${name}\``
15014
- );
15015
- }
15016
- names.add(name);
15017
- entries.push({
15018
- name,
15019
- path: childPath,
15020
- handler: child
15021
- });
15022
- } else {
15023
- visitActionGroup(child, childPath, entries, names);
15024
- }
15025
- }
15247
+ state: readWorkflowCbor(bc),
15248
+ iteration: readU32(bc),
15249
+ output: read0(bc)
15250
+ };
15026
15251
  }
15027
- function lookupNestedSchema(schemas, path2) {
15028
- let value = schemas;
15029
- for (const segment of path2) {
15030
- if (!isRecord(value) || !Object.hasOwn(value, segment)) {
15031
- return void 0;
15032
- }
15033
- value = value[segment];
15034
- }
15035
- return value;
15252
+ function readWorkflowSleepEntry(bc) {
15253
+ return {
15254
+ deadline: readU64(bc),
15255
+ state: readWorkflowSleepState(bc)
15256
+ };
15036
15257
  }
15037
- function isRecord(value) {
15038
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
15039
- return false;
15040
- }
15041
- const prototype = Object.getPrototypeOf(value);
15042
- return prototype === Object.prototype || prototype === null;
15258
+ function readWorkflowMessageEntry(bc) {
15259
+ return {
15260
+ name: readString(bc),
15261
+ messageData: readWorkflowCbor(bc)
15262
+ };
15043
15263
  }
15044
- function formatActionPath(path2) {
15045
- return path2.length === 0 ? "actions" : `Action \`${path2.join(".")}\``;
15264
+ function readWorkflowRollbackCheckpointEntry(bc) {
15265
+ return {
15266
+ name: readString(bc)
15267
+ };
15046
15268
  }
15047
- var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
15048
- var ACTOR_CONTEXT_INTERNAL_SYMBOL = /* @__PURE__ */ Symbol(
15049
- "rivetkit.actor_context_internal"
15050
- );
15051
- var RAW_STATE_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.raw_state");
15052
- var CONN_STATE_MANAGER_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.conn_state_manager");
15053
- var zFunction = () => external_exports.custom((val) => typeof val === "function");
15054
- var zActionTree = external_exports.custom((value) => {
15055
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
15056
- return false;
15057
- }
15058
- const prototype = Object.getPrototypeOf(value);
15059
- return prototype === Object.prototype || prototype === null;
15060
- }).superRefine((actions, ctx) => {
15061
- try {
15062
- flattenActionHandlers(actions);
15063
- } catch (error46) {
15064
- ctx.addIssue({
15065
- code: "custom",
15066
- message: error46 instanceof Error ? error46.message : "Invalid action definition"
15067
- });
15068
- }
15069
- });
15070
- var WorkflowInspectorConfigSchema = external_exports.object({
15071
- getHistory: zFunction(),
15072
- getState: zFunction().optional(),
15073
- onHistoryUpdated: zFunction().optional(),
15074
- replayFromStep: zFunction().optional()
15075
- });
15076
- var RunInspectorConfigSchema = external_exports.object({
15077
- workflow: WorkflowInspectorConfigSchema.optional()
15078
- }).optional();
15079
- var BUILTIN_INSPECTOR_TAB_IDS = [
15080
- "workflow",
15081
- "database",
15082
- "state",
15083
- "queue",
15084
- "schedules",
15085
- "connections",
15086
- "console"
15087
- ];
15088
- var BuiltinInspectorTabIdSchema = external_exports.enum(BUILTIN_INSPECTOR_TAB_IDS);
15089
- var CUSTOM_INSPECTOR_TAB_ID_RE = /^[A-Za-z0-9_-]+$/;
15090
- var CustomInspectorTabEntrySchema = external_exports.object({
15091
- id: external_exports.string().regex(
15092
- CUSTOM_INSPECTOR_TAB_ID_RE,
15093
- "inspector.tabs[].id must contain only letters, digits, underscore, or dash"
15094
- ),
15095
- label: external_exports.string().min(1),
15096
- source: external_exports.string().min(1),
15097
- /**
15098
- * Optional icon id. The dashboard maps strings to glyphs (see its
15099
- * icon registry); unknown ids fall back to a generic icon.
15100
- */
15101
- icon: external_exports.string().min(1).optional(),
15102
- hidden: external_exports.literal(false).optional()
15103
- }).strict();
15104
- var HideInspectorTabEntrySchema = external_exports.object({
15105
- id: BuiltinInspectorTabIdSchema,
15106
- hidden: external_exports.literal(true)
15107
- }).strict();
15108
- var InspectorTabEntrySchema = external_exports.union([
15109
- CustomInspectorTabEntrySchema,
15110
- HideInspectorTabEntrySchema
15111
- ]);
15112
- var ActorInspectorConfigSchema = external_exports.object({
15113
- tabs: external_exports.array(InspectorTabEntrySchema).default(() => [])
15114
- }).strict().refine(
15115
- (data) => {
15116
- const ids = data.tabs.map((t) => t.id);
15117
- return new Set(ids).size === ids.length;
15118
- },
15119
- { message: "Duplicate id in inspector.tabs", path: ["tabs"] }
15120
- ).refine(
15121
- (data) => {
15122
- const builtinSet = new Set(BUILTIN_INSPECTOR_TAB_IDS);
15123
- return data.tabs.every(
15124
- (t) => t.hidden === true || !builtinSet.has(t.id)
15125
- );
15126
- },
15127
- {
15128
- message: "Custom inspector tab id collides with a built-in (use hidden: true to hide a built-in)",
15129
- path: ["tabs"]
15130
- }
15131
- );
15132
- var RunConfigSchema = external_exports.object({
15133
- /** Display name for the actor in the Inspector UI. */
15134
- name: external_exports.string().optional(),
15135
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
15136
- icon: external_exports.string().optional(),
15137
- /** The run handler function. */
15138
- run: zFunction(),
15139
- /** Inspector integration for long-running run handlers. */
15140
- inspector: RunInspectorConfigSchema.optional()
15141
- });
15142
- var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("rivetkit.run_function_config");
15143
- function defineRunHandler(run, options) {
15144
- if (options.inspectorKind === void 0 !== (options.createInspector === void 0)) {
15145
- throw new TypeError(
15146
- "defineRunHandler requires inspectorKind and createInspector together"
15147
- );
15148
- }
15149
- Object.defineProperty(run, RUN_FUNCTION_CONFIG_SYMBOL, {
15150
- configurable: false,
15151
- enumerable: false,
15152
- writable: false,
15153
- value: {
15154
- name: options.name,
15155
- icon: options.icon,
15156
- inspectorKind: options.inspectorKind,
15157
- createInspector: options.createInspector
15269
+ function readWorkflowBranchStatus(bc) {
15270
+ return {
15271
+ status: readWorkflowBranchStatusType(bc),
15272
+ output: read0(bc),
15273
+ error: read1(bc)
15274
+ };
15275
+ }
15276
+ function read2(bc) {
15277
+ const len = readUintSafe(bc);
15278
+ const result = /* @__PURE__ */ new Map();
15279
+ for (let i = 0; i < len; i++) {
15280
+ const offset = bc.offset;
15281
+ const key = readString(bc);
15282
+ if (result.has(key)) {
15283
+ bc.offset = offset;
15284
+ throw new BareError(offset, "duplicated key");
15158
15285
  }
15159
- });
15160
- return run;
15286
+ result.set(key, readWorkflowBranchStatus(bc));
15287
+ }
15288
+ return result;
15161
15289
  }
15162
- function getRunInspectorKind(run) {
15163
- var _a2;
15164
- if (!run || typeof run !== "function") return void 0;
15165
- return (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.inspectorKind;
15290
+ function readWorkflowJoinEntry(bc) {
15291
+ return {
15292
+ branches: read2(bc)
15293
+ };
15166
15294
  }
15167
- function createRunInspector(run, context) {
15168
- var _a2, _b;
15169
- if (!run || typeof run !== "function") return void 0;
15170
- return (_b = (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.createInspector) == null ? void 0 : _b.call(_a2, context);
15295
+ function readWorkflowRaceEntry(bc) {
15296
+ return {
15297
+ winner: read1(bc),
15298
+ branches: read2(bc)
15299
+ };
15171
15300
  }
15172
- var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
15173
- function getRunFunction(run) {
15174
- if (!run) return void 0;
15175
- if (typeof run === "function") return run;
15176
- return run.run;
15301
+ function readWorkflowRemovedEntry(bc) {
15302
+ return {
15303
+ originalType: readString(bc),
15304
+ originalName: read1(bc)
15305
+ };
15177
15306
  }
15178
- function getRunMetadata(run) {
15179
- if (!run) return {};
15180
- if (typeof run === "function") {
15181
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15182
- if (!config3) return {};
15183
- return { name: config3.name, icon: config3.icon };
15184
- }
15185
- return { name: run.name, icon: run.icon };
15307
+ function readWorkflowVersionCheckEntry(bc) {
15308
+ return {
15309
+ resolved: readU32(bc),
15310
+ latest: readU32(bc)
15311
+ };
15186
15312
  }
15187
- function getRunInspectorConfig(run, actor2) {
15188
- if (!run) return void 0;
15189
- if (typeof run === "function") {
15190
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15191
- return (config3 == null ? void 0 : config3.inspectorFactory) ? config3.inspectorFactory(actor2) : config3 == null ? void 0 : config3.inspector;
15313
+ function readWorkflowEntryKind(bc) {
15314
+ const offset = bc.offset;
15315
+ const tag = readU8(bc);
15316
+ switch (tag) {
15317
+ case 0:
15318
+ return { tag: "WorkflowStepEntry", val: readWorkflowStepEntry(bc) };
15319
+ case 1:
15320
+ return { tag: "WorkflowLoopEntry", val: readWorkflowLoopEntry(bc) };
15321
+ case 2:
15322
+ return {
15323
+ tag: "WorkflowSleepEntry",
15324
+ val: readWorkflowSleepEntry(bc)
15325
+ };
15326
+ case 3:
15327
+ return {
15328
+ tag: "WorkflowMessageEntry",
15329
+ val: readWorkflowMessageEntry(bc)
15330
+ };
15331
+ case 4:
15332
+ return {
15333
+ tag: "WorkflowRollbackCheckpointEntry",
15334
+ val: readWorkflowRollbackCheckpointEntry(bc)
15335
+ };
15336
+ case 5:
15337
+ return { tag: "WorkflowJoinEntry", val: readWorkflowJoinEntry(bc) };
15338
+ case 6:
15339
+ return { tag: "WorkflowRaceEntry", val: readWorkflowRaceEntry(bc) };
15340
+ case 7:
15341
+ return {
15342
+ tag: "WorkflowRemovedEntry",
15343
+ val: readWorkflowRemovedEntry(bc)
15344
+ };
15345
+ case 8:
15346
+ return {
15347
+ tag: "WorkflowVersionCheckEntry",
15348
+ val: readWorkflowVersionCheckEntry(bc)
15349
+ };
15350
+ default: {
15351
+ bc.offset = offset;
15352
+ throw new BareError(offset, "invalid tag");
15353
+ }
15192
15354
  }
15193
- return run.inspector;
15194
15355
  }
15195
- function hasRunInspectorConfig(run) {
15196
- if (!run) return false;
15197
- if (typeof run !== "function") return run.inspector !== void 0;
15198
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15199
- return (config3 == null ? void 0 : config3.inspectorKind) !== void 0 || (config3 == null ? void 0 : config3.createInspector) !== void 0 || (config3 == null ? void 0 : config3.inspector) !== void 0 || (config3 == null ? void 0 : config3.inspectorFactory) !== void 0;
15356
+ function readWorkflowEntry(bc) {
15357
+ return {
15358
+ id: readString(bc),
15359
+ location: readWorkflowLocation(bc),
15360
+ kind: readWorkflowEntryKind(bc)
15361
+ };
15362
+ }
15363
+ function read3(bc) {
15364
+ return readBool(bc) ? readU64(bc) : null;
15200
15365
  }
15201
- function disposeRunInspector(run, actorId) {
15202
- var _a2;
15203
- if (!run || typeof run !== "function") {
15204
- return;
15205
- }
15206
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15207
- (_a2 = config3 == null ? void 0 : config3.disposeInspector) == null ? void 0 : _a2.call(config3, actorId);
15366
+ function readWorkflowEntryMetadata(bc) {
15367
+ return {
15368
+ status: readWorkflowEntryStatus(bc),
15369
+ error: read1(bc),
15370
+ attempts: readU32(bc),
15371
+ lastAttemptAt: readU64(bc),
15372
+ createdAt: readU64(bc),
15373
+ completedAt: read3(bc),
15374
+ rollbackCompletedAt: read3(bc),
15375
+ rollbackError: read1(bc)
15376
+ };
15208
15377
  }
15209
- var GlobalActorOptionsBaseSchema = external_exports.object({
15210
- /** Display name for the actor in the Inspector UI. */
15211
- name: external_exports.string().optional(),
15212
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
15213
- icon: external_exports.string().optional(),
15214
- /** Enables the experimental Actor Runtime Socket for this actor. */
15215
- enableActorRuntimeSocket: external_exports.boolean().default(false),
15216
- /**
15217
- * Can hibernate WebSockets for onWebSocket.
15218
- *
15219
- * WebSockets using actions/events are hibernatable by default.
15220
- *
15221
- * @experimental
15222
- **/
15223
- canHibernateWebSocket: external_exports.union([external_exports.boolean(), zFunction()]).default(false)
15224
- }).strict();
15225
- var GlobalActorOptionsSchema = GlobalActorOptionsBaseSchema.prefault(
15226
- () => ({})
15227
- );
15228
- var InstanceActorOptionsBaseSchema = external_exports.object({
15229
- createVarsTimeout: external_exports.number().positive().default(5e3),
15230
- createConnStateTimeout: external_exports.number().positive().default(5e3),
15231
- onBeforeConnectTimeout: external_exports.number().positive().default(5e3),
15232
- onConnectTimeout: external_exports.number().positive().default(5e3),
15233
- onMigrateTimeout: external_exports.number().positive().default(3e4),
15234
- sleepGracePeriod: external_exports.number().positive().default(DEFAULT_SLEEP_GRACE_PERIOD),
15235
- /** @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. */
15236
- onDestroyTimeout: external_exports.number().positive().optional(),
15237
- /** @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. */
15238
- waitUntilTimeout: external_exports.number().positive().optional(),
15239
- stateSaveInterval: external_exports.number().positive().default(1e3),
15240
- actionTimeout: external_exports.number().positive().default(6e4),
15241
- connectionLivenessTimeout: external_exports.number().positive().default(2500),
15242
- connectionLivenessInterval: external_exports.number().positive().default(5e3),
15243
- /** @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. */
15244
- noSleep: external_exports.boolean().default(false),
15245
- sleepTimeout: external_exports.number().positive().default(3e4),
15246
- maxQueueSize: external_exports.number().positive().default(1e3),
15247
- /** Maximum pending one-shot and recurring schedules. */
15248
- maxSchedules: external_exports.number().int().nonnegative().default(1e3),
15249
- maxQueueMessageSize: external_exports.number().positive().default(64 * 1024),
15250
- /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
15251
- preloadMaxWorkflowBytes: external_exports.number().nonnegative().optional(),
15252
- /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
15253
- preloadMaxConnectionsBytes: external_exports.number().nonnegative().optional()
15254
- }).strict();
15255
- var InstanceActorOptionsSchema = InstanceActorOptionsBaseSchema.prefault(() => ({}));
15256
- var ActorOptionsSchema = GlobalActorOptionsBaseSchema.extend(
15257
- InstanceActorOptionsBaseSchema.shape
15258
- ).strict().prefault(() => ({}));
15259
- var ActorConfigSchema = external_exports.object({
15260
- onCreate: zFunction().optional(),
15261
- onDestroy: zFunction().optional(),
15262
- onMigrate: zFunction().optional(),
15263
- onWake: zFunction().optional(),
15264
- onSleep: zFunction().optional(),
15265
- run: zRunHandler,
15266
- onStateChange: zFunction().optional(),
15267
- onBeforeConnect: zFunction().optional(),
15268
- onConnect: zFunction().optional(),
15269
- onDisconnect: zFunction().optional(),
15270
- onBeforeActionResponse: zFunction().optional(),
15271
- onRequest: zFunction().optional(),
15272
- onWebSocket: zFunction().optional(),
15273
- actions: zActionTree.default(() => ({})),
15274
- actionInputSchemas: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15275
- connParamsSchema: external_exports.any().optional(),
15276
- events: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15277
- queues: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15278
- state: external_exports.any().optional(),
15279
- createState: zFunction().optional(),
15280
- connState: external_exports.any().optional(),
15281
- createConnState: zFunction().optional(),
15282
- vars: external_exports.any().optional(),
15283
- db: external_exports.any().optional(),
15284
- createVars: zFunction().optional(),
15285
- options: ActorOptionsSchema,
15286
- inspector: ActorInspectorConfigSchema.optional()
15287
- }).strict().refine(
15288
- (data) => !(data.state !== void 0 && data.createState !== void 0),
15289
- {
15290
- message: "Cannot define both 'state' and 'createState'",
15291
- path: ["state"]
15292
- }
15293
- ).refine(
15294
- (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
15295
- {
15296
- message: "Cannot define both 'connState' and 'createConnState'",
15297
- path: ["connState"]
15378
+ function read4(bc) {
15379
+ const len = readUintSafe(bc);
15380
+ if (len === 0) {
15381
+ return [];
15298
15382
  }
15299
- ).refine(
15300
- (data) => !(data.vars !== void 0 && data.createVars !== void 0),
15301
- {
15302
- message: "Cannot define both 'vars' and 'createVars'",
15303
- path: ["vars"]
15383
+ const result = [readString(bc)];
15384
+ for (let i = 1; i < len; i++) {
15385
+ result[i] = readString(bc);
15304
15386
  }
15305
- );
15306
- var DocActorOptionsSchema = external_exports.object({
15307
- name: external_exports.string().optional().describe("Display name for the actor in the Inspector UI."),
15308
- icon: external_exports.string().optional().describe(
15309
- "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
15310
- ),
15311
- enableActorRuntimeSocket: external_exports.boolean().optional().describe(
15312
- "Enables the experimental Actor Runtime Socket for this actor. Default: false"
15313
- ),
15314
- createVarsTimeout: external_exports.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
15315
- createConnStateTimeout: external_exports.number().optional().describe(
15316
- "Timeout in ms for createConnState handler. Default: 5000"
15317
- ),
15318
- onMigrateTimeout: external_exports.number().optional().describe("Timeout in ms for onMigrate handler. Default: 30000"),
15319
- onBeforeConnectTimeout: external_exports.number().optional().describe(
15320
- "Timeout in ms for onBeforeConnect handler. Default: 5000"
15321
- ),
15322
- onConnectTimeout: external_exports.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
15323
- sleepGracePeriod: external_exports.number().optional().describe(
15324
- `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}.`
15325
- ),
15326
- onDestroyTimeout: external_exports.number().optional().describe(
15327
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
15328
- ),
15329
- waitUntilTimeout: external_exports.number().optional().describe(
15330
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
15331
- ),
15332
- stateSaveInterval: external_exports.number().optional().describe(
15333
- "Interval in ms between automatic state saves. Default: 1000"
15334
- ),
15335
- actionTimeout: external_exports.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
15336
- connectionLivenessTimeout: external_exports.number().optional().describe(
15337
- "Timeout in ms for connection liveness checks. Default: 2500"
15338
- ),
15339
- connectionLivenessInterval: external_exports.number().optional().describe(
15340
- "Interval in ms between connection liveness checks. Default: 5000"
15341
- ),
15342
- noSleep: external_exports.boolean().optional().describe(
15343
- "Deprecated. If true, the actor will never sleep. Use c.keepAwake(promise) to scope keep-awake to a specific operation instead. Default: false"
15344
- ),
15345
- sleepTimeout: external_exports.number().optional().describe(
15346
- "Time in ms of inactivity before the actor sleeps. Default: 30000"
15347
- ),
15348
- maxQueueSize: external_exports.number().optional().describe(
15349
- "Maximum number of queue messages before rejecting new messages. Default: 1000"
15350
- ),
15351
- maxSchedules: external_exports.number().int().nonnegative().optional().describe(
15352
- "Maximum pending one-shot and recurring schedules before rejecting new schedules. Default: 1000"
15353
- ),
15354
- maxQueueMessageSize: external_exports.number().optional().describe(
15355
- "Maximum size of each queue message in bytes. Default: 65536"
15356
- ),
15357
- canHibernateWebSocket: external_exports.boolean().optional().describe(
15358
- "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
15359
- )
15360
- }).describe("Actor options for timeouts and behavior configuration.");
15361
- var DocActorConfigSchema = external_exports.object({
15362
- state: external_exports.unknown().optional().describe(
15363
- "Initial state value for the actor. Cannot be used with createState."
15364
- ),
15365
- createState: external_exports.unknown().optional().describe(
15366
- "Function to create initial state. Receives context and input. Cannot be used with state."
15367
- ),
15368
- connState: external_exports.unknown().optional().describe(
15369
- "Initial connection state value. Cannot be used with createConnState."
15370
- ),
15371
- createConnState: external_exports.unknown().optional().describe(
15372
- "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."
15373
- ),
15374
- vars: external_exports.unknown().optional().describe(
15375
- "Initial ephemeral variables value. Cannot be used with createVars."
15376
- ),
15377
- createVars: external_exports.unknown().optional().describe(
15378
- "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
15379
- ),
15380
- db: external_exports.unknown().optional().describe("Database provider instance for the actor."),
15381
- onCreate: external_exports.unknown().optional().describe(
15382
- "Called when the actor is first initialized. Use to initialize state."
15383
- ),
15384
- onDestroy: external_exports.unknown().optional().describe("Called when the actor is destroyed."),
15385
- onMigrate: external_exports.unknown().optional().describe(
15386
- "Called on every actor start after persisted state loads and before onWake. Use for repeatable schema migrations."
15387
- ),
15388
- onWake: external_exports.unknown().optional().describe(
15389
- "Called when the actor wakes up and is ready to receive connections and actions."
15390
- ),
15391
- onSleep: external_exports.unknown().optional().describe(
15392
- "Called when the actor is stopping or sleeping. Use to clean up resources."
15393
- ),
15394
- run: external_exports.unknown().optional().describe(
15395
- "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."
15396
- ),
15397
- onStateChange: external_exports.unknown().optional().describe(
15398
- "Called when the actor's state changes. State changes within this hook won't trigger recursion."
15399
- ),
15400
- onBeforeConnect: external_exports.unknown().optional().describe(
15401
- "Called before a client connects. Throw an error to reject the connection. The pending connection is not visible in c.conns while this runs."
15402
- ),
15403
- onConnect: external_exports.unknown().optional().describe(
15404
- "Called when a client successfully connects. The connection is visible in c.conns before this runs."
15405
- ),
15406
- onDisconnect: external_exports.unknown().optional().describe("Called when a client disconnects."),
15407
- onBeforeActionResponse: external_exports.unknown().optional().describe(
15408
- "Called before sending an action response. Use to transform output."
15409
- ),
15410
- onRequest: external_exports.unknown().optional().describe(
15411
- "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
15412
- ),
15413
- onWebSocket: external_exports.unknown().optional().describe(
15414
- "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
15415
- ),
15416
- actions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
15417
- "Tree of action names or nested groups to handler functions. Nested paths use dot-separated low-level action names. Defaults to an empty object."
15418
- ),
15419
- actionInputSchemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
15420
- "Optional schemas for validating action argument tuples in native runtimes. May mirror nested action groups or use dot-separated low-level action names."
15421
- ),
15422
- connParamsSchema: external_exports.unknown().optional().describe(
15423
- "Optional schema for validating connection params in native runtimes."
15424
- ),
15425
- events: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of event names to schemas."),
15426
- queues: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of queue names to schemas."),
15427
- options: DocActorOptionsSchema.optional()
15428
- }).describe("Actor configuration passed to the actor() function.");
15387
+ return result;
15388
+ }
15389
+ function read5(bc) {
15390
+ const len = readUintSafe(bc);
15391
+ if (len === 0) {
15392
+ return [];
15393
+ }
15394
+ const result = [readWorkflowEntry(bc)];
15395
+ for (let i = 1; i < len; i++) {
15396
+ result[i] = readWorkflowEntry(bc);
15397
+ }
15398
+ return result;
15399
+ }
15400
+ function read6(bc) {
15401
+ const len = readUintSafe(bc);
15402
+ const result = /* @__PURE__ */ new Map();
15403
+ for (let i = 0; i < len; i++) {
15404
+ const offset = bc.offset;
15405
+ const key = readString(bc);
15406
+ if (result.has(key)) {
15407
+ bc.offset = offset;
15408
+ throw new BareError(offset, "duplicated key");
15409
+ }
15410
+ result.set(key, readWorkflowEntryMetadata(bc));
15411
+ }
15412
+ return result;
15413
+ }
15414
+ function readWorkflowHistory(bc) {
15415
+ return {
15416
+ nameRegistry: read4(bc),
15417
+ entries: read5(bc),
15418
+ entryMetadata: read6(bc)
15419
+ };
15420
+ }
15421
+ function decodeWorkflowHistory(bytes) {
15422
+ const bc = new ByteCursor(bytes, config2);
15423
+ const result = readWorkflowHistory(bc);
15424
+ if (bc.offset < bc.view.byteLength) {
15425
+ throw new BareError(bc.offset, "remaining bytes");
15426
+ }
15427
+ return result;
15428
+ }
15429
+ function decodeWorkflowHistoryTransport(data) {
15430
+ return decodeWorkflowHistory(toUint8Array(data));
15431
+ }
15429
15432
 
15430
15433
  // ../rivetkit/dist/tsup/chunk-JI6GZ2C2.js
15431
15434
  var EMPTY_KEY = "/";
@@ -15544,7 +15547,7 @@ function removePrefixFromKey(prefixedKey) {
15544
15547
  return prefixedKey.slice(KEYS.KV.length);
15545
15548
  }
15546
15549
 
15547
- // ../rivetkit/dist/tsup/chunk-FXT3HN32.js
15550
+ // ../rivetkit/dist/tsup/chunk-XKVQ3AMZ.js
15548
15551
  function logger() {
15549
15552
  return getLogger("actor-client");
15550
15553
  }
@@ -15665,7 +15668,7 @@ var AsyncMutex = class {
15665
15668
  }
15666
15669
  };
15667
15670
 
15668
- // ../rivetkit/dist/tsup/chunk-6CXQMHZR.js
15671
+ // ../rivetkit/dist/tsup/chunk-QU5UOJLK.js
15669
15672
  var import_invariant2 = __toESM(require_invariant(), 1);
15670
15673
 
15671
15674
  // ../../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
@@ -15843,7 +15846,7 @@ function createVersionedDataHandler(config3) {
15843
15846
  return new VersionedDataHandler(config3);
15844
15847
  }
15845
15848
 
15846
- // ../rivetkit/dist/tsup/chunk-6CXQMHZR.js
15849
+ // ../rivetkit/dist/tsup/chunk-QU5UOJLK.js
15847
15850
  var import_invariant3 = __toESM(require_invariant(), 1);
15848
15851
  var import_invariant4 = __toESM(require_invariant(), 1);
15849
15852
  var PATH_CONNECT = "/connect";
@@ -15852,6 +15855,7 @@ var PATH_WEBSOCKET_PREFIX = "/websocket/";
15852
15855
  var HEADER_ACTOR_QUERY = "x-rivet-query";
15853
15856
  var HEADER_ENCODING = "x-rivet-encoding";
15854
15857
  var HEADER_CONN_PARAMS = "x-rivet-conn-params";
15858
+ var HEADER_ORIGINAL_REQUEST_URL = "x-rivet-internal-original-request-url";
15855
15859
  var HEADER_ACTOR_ID = "x-rivet-actor";
15856
15860
  var HEADER_ACTOR_GENERATION = "x-rivet-actor-generation";
15857
15861
  var HEADER_ACTOR_KEY = "x-rivet-actor-key";
@@ -17910,6 +17914,18 @@ async function checkForSchedulingError(group, code, actorId, query, driver, rayI
17910
17914
  }
17911
17915
  return null;
17912
17916
  }
17917
+ function isUrlLike(value) {
17918
+ return typeof value === "object" && value !== null && typeof value.href === "string" && typeof value.pathname === "string" && typeof value.search === "string";
17919
+ }
17920
+ function isRequestLike(value) {
17921
+ return typeof value === "object" && value !== null && typeof value.url === "string" && typeof value.method === "string" && isHeadersLike(value.headers);
17922
+ }
17923
+ function isResponseLike(value) {
17924
+ return typeof value === "object" && value !== null && typeof value.status === "number" && isHeadersLike(value.headers) && typeof value.arrayBuffer === "function";
17925
+ }
17926
+ function isHeadersLike(value) {
17927
+ return typeof value === "object" && value !== null && typeof value.entries === "function";
17928
+ }
17913
17929
  function* walkErrorChain(error46, maxDepth = 8) {
17914
17930
  let current = error46;
17915
17931
  let depth = 0;
@@ -18335,28 +18351,28 @@ function createQueueSender(senderOptions) {
18335
18351
  send
18336
18352
  };
18337
18353
  }
18338
- function isUrlLike(value) {
18339
- return typeof value === "object" && value !== null && typeof value.href === "string" && typeof value.pathname === "string" && typeof value.search === "string";
18340
- }
18341
- function isRequestLike(value) {
18342
- return typeof value === "object" && value !== null && typeof value.url === "string" && typeof value.method === "string" && isHeadersLike(value.headers);
18343
- }
18344
- function isResponseLike(value) {
18345
- return typeof value === "object" && value !== null && typeof value.status === "number" && isHeadersLike(value.headers) && typeof value.arrayBuffer === "function";
18346
- }
18347
- function isHeadersLike(value) {
18348
- return typeof value === "object" && value !== null && typeof value.entries === "function";
18354
+ async function prepareRetryableInit(init) {
18355
+ if (init.body instanceof ReadableStream) {
18356
+ return {
18357
+ ...init,
18358
+ body: new Uint8Array(await new Response(init.body).arrayBuffer())
18359
+ };
18360
+ }
18361
+ return init;
18349
18362
  }
18350
18363
  async function rawHttpFetch(driver, target, params, input, init, options = {}) {
18351
18364
  let path2;
18365
+ let originalUrl;
18352
18366
  let mergedInit = init || {};
18353
18367
  if (typeof input === "string") {
18354
18368
  path2 = input;
18355
18369
  } else if (isUrlLike(input)) {
18356
18370
  path2 = input.pathname + input.search;
18371
+ originalUrl = input.toString();
18357
18372
  } else if (isRequestLike(input)) {
18358
18373
  const url2 = new URL(input.url);
18359
18374
  path2 = url2.pathname + url2.search;
18375
+ originalUrl = url2.toString();
18360
18376
  const requestHeaders = new Headers(input.headers);
18361
18377
  const initHeaders = new Headers((init == null ? void 0 : init.headers) || {});
18362
18378
  const mergedHeaders = new Headers(requestHeaders);
@@ -18398,6 +18414,10 @@ async function rawHttpFetch(driver, target, params, input, init, options = {}) {
18398
18414
  const normalizedPath = path2.startsWith("/") ? path2.slice(1) : path2;
18399
18415
  const url2 = new URL(`http://actor/request/${normalizedPath}`);
18400
18416
  const proxyRequestHeaders = new Headers(mergedInit.headers);
18417
+ proxyRequestHeaders.delete(HEADER_ORIGINAL_REQUEST_URL);
18418
+ if (originalUrl) {
18419
+ proxyRequestHeaders.set(HEADER_ORIGINAL_REQUEST_URL, originalUrl);
18420
+ }
18401
18421
  if (params) {
18402
18422
  proxyRequestHeaders.set(HEADER_CONN_PARAMS, JSON.stringify(params));
18403
18423
  }
@@ -18492,6 +18512,7 @@ var ActorHandleRaw = class {
18492
18512
  #gatewayOptions;
18493
18513
  #params;
18494
18514
  #getParams;
18515
+ #signal;
18495
18516
  #resolvedActorId;
18496
18517
  #resolvingActorId;
18497
18518
  #queueSendMutex = new AsyncMutex();
@@ -18502,7 +18523,7 @@ var ActorHandleRaw = class {
18502
18523
  *
18503
18524
  * @protected
18504
18525
  */
18505
- constructor(client, driver, params, getParams, encoding, actorResolutionState, gatewayOptions = {}) {
18526
+ constructor(client, driver, params, getParams, encoding, actorResolutionState, gatewayOptions = {}, signal) {
18506
18527
  this.#client = client;
18507
18528
  this.#driver = driver;
18508
18529
  this.#encoding = encoding;
@@ -18510,6 +18531,7 @@ var ActorHandleRaw = class {
18510
18531
  this.#gatewayOptions = gatewayOptions;
18511
18532
  this.#params = params;
18512
18533
  this.#getParams = getParams;
18534
+ this.#signal = signal;
18513
18535
  }
18514
18536
  async #resolveConnectionParams() {
18515
18537
  if (this.#getParams) {
@@ -18523,7 +18545,9 @@ var ActorHandleRaw = class {
18523
18545
  async #sendQueueMessage(name, body, options) {
18524
18546
  return await this.#queueSendMutex.run(async () => {
18525
18547
  const maxAttempts = this.#getDynamicQueryMaxAttempts();
18526
- let useQueryTarget = false;
18548
+ let useQueryTarget = isDynamicActorQuery(
18549
+ this.#actorResolutionState
18550
+ );
18527
18551
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
18528
18552
  let actorId;
18529
18553
  try {
@@ -18586,8 +18610,9 @@ var ActorHandleRaw = class {
18586
18610
  code
18587
18611
  );
18588
18612
  if (invalidated && attempt < maxAttempts - 1) {
18589
- useQueryTarget = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
18590
- if (useQueryTarget) {
18613
+ const waitForReady = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
18614
+ useQueryTarget = useQueryTarget || waitForReady;
18615
+ if (waitForReady) {
18591
18616
  await this.#waitForRetryWindow();
18592
18617
  }
18593
18618
  continue;
@@ -18615,15 +18640,17 @@ var ActorHandleRaw = class {
18615
18640
  `Invalid action call: expected an options object { name, args }, got ${typeof opts}. Use handle.actionName(...args) for the shorthand API.`
18616
18641
  );
18617
18642
  }
18618
- const run = async () => await this.#sendActionNow(opts);
18643
+ const signal = opts.signal ?? this.#signal;
18644
+ const optsWithSignal = { ...opts, signal };
18645
+ const run = async () => await this.#sendActionNow(optsWithSignal);
18619
18646
  if (opts.name === "destroy") {
18620
18647
  return await run();
18621
18648
  }
18622
- return await retryOnLifecycleBoundary(run, { signal: opts.signal });
18649
+ return await retryOnLifecycleBoundary(run, { signal });
18623
18650
  }
18624
18651
  async #sendActionNow(opts) {
18625
18652
  const maxAttempts = this.#getDynamicQueryMaxAttempts();
18626
- let useQueryTarget = false;
18653
+ let useQueryTarget = isDynamicActorQuery(this.#actorResolutionState);
18627
18654
  const gatewayOptions = resolveActorGatewayOptions(
18628
18655
  this.#gatewayOptions,
18629
18656
  opts
@@ -18871,9 +18898,11 @@ var ActorHandleRaw = class {
18871
18898
  return this.#fetchWithResolvedActor(input, init);
18872
18899
  }
18873
18900
  async #fetchWithResolvedActor(input, init) {
18901
+ const { skipReadyWait, ...restInit } = init ?? {};
18874
18902
  const maxAttempts = this.#getDynamicQueryMaxAttempts();
18875
- let useQueryTarget = false;
18876
- const { skipReadyWait, ...requestInit } = init ?? {};
18903
+ const requestInit = maxAttempts > 1 ? await prepareRetryableInit(restInit) : restInit;
18904
+ const clonesInputBody = requestInit.body === void 0 && isRequestLike(input) && input.body !== null;
18905
+ let useQueryTarget = isDynamicActorQuery(this.#actorResolutionState);
18877
18906
  const gatewayOptions = resolveActorGatewayOptions(
18878
18907
  this.#gatewayOptions,
18879
18908
  {
@@ -18892,7 +18921,9 @@ var ActorHandleRaw = class {
18892
18921
  this.#driver,
18893
18922
  target,
18894
18923
  this.#params,
18895
- input,
18924
+ // Clone a body-bearing Request so retries don't reuse a consumed stream.
18925
+ // NOTE: This holds the body in memory until GC (unavoidable).
18926
+ clonesInputBody ? input.clone() : input,
18896
18927
  requestInit,
18897
18928
  gatewayOptions
18898
18929
  );
@@ -18940,8 +18971,9 @@ var ActorHandleRaw = class {
18940
18971
  code
18941
18972
  );
18942
18973
  if (invalidated && attempt < maxAttempts - 1) {
18943
- useQueryTarget = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
18944
- if (useQueryTarget) {
18974
+ const waitForReady = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
18975
+ useQueryTarget = useQueryTarget || waitForReady;
18976
+ if (waitForReady) {
18945
18977
  await this.#waitForRetryWindow();
18946
18978
  }
18947
18979
  continue;
@@ -18991,10 +19023,10 @@ var ActorHandleRaw = class {
18991
19023
  }
18992
19024
  const invalidated = this.#invalidateResolvedActorId(group, code);
18993
19025
  if (invalidated && attempt < maxAttempts - 1) {
18994
- const useQueryTarget = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
19026
+ const waitForReady = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
18995
19027
  return {
18996
- useQueryTarget,
18997
- waitForRetryWindow: useQueryTarget
19028
+ useQueryTarget: true,
19029
+ waitForRetryWindow: waitForReady
18998
19030
  };
18999
19031
  }
19000
19032
  return null;
@@ -19145,7 +19177,8 @@ var ClientRaw = class {
19145
19177
  const handle = this.#createHandle(
19146
19178
  opts == null ? void 0 : opts.params,
19147
19179
  opts == null ? void 0 : opts.getParams,
19148
- actorQuery
19180
+ actorQuery,
19181
+ opts == null ? void 0 : opts.signal
19149
19182
  );
19150
19183
  return createActorProxy(handle);
19151
19184
  }
@@ -19175,7 +19208,8 @@ var ClientRaw = class {
19175
19208
  const handle = this.#createHandle(
19176
19209
  opts == null ? void 0 : opts.params,
19177
19210
  opts == null ? void 0 : opts.getParams,
19178
- actorQuery
19211
+ actorQuery,
19212
+ opts == null ? void 0 : opts.signal
19179
19213
  );
19180
19214
  return createActorProxy(handle);
19181
19215
  }
@@ -19209,7 +19243,8 @@ var ClientRaw = class {
19209
19243
  const handle = this.#createHandle(
19210
19244
  opts == null ? void 0 : opts.params,
19211
19245
  opts == null ? void 0 : opts.getParams,
19212
- actorQuery
19246
+ actorQuery,
19247
+ opts == null ? void 0 : opts.signal
19213
19248
  );
19214
19249
  return createActorProxy(handle);
19215
19250
  }
@@ -19256,12 +19291,13 @@ var ClientRaw = class {
19256
19291
  const handle = this.#createHandle(
19257
19292
  opts == null ? void 0 : opts.params,
19258
19293
  opts == null ? void 0 : opts.getParams,
19259
- getForIdQuery
19294
+ getForIdQuery,
19295
+ opts == null ? void 0 : opts.signal
19260
19296
  );
19261
19297
  const proxy = createActorProxy(handle);
19262
19298
  return proxy;
19263
19299
  }
19264
- #createHandle(params, getParams, actorQuery) {
19300
+ #createHandle(params, getParams, actorQuery, signal) {
19265
19301
  return new ActorHandleRaw(
19266
19302
  this,
19267
19303
  this.#driver,
@@ -19269,7 +19305,8 @@ var ClientRaw = class {
19269
19305
  getParams,
19270
19306
  this.#encodingKind,
19271
19307
  actorQuery,
19272
- this.#gatewayOptions
19308
+ this.#gatewayOptions,
19309
+ signal
19273
19310
  );
19274
19311
  }
19275
19312
  [CREATE_ACTOR_CONN_PROXY](conn) {
@@ -20640,23 +20677,19 @@ async function sendHttpRequestToGateway(runConfig, gatewayUrl, actorRequest, opt
20640
20677
  if (actorRequest.bodyUsed) {
20641
20678
  throw new Error("Request body has already been consumed");
20642
20679
  }
20643
- const reqBody = await actorRequest.arrayBuffer();
20644
- if (reqBody.byteLength !== 0) {
20645
- bodyToSend = reqBody;
20680
+ if (actorRequest.body) {
20681
+ bodyToSend = actorRequest.body;
20646
20682
  guardHeaders.delete("transfer-encoding");
20647
20683
  guardHeaders.delete("content-length");
20648
20684
  }
20649
20685
  }
20650
- const guardRequest = new Request(gatewayUrl, {
20686
+ return fetch(gatewayUrl, {
20651
20687
  method: actorRequest.method,
20652
20688
  headers: guardHeaders,
20653
20689
  body: bodyToSend,
20654
- signal: actorRequest.signal
20690
+ signal: actorRequest.signal,
20691
+ ...bodyToSend ? { duplex: "half" } : {}
20655
20692
  });
20656
- return mutableResponse(await fetch(guardRequest));
20657
- }
20658
- function mutableResponse(fetchRes) {
20659
- return new Response(fetchRes.body, fetchRes);
20660
20693
  }
20661
20694
  function buildGuardHeaders(runConfig, actorRequest, options) {
20662
20695
  const headers = new Headers();
@@ -21367,24 +21400,45 @@ var RemoteEngineControlClient = class {
21367
21400
  name,
21368
21401
  key
21369
21402
  });
21370
- const { actor: actor2, created } = await getOrCreateActor(this.#config, {
21371
- datacenter: region,
21372
- name,
21373
- key: serializeActorKey(key),
21374
- runner_name_selector: poolName ?? this.#config.poolName,
21375
- input: actorInput ? uint8ArrayToBase642(
21376
- encodeCborCompat(actorInput)
21377
- ) : void 0,
21378
- crash_policy: crashPolicy ?? "sleep"
21379
- });
21380
- logger2().info({
21381
- msg: "getOrCreateWithKey: actor ready",
21382
- actorId: actor2.actor_id,
21383
- name,
21384
- key,
21385
- created
21386
- });
21387
- return apiActorToOutput(actor2);
21403
+ try {
21404
+ const { actor: actor2, created } = await getOrCreateActor(this.#config, {
21405
+ datacenter: region,
21406
+ name,
21407
+ key: serializeActorKey(key),
21408
+ runner_name_selector: poolName ?? this.#config.poolName,
21409
+ input: actorInput ? uint8ArrayToBase642(
21410
+ encodeCborCompat(actorInput)
21411
+ ) : void 0,
21412
+ crash_policy: crashPolicy ?? "sleep"
21413
+ });
21414
+ logger2().info({
21415
+ msg: "getOrCreateWithKey: actor ready",
21416
+ actorId: actor2.actor_id,
21417
+ name,
21418
+ key,
21419
+ created
21420
+ });
21421
+ return apiActorToOutput(actor2);
21422
+ } catch (error46) {
21423
+ if (error46 instanceof RivetError && error46.group === "actor" && error46.code === "key_reserved_in_different_datacenter") {
21424
+ logger2().warn({
21425
+ msg: "getOrCreateWithKey: key reserved in different datacenter, retrying as get",
21426
+ name,
21427
+ key
21428
+ });
21429
+ const response = await getActorByKey(this.#config, name, key);
21430
+ const existing = response.actors[0];
21431
+ if (!existing) throw error46;
21432
+ logger2().info({
21433
+ msg: "getOrCreateWithKey: resolved existing actor via get",
21434
+ actorId: existing.actor_id,
21435
+ name,
21436
+ key
21437
+ });
21438
+ return apiActorToOutput(existing);
21439
+ }
21440
+ throw error46;
21441
+ }
21388
21442
  }
21389
21443
  async createActor({
21390
21444
  name,
@@ -21585,7 +21639,7 @@ function apiActorToOutput(actor2) {
21585
21639
  };
21586
21640
  }
21587
21641
 
21588
- // ../rivetkit/dist/tsup/chunk-D6TORRA4.js
21642
+ // ../rivetkit/dist/tsup/chunk-MLT7XFEF.js
21589
21643
  var nativeStateTransactionOpeners = /* @__PURE__ */ new WeakMap();
21590
21644
  var nativeStateTransactionClientBinders = /* @__PURE__ */ new WeakMap();
21591
21645
  function registerNativeStateTransactionOpener(provider, opener) {
@@ -23661,6 +23715,12 @@ var RegistryConfigSchema = external_exports.object({
23661
23715
  enginePort: external_exports.number().int().min(1).max(65535).optional().default(() => getRivetRunEnginePort() ?? ENGINE_PORT),
23662
23716
  /** @experimental */
23663
23717
  engineVersion: external_exports.string().optional().default(() => getRivetRunEngineVersion() ?? VERSION),
23718
+ /**
23719
+ * Starts the first-party Services actor host when RivetKit manages
23720
+ * a local engine. Defaults to the local-engine decision. Set
23721
+ * RIVET_RUN_SERVICES=0 or 1 to override it.
23722
+ */
23723
+ startServices: external_exports.boolean().optional(),
23664
23724
  /**
23665
23725
  * @experimental
23666
23726
  *
@@ -23741,11 +23801,12 @@ var RegistryConfigSchema = external_exports.object({
23741
23801
  config3.enginePort
23742
23802
  );
23743
23803
  const endpoint = config3.startEngine ? localEngineEndpoint : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? localEngineEndpoint : void 0);
23804
+ const startServices = config3.startServices ?? getRivetRunServices() ?? Boolean(endpoint && isLocalEngineEndpoint(endpoint));
23744
23805
  const validateServerlessEndpoint = Boolean(
23745
23806
  config3.startEngine || parsedEndpoint
23746
23807
  );
23747
23808
  const namespace = (parsedEndpoint == null ? void 0 : parsedEndpoint.namespace) ?? config3.namespace ?? "default";
23748
- const token = (parsedEndpoint == null ? void 0 : parsedEndpoint.token) ?? config3.token;
23809
+ const token = (parsedEndpoint == null ? void 0 : parsedEndpoint.token) ?? config3.token ?? "dev";
23749
23810
  const parsedPublicEndpoint = config3.serverless.publicEndpoint ? tryParseEndpoint(ctx, {
23750
23811
  endpoint: config3.serverless.publicEndpoint,
23751
23812
  path: ["serverless", "publicEndpoint"]
@@ -23764,6 +23825,7 @@ var RegistryConfigSchema = external_exports.object({
23764
23825
  ...config3,
23765
23826
  sqlite,
23766
23827
  endpoint,
23828
+ startServices,
23767
23829
  namespace,
23768
23830
  token,
23769
23831
  publicEndpoint,
@@ -23877,6 +23939,9 @@ var DocRegistryConfigSchema = external_exports.object({
23877
23939
  engineVersion: external_exports.string().optional().describe(
23878
23940
  "Version of the local engine package to use. Defaults to the current RivetKit version."
23879
23941
  ),
23942
+ startServices: external_exports.boolean().optional().describe(
23943
+ "Starts Services when RivetKit manages a local Engine. Defaults to the local-Engine decision. Set RIVET_RUN_SERVICES=0 or 1 to override."
23944
+ ),
23880
23945
  configurePool: DocConfigurePoolSchema.describe(
23881
23946
  "Automatically configure serverless runners in the engine."
23882
23947
  ),
@@ -24386,16 +24451,30 @@ function toNapiApplication(application) {
24386
24451
  if (!request) {
24387
24452
  throw new Error("application fetch callback received no request");
24388
24453
  }
24389
- const response = await application({
24390
- ...request,
24391
- body: new Uint8Array(request.body)
24392
- });
24454
+ const response = await application(
24455
+ {
24456
+ ...request,
24457
+ body: new Uint8Array(request.body),
24458
+ cancelToken: request.cancelToken
24459
+ },
24460
+ request.responseBodyStream ? fromNapiHttpResponseBodyStream(
24461
+ request.responseBodyStream
24462
+ ) : void 0
24463
+ );
24393
24464
  return {
24394
24465
  ...response,
24395
- body: toNapiBuffer(response.body)
24466
+ body: response.body === void 0 ? void 0 : toNapiBuffer(response.body)
24396
24467
  };
24397
24468
  };
24398
24469
  }
24470
+ function fromNapiHttpResponseBodyStream(stream) {
24471
+ return {
24472
+ cancelled: () => stream.cancelled(),
24473
+ write: (chunk) => stream.write(Buffer.from(chunk)),
24474
+ end: () => stream.end(),
24475
+ error: (message) => stream.error(message)
24476
+ };
24477
+ }
24399
24478
  function toNapiHttpRequest(request) {
24400
24479
  if (!request) {
24401
24480
  return request;
@@ -24938,6 +25017,147 @@ async function loadNapiRuntime() {
24938
25017
  runtime: new NapiCoreRuntime(bindings)
24939
25018
  };
24940
25019
  }
25020
+ var HTTP_BODY_CHUNK_SIZE = 64 * 1024;
25021
+ function runtimeBytesToArrayBuffer(value) {
25022
+ return value.buffer.slice(
25023
+ value.byteOffset,
25024
+ value.byteOffset + value.byteLength
25025
+ );
25026
+ }
25027
+ function buildNativeHttpRequest(init) {
25028
+ var _a2;
25029
+ const headers = new Headers(init.headers);
25030
+ const originalUrl = headers.get(HEADER_ORIGINAL_REQUEST_URL);
25031
+ headers.delete(HEADER_ORIGINAL_REQUEST_URL);
25032
+ const url2 = originalUrl ?? (init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString());
25033
+ const method2 = init.method.toUpperCase();
25034
+ const bodyForbidden = method2 === "GET" || method2 === "HEAD";
25035
+ const body = bodyForbidden ? void 0 : init.bodyStream ? new ReadableStream({
25036
+ async pull(controller) {
25037
+ var _a22, _b;
25038
+ try {
25039
+ if (init.body && init.body.length > 0) {
25040
+ controller.enqueue(new Uint8Array(init.body));
25041
+ init.body = void 0;
25042
+ return;
25043
+ }
25044
+ const chunk = await ((_a22 = init.bodyStream) == null ? void 0 : _a22.read());
25045
+ if (!chunk) {
25046
+ controller.close();
25047
+ } else {
25048
+ controller.enqueue(new Uint8Array(chunk));
25049
+ }
25050
+ } catch (error46) {
25051
+ (_b = init.abortController) == null ? void 0 : _b.abort(error46);
25052
+ controller.error(error46);
25053
+ }
25054
+ },
25055
+ async cancel() {
25056
+ var _a22;
25057
+ await ((_a22 = init.bodyStream) == null ? void 0 : _a22.cancel());
25058
+ }
25059
+ }) : init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
25060
+ const streamInit = init.bodyStream && !bodyForbidden ? { duplex: "half" } : {};
25061
+ return new Request(url2, {
25062
+ method: method2,
25063
+ headers,
25064
+ body,
25065
+ signal: ((_a2 = init.abortController) == null ? void 0 : _a2.signal) ?? init.signal,
25066
+ ...streamInit
25067
+ });
25068
+ }
25069
+ async function cancelNativeHttpRequestBody(bodyStream) {
25070
+ await (bodyStream == null ? void 0 : bodyStream.cancel());
25071
+ }
25072
+ async function writeResponseChunk(stream, chunk) {
25073
+ for (let offset = 0; offset < chunk.byteLength; offset += HTTP_BODY_CHUNK_SIZE) {
25074
+ await stream.write(
25075
+ chunk.subarray(offset, offset + HTTP_BODY_CHUNK_SIZE)
25076
+ );
25077
+ }
25078
+ }
25079
+ async function pumpResponseBody(reader, stream) {
25080
+ var _a2;
25081
+ const cancelled = stream.cancelled().then(() => ({ cancelled: true }));
25082
+ try {
25083
+ for (; ; ) {
25084
+ const read = reader.read().then((next2) => ({ cancelled: false, next: next2 }));
25085
+ const result = await Promise.race([read, cancelled]);
25086
+ if (result.cancelled) {
25087
+ void reader.cancel(
25088
+ new Error(
25089
+ "native http response stream receiver dropped"
25090
+ )
25091
+ ).catch((error46) => {
25092
+ logger22().debug({
25093
+ msg: "failed to cancel native http response reader",
25094
+ error: error46
25095
+ });
25096
+ });
25097
+ return;
25098
+ }
25099
+ const { next } = result;
25100
+ if (next.done) {
25101
+ await stream.end();
25102
+ return;
25103
+ }
25104
+ if ((_a2 = next.value) == null ? void 0 : _a2.byteLength) {
25105
+ await writeResponseChunk(stream, next.value);
25106
+ }
25107
+ }
25108
+ } catch (error46) {
25109
+ try {
25110
+ await stream.error(stringifyError(error46));
25111
+ } catch (streamError) {
25112
+ logger22().debug({
25113
+ msg: "failed to report native http response stream error",
25114
+ error: streamError
25115
+ });
25116
+ }
25117
+ void reader.cancel(error46).catch(() => {
25118
+ });
25119
+ } finally {
25120
+ try {
25121
+ reader.releaseLock();
25122
+ } catch (error46) {
25123
+ logger22().debug({
25124
+ msg: "failed to release native http response reader lock",
25125
+ error: error46
25126
+ });
25127
+ }
25128
+ }
25129
+ }
25130
+ async function convertNativeHttpResponse(response, responseBodyStream) {
25131
+ const headers = Object.fromEntries(response.headers.entries());
25132
+ if (!response.body) {
25133
+ return {
25134
+ response: {
25135
+ status: response.status,
25136
+ headers,
25137
+ body: new Uint8Array()
25138
+ }
25139
+ };
25140
+ }
25141
+ if (responseBodyStream) {
25142
+ const reader = response.body.getReader();
25143
+ const bodyCompletion = pumpResponseBody(reader, responseBodyStream);
25144
+ return {
25145
+ response: {
25146
+ status: response.status,
25147
+ headers,
25148
+ stream: true
25149
+ },
25150
+ bodyCompletion
25151
+ };
25152
+ }
25153
+ return {
25154
+ response: {
25155
+ status: response.status,
25156
+ headers,
25157
+ body: new Uint8Array(await response.arrayBuffer())
25158
+ }
25159
+ };
25160
+ }
24941
25161
  var CONN_PARAMS_KEY = "__conn_params__";
24942
25162
  function validateActionArgs(schemas, name, args) {
24943
25163
  if (!(schemas == null ? void 0 : schemas[name])) {
@@ -26084,10 +26304,28 @@ async function loadAutoRuntime(config3, loaders = defaultRuntimeLoaders) {
26084
26304
  if (loaders.detectHost() === "edge-like") {
26085
26305
  return (await loaders.loadWasm(config3.wasm)).runtime;
26086
26306
  }
26307
+ let nativeError;
26087
26308
  try {
26088
26309
  return (await loaders.loadNative()).runtime;
26089
- } catch {
26310
+ } catch (error46) {
26311
+ nativeError = error46;
26312
+ logger22().warn({
26313
+ msg: "native runtime failed to load; falling back to wasm",
26314
+ error: stringifyError(error46)
26315
+ });
26316
+ }
26317
+ try {
26090
26318
  return (await loaders.loadWasm(config3.wasm)).runtime;
26319
+ } catch (wasmError) {
26320
+ throw new RivetError(
26321
+ "config",
26322
+ "runtime_unavailable",
26323
+ `RivetKit could not load a core runtime. Native runtime: ${stringifyError(nativeError)} Wasm runtime: ${stringifyError(wasmError)}`,
26324
+ {
26325
+ public: true,
26326
+ statusCode: 500
26327
+ }
26328
+ );
26091
26329
  }
26092
26330
  }
26093
26331
  async function loadConfiguredRuntime(config3, loaders = defaultRuntimeLoaders) {
@@ -26386,7 +26624,7 @@ function toRuntimeBytes(value) {
26386
26624
  function arrayBufferViewToRuntimeBytes(value) {
26387
26625
  return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
26388
26626
  }
26389
- function runtimeBytesToArrayBuffer(value) {
26627
+ function runtimeBytesToArrayBuffer2(value) {
26390
26628
  return value.buffer.slice(
26391
26629
  value.byteOffset,
26392
26630
  value.byteOffset + value.byteLength
@@ -26432,6 +26670,9 @@ function decodeNativeKvValue(value, options) {
26432
26670
  async function loadEngineCli() {
26433
26671
  return import(["@rivetkit", "engine-cli"].join("/"));
26434
26672
  }
26673
+ async function loadServices() {
26674
+ return import(["@rivet-dev", "services"].join("/"));
26675
+ }
26435
26676
  function decodeValue(value) {
26436
26677
  if (!value || value.length === 0) {
26437
26678
  return void 0;
@@ -26717,24 +26958,6 @@ function decodeArgs(value) {
26717
26958
  const decoded = decodeValue(value);
26718
26959
  return normalizeArgs(decoded);
26719
26960
  }
26720
- function buildRequest(init) {
26721
- const url2 = init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString();
26722
- const body = init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
26723
- return new Request(url2, {
26724
- method: init.method,
26725
- headers: init.headers,
26726
- body
26727
- });
26728
- }
26729
- async function toRuntimeHttpResponse(response) {
26730
- const headers = Object.fromEntries(response.headers.entries());
26731
- const body = new Uint8Array(await response.arrayBuffer());
26732
- return {
26733
- status: response.status,
26734
- headers,
26735
- body
26736
- };
26737
- }
26738
26961
  function toActorKey(segments) {
26739
26962
  return segments.map(
26740
26963
  (segment) => segment.kind === "number" ? String(segment.numberValue ?? 0) : segment.stringValue ?? ""
@@ -27447,7 +27670,7 @@ var NativeWebSocketAdapter = class {
27447
27670
  this.#runtime.webSocketSetEventCallback(this.#ws, (event2) => {
27448
27671
  if (event2.kind === "message") {
27449
27672
  this.#virtual.triggerMessage(
27450
- event2.binary ? runtimeBytesToArrayBuffer(event2.data) : event2.data,
27673
+ event2.binary ? runtimeBytesToArrayBuffer2(event2.data) : event2.data,
27451
27674
  event2.messageIndex
27452
27675
  );
27453
27676
  return;
@@ -28830,12 +29053,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28830
29053
  cancelToken,
28831
29054
  run !== void 0
28832
29055
  );
28833
- const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
29056
+ const maybeHandleNativeInspectorRequest = async (ctx, rawRequest) => {
28834
29057
  var _a22, _b, _c, _d;
28835
- const url2 = new URL(jsRequest.url);
29058
+ const rawUrl = rawRequest.uri.startsWith("http") ? rawRequest.uri : new URL(rawRequest.uri, "http://127.0.0.1").toString();
29059
+ const url2 = new URL(rawUrl);
28836
29060
  if (!url2.pathname.startsWith("/inspector/")) {
28837
29061
  return void 0;
28838
29062
  }
29063
+ const jsRequest = buildNativeHttpRequest(rawRequest);
28839
29064
  const jsonResponse = (body, init) => new Response(JSON.stringify(body), {
28840
29065
  status: (init == null ? void 0 : init.status) ?? 200,
28841
29066
  headers: {
@@ -29366,7 +29591,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29366
29591
  );
29367
29592
  const actorCtx = makeActorCtx(
29368
29593
  ctx,
29369
- request ? buildRequest(request) : void 0
29594
+ request ? buildNativeHttpRequest(request) : void 0
29370
29595
  );
29371
29596
  try {
29372
29597
  await config3.onBeforeConnect(
@@ -29386,7 +29611,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29386
29611
  const { ctx, conn, params, request } = unwrapTsfnPayload(error46, payload);
29387
29612
  const actorCtx = makeActorCtx(
29388
29613
  ctx,
29389
- request ? buildRequest(request) : void 0
29614
+ request ? buildNativeHttpRequest(request) : void 0
29390
29615
  );
29391
29616
  const connAdapter = new NativeConnAdapter(
29392
29617
  runtime,
@@ -29424,7 +29649,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29424
29649
  );
29425
29650
  const actorCtx = makeActorCtx(
29426
29651
  ctx,
29427
- request ? buildRequest(request) : void 0
29652
+ request ? buildNativeHttpRequest(request) : void 0
29428
29653
  );
29429
29654
  const connAdapter = new NativeConnAdapter(
29430
29655
  runtime,
@@ -29531,27 +29756,45 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29531
29756
  onRequest: wrapNativeCallback(
29532
29757
  async (error46, payload) => {
29533
29758
  try {
29534
- const { ctx, request, cancelToken } = unwrapTsfnPayload(
29535
- error46,
29536
- payload
29537
- );
29538
- const jsRequest = buildRequest(request);
29539
- const inspectorResponse = await maybeHandleNativeInspectorRequest(
29540
- ctx,
29541
- request,
29542
- jsRequest
29543
- );
29759
+ const { ctx, request, cancelToken, responseBodyStream } = unwrapTsfnPayload(error46, payload);
29760
+ const inspectorResponse = await maybeHandleNativeInspectorRequest(ctx, request);
29544
29761
  if (inspectorResponse) {
29545
- return await toRuntimeHttpResponse(inspectorResponse);
29762
+ await cancelNativeHttpRequestBody(request.bodyStream);
29763
+ return (await convertNativeHttpResponse(
29764
+ inspectorResponse,
29765
+ responseBodyStream
29766
+ )).response;
29546
29767
  }
29547
29768
  if (typeof config3.onRequest !== "function") {
29548
- return await toRuntimeHttpResponse(
29549
- new Response(null, { status: 404 })
29550
- );
29769
+ await cancelNativeHttpRequestBody(request.bodyStream);
29770
+ return (await convertNativeHttpResponse(
29771
+ new Response(null, { status: 404 }),
29772
+ responseBodyStream
29773
+ )).response;
29551
29774
  }
29552
- const rawConnParams = jsRequest.headers.get(HEADER_CONN_PARAMS);
29775
+ const requestAbortController = new AbortController();
29776
+ const handlerRequest = buildNativeHttpRequest({
29777
+ ...request,
29778
+ abortController: requestAbortController
29779
+ });
29780
+ const rawConnParams = handlerRequest.headers.get(HEADER_CONN_PARAMS);
29553
29781
  let requestCtx;
29554
29782
  let conn;
29783
+ let removeRequestAbortListener;
29784
+ let cleanupDeferredToBody = false;
29785
+ let cleanedUp = false;
29786
+ const cleanupRequest = async () => {
29787
+ if (cleanedUp) return;
29788
+ cleanedUp = true;
29789
+ removeRequestAbortListener == null ? void 0 : removeRequestAbortListener();
29790
+ try {
29791
+ await (requestCtx == null ? void 0 : requestCtx.dispose());
29792
+ } finally {
29793
+ if (conn) {
29794
+ await runtime.connDisconnect(conn);
29795
+ }
29796
+ }
29797
+ };
29555
29798
  try {
29556
29799
  const connParams = validateConnParams(
29557
29800
  schemaConfig.connParamsSchema,
@@ -29567,23 +29810,56 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29567
29810
  requestCtx = makeConnCtx(
29568
29811
  ctx,
29569
29812
  conn,
29570
- jsRequest,
29813
+ handlerRequest,
29571
29814
  cancelToken
29572
29815
  );
29816
+ const ctxAbortSignal = requestCtx.abortSignal;
29817
+ const abortRequest = () => requestAbortController.abort(ctxAbortSignal.reason);
29818
+ if (ctxAbortSignal.aborted) {
29819
+ abortRequest();
29820
+ } else {
29821
+ ctxAbortSignal.addEventListener(
29822
+ "abort",
29823
+ abortRequest,
29824
+ { once: true }
29825
+ );
29826
+ removeRequestAbortListener = () => ctxAbortSignal.removeEventListener(
29827
+ "abort",
29828
+ abortRequest
29829
+ );
29830
+ }
29573
29831
  const response = await config3.onRequest(
29574
29832
  requestCtx,
29575
- jsRequest
29833
+ handlerRequest
29576
29834
  );
29577
29835
  if (!isResponseLike(response)) {
29578
29836
  throw new Error(
29579
29837
  "onRequest handler must return a Response"
29580
29838
  );
29581
29839
  }
29582
- return await toRuntimeHttpResponse(response);
29840
+ const conversion = await convertNativeHttpResponse(
29841
+ response,
29842
+ responseBodyStream
29843
+ );
29844
+ if (conversion.bodyCompletion) {
29845
+ cleanupDeferredToBody = true;
29846
+ void conversion.bodyCompletion.then(cleanupRequest).catch((cleanupError) => {
29847
+ logger22().error({
29848
+ msg: "failed to clean up native streaming http request",
29849
+ error: cleanupError
29850
+ });
29851
+ });
29852
+ }
29853
+ return conversion.response;
29583
29854
  } finally {
29584
- await (requestCtx == null ? void 0 : requestCtx.dispose());
29585
- if (conn) {
29586
- await runtime.connDisconnect(conn);
29855
+ try {
29856
+ await cancelNativeHttpRequestBody(
29857
+ request.bodyStream
29858
+ );
29859
+ } finally {
29860
+ if (!cleanupDeferredToBody) {
29861
+ await cleanupRequest();
29862
+ }
29587
29863
  }
29588
29864
  }
29589
29865
  } catch (error210) {
@@ -29598,7 +29874,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29598
29874
  onWebSocket: typeof config3.onWebSocket === "function" ? wrapNativeCallback(
29599
29875
  async (error46, payload) => {
29600
29876
  const { ctx, conn, ws, request } = unwrapTsfnPayload(error46, payload);
29601
- const jsRequest = request ? buildRequest(request) : void 0;
29877
+ const jsRequest = request ? buildNativeHttpRequest(request) : void 0;
29602
29878
  const actorCtx = makeConnCtx(ctx, conn, jsRequest);
29603
29879
  try {
29604
29880
  await config3.onWebSocket(
@@ -29704,7 +29980,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29704
29980
  timeoutMs,
29705
29981
  cancelToken
29706
29982
  } = unwrapTsfnPayload(error46, payload);
29707
- const jsRequest = buildRequest(request);
29983
+ const jsRequest = buildNativeHttpRequest(request);
29708
29984
  const actorCtx = withConnContext(
29709
29985
  runtime,
29710
29986
  ctx,
@@ -29774,7 +30050,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29774
30050
  buildActorConfig(definition, registryConfig, runtime.kind)
29775
30051
  );
29776
30052
  }
29777
- async function buildServeConfig(config3) {
30053
+ async function buildServeConfig(config3, resolveServicesBinary = true) {
29778
30054
  var _a2;
29779
30055
  if (!config3.endpoint) {
29780
30056
  throw nativeEndpointNotConfiguredError();
@@ -29785,6 +30061,7 @@ async function buildServeConfig(config3) {
29785
30061
  token: config3.token,
29786
30062
  namespace: config3.namespace,
29787
30063
  poolName: config3.envoy.poolName,
30064
+ startServices: resolveServicesBinary && config3.startServices,
29788
30065
  handleInspectorHttpInRuntime: true,
29789
30066
  serverlessBasePath: config3.serverless.basePath,
29790
30067
  serverlessPackageVersion: VERSION,
@@ -29803,6 +30080,17 @@ async function buildServeConfig(config3) {
29803
30080
  error: stringifyError(error46)
29804
30081
  });
29805
30082
  }
30083
+ if (resolveServicesBinary && config3.startServices) {
30084
+ try {
30085
+ const { getServicesPath } = await loadServices();
30086
+ serveConfig.servicesBinaryPath = getServicesPath();
30087
+ } catch (error46) {
30088
+ logger22().warn({
30089
+ msg: "could not resolve the Services binary; a local engine will fail with services.binary_unavailable \u2014 set RIVET_RUN_SERVICES=0 to disable Services or RIVET_SERVICES_BINARY to a local rivet-services binary",
30090
+ error: stringifyError(error46)
30091
+ });
30092
+ }
30093
+ }
29806
30094
  serveConfig.engineHost = config3.engineHost;
29807
30095
  serveConfig.enginePort = config3.enginePort;
29808
30096
  if ((_a2 = config3.test) == null ? void 0 : _a2.enabled) {
@@ -29829,7 +30117,7 @@ async function buildRegistryWithRuntime(config3, runtime) {
29829
30117
  return {
29830
30118
  runtime,
29831
30119
  registry: registry2,
29832
- serveConfig: await buildServeConfig(config3)
30120
+ serveConfig: await buildServeConfig(config3, runtime.kind === "napi")
29833
30121
  };
29834
30122
  }
29835
30123
  async function buildConfiguredRegistry(config3) {
@@ -29854,15 +30142,27 @@ function finishShutdownSignal(signal) {
29854
30142
  }
29855
30143
  process.kill(process.pid, signal);
29856
30144
  }
29857
- function createApplicationFetch(application) {
29858
- return async (request) => {
30145
+ function createApplicationFetch(application, runtime) {
30146
+ return async (request, responseBodyStream) => {
29859
30147
  const method2 = request.method.toUpperCase();
29860
30148
  const body = method2 === "GET" || method2 === "HEAD" || request.body.length === 0 ? void 0 : Uint8Array.from(request.body).buffer;
30149
+ const abortController = new AbortController();
30150
+ if (request.cancelToken) {
30151
+ if (runtime.cancellationTokenAborted(request.cancelToken)) {
30152
+ abortController.abort();
30153
+ } else {
30154
+ runtime.onCancellationTokenCancelled(
30155
+ request.cancelToken,
30156
+ () => abortController.abort()
30157
+ );
30158
+ }
30159
+ }
29861
30160
  const response = await application.fetch(
29862
30161
  new Request(request.url, {
29863
30162
  method: method2,
29864
30163
  headers: request.headers,
29865
- body
30164
+ body,
30165
+ signal: abortController.signal
29866
30166
  })
29867
30167
  );
29868
30168
  if (!isResponseLike(response)) {
@@ -29870,10 +30170,23 @@ function createApplicationFetch(application) {
29870
30170
  "registry.listen() application fetch must return a Response"
29871
30171
  );
29872
30172
  }
30173
+ const conversion = await convertNativeHttpResponse(
30174
+ response,
30175
+ responseBodyStream
30176
+ );
30177
+ if (conversion.bodyCompletion) {
30178
+ void conversion.bodyCompletion.catch((error46) => {
30179
+ logger22().error({
30180
+ msg: "application response stream failed",
30181
+ error: error46
30182
+ });
30183
+ });
30184
+ }
29873
30185
  return {
29874
- status: response.status,
29875
- headers: Object.fromEntries(response.headers.entries()),
29876
- body: new Uint8Array(await response.arrayBuffer())
30186
+ status: conversion.response.status ?? response.status,
30187
+ headers: conversion.response.headers ?? Object.fromEntries(response.headers.entries()),
30188
+ body: conversion.response.body,
30189
+ stream: conversion.response.stream
29877
30190
  };
29878
30191
  };
29879
30192
  }
@@ -30131,8 +30444,7 @@ var Registry = class {
30131
30444
  const port = opts.port ?? parsePortEnv(process.env.RIVET_PORT) ?? 3e3;
30132
30445
  const publicDir = opts.publicDir ?? getRivetkitPublicDir();
30133
30446
  const config3 = this.parseConfig();
30134
- const application = opts.application ? createApplicationFetch(opts.application) : void 0;
30135
- if (application && getRivetkitRuntimeMode() !== "serverless") {
30447
+ if (opts.application && getRivetkitRuntimeMode() !== "serverless") {
30136
30448
  if (config3.runtime === "wasm") {
30137
30449
  throw new Error(
30138
30450
  "registry.listen() requires the native runtime; use an application-owned HTTP server with WebAssembly"
@@ -30151,13 +30463,18 @@ var Registry = class {
30151
30463
  throw new Error("registry envoy startup did not initialize");
30152
30464
  }
30153
30465
  const { runtime: runtime2, registry: registry22, serveConfig: serveConfig2 } = await configuredRegistryPromise2;
30466
+ const application2 = createApplicationFetch(
30467
+ opts.application,
30468
+ runtime2
30469
+ );
30470
+ await readyPromise;
30154
30471
  const listenerPromise = runtime2.serveApplicationListener(
30155
30472
  registry22,
30156
30473
  {
30157
30474
  port,
30158
30475
  host: opts.host,
30159
30476
  publicDir,
30160
- application
30477
+ application: application2
30161
30478
  },
30162
30479
  serveConfig2
30163
30480
  );
@@ -30168,14 +30485,10 @@ var Registry = class {
30168
30485
  "registry envoy serve lifecycle did not initialize"
30169
30486
  );
30170
30487
  }
30171
- await Promise.all([
30172
- readyPromise,
30173
- listenerPromise,
30174
- serveLifecyclePromise
30175
- ]);
30488
+ await Promise.all([listenerPromise, serveLifecyclePromise]);
30176
30489
  return;
30177
30490
  }
30178
- const configuredRegistryPromise = buildConfiguredRegistry(config3);
30491
+ const configuredRegistryPromise = this.#buildConfiguredRegistry(config3);
30179
30492
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
30180
30493
  this.#runtimeServerlessPromise = configuredRegistryPromise;
30181
30494
  this.#installSignalHandlers(config3);
@@ -30186,6 +30499,7 @@ var Registry = class {
30186
30499
  });
30187
30500
  this.#ensureServerlessPoolConfigured(config3);
30188
30501
  const { runtime, registry: registry2, serveConfig } = await configuredRegistryPromise;
30502
+ const application = opts.application ? createApplicationFetch(opts.application, runtime) : void 0;
30189
30503
  await runtime.serveListener(
30190
30504
  registry2,
30191
30505
  {