@rivetkit/supabase 2.3.20 → 2.3.21

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 +1326 -1094
  2. package/dist/mod.mjs +1329 -1097
  3. package/package.json +4 -4
package/dist/mod.js CHANGED
@@ -335,6 +335,202 @@ __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-P2OFXH4G.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 encodeErrorForBridge(error46) {
454
+ if (isCanonicalStructuredRivetError(error46)) {
455
+ return encodeBridgeRivetError(error46);
456
+ }
457
+ return String(error46);
458
+ }
459
+ function isCanonicalStructuredRivetError(error46) {
460
+ 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";
461
+ }
462
+ function decodeBridgeRivetErrorPayload(value) {
463
+ if (!value.startsWith(BRIDGE_RIVET_ERROR_PREFIX)) {
464
+ return void 0;
465
+ }
466
+ try {
467
+ const raw = JSON.parse(
468
+ value.slice(BRIDGE_RIVET_ERROR_PREFIX.length)
469
+ );
470
+ const payload = {
471
+ ...raw,
472
+ rayId: raw.rayId ?? void 0
473
+ };
474
+ if (!isRivetErrorLike(payload)) {
475
+ return void 0;
476
+ }
477
+ if (payload.actor !== void 0 && payload.actor !== null && !isActorSpecifier(payload.actor)) {
478
+ return void 0;
479
+ }
480
+ return payload;
481
+ } catch {
482
+ return void 0;
483
+ }
484
+ }
485
+ function decodeBridgeRivetError(value) {
486
+ const payload = decodeBridgeRivetErrorPayload(value);
487
+ if (!payload) {
488
+ return void 0;
489
+ }
490
+ return new RivetError(payload.group, payload.code, payload.message, {
491
+ metadata: payload.metadata,
492
+ rayId: payload.rayId,
493
+ public: payload.public,
494
+ statusCode: payload.statusCode,
495
+ actor: payload.actor ?? void 0
496
+ });
497
+ }
498
+ function invalidRequest(error46) {
499
+ return new RivetError(
500
+ "request",
501
+ "invalid",
502
+ `Invalid request: ${errorMessage(error46, String(error46))}`,
503
+ {
504
+ public: true,
505
+ cause: error46 instanceof Error ? error46 : void 0
506
+ }
507
+ );
508
+ }
509
+ function actorNotFound(identifier) {
510
+ return new RivetError(
511
+ "actor",
512
+ "not_found",
513
+ identifier ? `Actor not found: ${identifier} (https://www.rivet.dev/docs/clients/javascript)` : "Actor not found (https://www.rivet.dev/docs/clients/javascript)",
514
+ { public: true }
515
+ );
516
+ }
517
+ function forbiddenError() {
518
+ return new RivetError("auth", "forbidden", "Forbidden", {
519
+ public: true,
520
+ statusCode: 403
521
+ });
522
+ }
523
+ function unsupportedFeature(feature) {
524
+ return new RivetError(
525
+ "feature",
526
+ "unsupported",
527
+ `Unsupported feature: ${feature}`
528
+ );
529
+ }
530
+
531
+ // ../rivetkit/dist/tsup/chunk-RGIZNZYO.js
532
+ var import_pino = require("pino");
533
+
338
534
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/classic/external.js
339
535
  var external_exports = {};
340
536
  __export(external_exports, {
@@ -13005,867 +13201,178 @@ var classic_default = external_exports;
13005
13201
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/index.js
13006
13202
  var v4_default = classic_default;
13007
13203
 
13008
- // ../rivetkit/dist/tsup/chunk-CSOHAAZK.js
13009
- function flattenActionHandlers(actions) {
13010
- const flattened = /* @__PURE__ */ Object.create(null);
13011
- for (const { name, handler } of collectActionEntries(actions)) {
13012
- flattened[name] = handler;
13204
+ // ../rivetkit/dist/tsup/chunk-RGIZNZYO.js
13205
+ var cbor = __toESM(require("cbor-x"), 1);
13206
+ var import_invariant = __toESM(require_invariant(), 1);
13207
+ var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
13208
+ var getRivetEndpoint = () => getEnvUniversal("RIVET_ENDPOINT");
13209
+ var getRivetToken = () => getEnvUniversal("RIVET_TOKEN");
13210
+ var getRivetNamespace = () => getEnvUniversal("RIVET_NAMESPACE");
13211
+ var getRivetPool = () => getEnvUniversal("RIVET_POOL");
13212
+ var getRivetTotalSlots = () => {
13213
+ const value = getEnvUniversal("RIVET_TOTAL_SLOTS");
13214
+ return value !== void 0 ? parseInt(value, 10) : void 0;
13215
+ };
13216
+ var getRivetRunEngine = () => getEnvUniversal("RIVET_RUN_ENGINE") === "1";
13217
+ var getRivetRunEngineHost = () => getEnvUniversal("RIVET_RUN_ENGINE_HOST");
13218
+ var getRivetRunEnginePort = () => {
13219
+ const value = getEnvUniversal("RIVET_RUN_ENGINE_PORT");
13220
+ return value !== void 0 ? parseInt(value, 10) : void 0;
13221
+ };
13222
+ var getRivetRunEngineVersion = () => getEnvUniversal("RIVET_RUN_ENGINE_VERSION");
13223
+ var getRivetRunServices = () => {
13224
+ const value = getEnvUniversal("RIVET_RUN_SERVICES");
13225
+ return value === void 0 ? void 0 : value === "1";
13226
+ };
13227
+ var getRivetEnvoyVersion = () => {
13228
+ const value = getEnvUniversal("RIVET_ENVOY_VERSION");
13229
+ return value !== void 0 ? parseInt(value, 10) : void 0;
13230
+ };
13231
+ var getRivetPublicEndpoint = () => getEnvUniversal("RIVET_PUBLIC_ENDPOINT");
13232
+ var getRivetPublicToken = () => getEnvUniversal("RIVET_PUBLIC_TOKEN");
13233
+ var getRivetkitRuntime = () => getEnvUniversal("RIVETKIT_RUNTIME");
13234
+ var getRivetkitRuntimeMode = () => {
13235
+ const value = getEnvUniversal("RIVETKIT_RUNTIME_MODE");
13236
+ if (value === void 0) return "envoy";
13237
+ if (value === "envoy" || value === "serverless") return value;
13238
+ throw new Error(
13239
+ `RIVETKIT_RUNTIME_MODE env var must be "envoy" or "serverless"; got "${value}"`
13240
+ );
13241
+ };
13242
+ var getRivetkitPublicDir = () => {
13243
+ const value = getEnvUniversal("RIVETKIT_PUBLIC_DIR");
13244
+ return value === void 0 || value === "" ? void 0 : value;
13245
+ };
13246
+ function parsePortEnv(raw) {
13247
+ if (raw === void 0 || raw === "") return void 0;
13248
+ const parsed = Number.parseInt(raw, 10);
13249
+ if (!Number.isFinite(parsed) || parsed < 1 || parsed > 65535 || String(parsed) !== raw.trim()) {
13250
+ throw new Error(
13251
+ `RIVET_PORT env var must be an integer between 1 and 65535; got "${raw}"`
13252
+ );
13013
13253
  }
13014
- return flattened;
13254
+ return parsed;
13015
13255
  }
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
- );
13029
- }
13030
- const schema = nestedSchema ?? flatSchema;
13031
- if (schema !== void 0) {
13032
- flattened[name] = schema;
13033
- }
13034
- }
13035
- return flattened;
13256
+ var getLogLevel = () => getEnvUniversal("RIVET_LOG_LEVEL") ?? getEnvUniversal("LOG_LEVEL");
13257
+ var getLogTarget = () => getEnvUniversal("RIVET_LOG_TARGET") === "1";
13258
+ var getLogTimestamp = () => getEnvUniversal("RIVET_LOG_TIMESTAMP") === "1";
13259
+ var getLogMessage = () => getEnvUniversal("RIVET_LOG_MESSAGE") === "1";
13260
+ var getLogErrorStack = () => getEnvUniversal("RIVET_LOG_ERROR_STACK") === "1";
13261
+ var getNodeEnv = () => getEnvUniversal("NODE_ENV");
13262
+ var getNextPhase = () => getEnvUniversal("NEXT_PHASE");
13263
+ var isDev = () => getNodeEnv() !== "production";
13264
+ function assertUnreachable(x) {
13265
+ throw new Error(`Unreachable case: ${x}`);
13036
13266
  }
13037
- function flattenActionTraceSamplers(actions, rates = {}) {
13038
- const handlers = flattenActionHandlers(actions);
13039
- const flattened = Object.fromEntries(flattenSampleRates(rates, []));
13040
- for (const name of Object.keys(flattened)) {
13041
- if (!Object.hasOwn(handlers, name)) {
13042
- throw new TypeError(
13043
- `tracing.actions.${name} does not name an action`
13044
- );
13267
+ function deconstructError(error46, exposeInternalError = false) {
13268
+ let statusCode;
13269
+ let public_;
13270
+ let group;
13271
+ let code;
13272
+ let message;
13273
+ let metadata;
13274
+ let rayId;
13275
+ let actor2;
13276
+ if (isCanonicalStructuredRivetError(error46)) {
13277
+ statusCode = typeof error46.statusCode === "number" ? error46.statusCode : error46.public ? 400 : 500;
13278
+ public_ = error46.public ?? false;
13279
+ group = error46.group;
13280
+ code = error46.code;
13281
+ message = error46.message;
13282
+ metadata = error46.metadata;
13283
+ rayId = error46.rayId;
13284
+ actor2 = error46.actor;
13285
+ } else if (RivetError.isActorError(error46) && error46.public) {
13286
+ statusCode = "statusCode" in error46 && error46.statusCode ? error46.statusCode : 400;
13287
+ public_ = true;
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 if (exposeInternalError) {
13295
+ if (RivetError.isActorError(error46)) {
13296
+ statusCode = 500;
13297
+ public_ = false;
13298
+ group = error46.group;
13299
+ code = error46.code;
13300
+ message = getErrorMessage(error46);
13301
+ metadata = error46.metadata;
13302
+ rayId = error46.rayId;
13303
+ actor2 = error46.actor;
13304
+ } else {
13305
+ statusCode = 500;
13306
+ public_ = false;
13307
+ group = "rivetkit";
13308
+ code = INTERNAL_ERROR_CODE;
13309
+ message = getErrorMessage(error46);
13045
13310
  }
13046
- }
13047
- return flattened;
13048
- }
13049
- function flattenSampleRates(rates, path2) {
13050
- return Object.entries(rates).flatMap(
13051
- ([segment, rate]) => {
13052
- const childPath = [...path2, segment];
13053
- return typeof rate === "number" ? [[childPath.join("."), rate]] : flattenSampleRates(rate, childPath);
13311
+ } else {
13312
+ statusCode = 500;
13313
+ public_ = false;
13314
+ group = "rivetkit";
13315
+ code = INTERNAL_ERROR_CODE;
13316
+ message = INTERNAL_ERROR_DESCRIPTION;
13317
+ if (RivetError.isActorError(error46)) {
13318
+ actor2 = error46.actor;
13054
13319
  }
13055
- );
13056
- }
13057
- function collectActionEntries(actions) {
13058
- const entries = [];
13059
- const names = /* @__PURE__ */ new Set();
13060
- visitActionGroup(actions ?? {}, [], entries, names);
13061
- return entries;
13062
- }
13063
- function visitActionGroup(value, path2, entries, names) {
13064
- if (!isRecord(value)) {
13065
- throw new TypeError(
13066
- `${formatActionPath(path2)} must be an action handler or group`
13067
- );
13320
+ metadata = {
13321
+ //url: `https://dashboard.rivet.dev/projects/${actorMetadata.project.slug}/environments/${actorMetadata.environment.slug}/actors?actorId=${actorMetadata.actor.id}`,
13322
+ };
13068
13323
  }
13069
- for (const [segment, child] of Object.entries(value)) {
13070
- const childPath = [...path2, segment];
13071
- if (typeof child === "function") {
13072
- const name = childPath.join(".");
13073
- if (names.has(name)) {
13074
- throw new TypeError(
13075
- `Multiple action definitions flatten to \`${name}\``
13076
- );
13324
+ return {
13325
+ __type: "ActorError",
13326
+ statusCode,
13327
+ public: public_,
13328
+ group,
13329
+ code,
13330
+ message,
13331
+ metadata,
13332
+ rayId,
13333
+ actor: actor2
13334
+ };
13335
+ }
13336
+ function stringifyError(error46) {
13337
+ if (error46 instanceof Error) {
13338
+ if (typeof process !== "undefined" && getLogErrorStack()) {
13339
+ let stack;
13340
+ try {
13341
+ stack = error46.stack;
13342
+ } catch {
13343
+ stack = void 0;
13077
13344
  }
13078
- names.add(name);
13079
- entries.push({
13080
- name,
13081
- path: childPath,
13082
- handler: child
13083
- });
13345
+ return `${error46.name}: ${error46.message}${stack ? `
13346
+ ${stack}` : ""}`;
13084
13347
  } else {
13085
- visitActionGroup(child, childPath, entries, names);
13348
+ return `${error46.name}: ${error46.message}`;
13086
13349
  }
13087
- }
13088
- }
13089
- function lookupNestedSchema(schemas, path2) {
13090
- let value = schemas;
13091
- for (const segment of path2) {
13092
- if (!isRecord(value) || !Object.hasOwn(value, segment)) {
13093
- return void 0;
13350
+ } else if (typeof error46 === "string") {
13351
+ return error46;
13352
+ } else if (typeof error46 === "object" && error46 !== null) {
13353
+ try {
13354
+ return `${JSON.stringify(error46)}`;
13355
+ } catch {
13356
+ return "[cannot stringify error]";
13094
13357
  }
13095
- value = value[segment];
13358
+ } else {
13359
+ return `Unknown error: ${getErrorMessage(error46)}`;
13096
13360
  }
13097
- return value;
13098
13361
  }
13099
- function isRecord(value) {
13100
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
13101
- return false;
13362
+ function getErrorMessage(err) {
13363
+ if (err && typeof err === "object" && "message" in err && typeof err.message === "string") {
13364
+ return err.message;
13365
+ } else {
13366
+ return String(err);
13102
13367
  }
13103
- const prototype = Object.getPrototypeOf(value);
13104
- return prototype === Object.prototype || prototype === null;
13105
13368
  }
13106
- function formatActionPath(path2) {
13107
- return path2.length === 0 ? "actions" : `Action \`${path2.join(".")}\``;
13108
- }
13109
- var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
13110
- var ACTOR_CONTEXT_INTERNAL_SYMBOL = /* @__PURE__ */ Symbol(
13111
- "rivetkit.actor_context_internal"
13112
- );
13113
- var RAW_STATE_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.raw_state");
13114
- var CONN_STATE_MANAGER_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.conn_state_manager");
13115
- var zFunction = () => external_exports.custom((val) => typeof val === "function");
13116
- var zActionTree = external_exports.custom((value) => {
13117
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
13118
- return false;
13119
- }
13120
- const prototype = Object.getPrototypeOf(value);
13121
- return prototype === Object.prototype || prototype === null;
13122
- }).superRefine((actions, ctx) => {
13123
- try {
13124
- flattenActionHandlers(actions);
13125
- } catch (error46) {
13126
- ctx.addIssue({
13127
- code: "custom",
13128
- message: error46 instanceof Error ? error46.message : "Invalid action definition"
13129
- });
13130
- }
13131
- });
13132
- var WorkflowInspectorConfigSchema = external_exports.object({
13133
- getHistory: zFunction(),
13134
- getState: zFunction().optional(),
13135
- onHistoryUpdated: zFunction().optional(),
13136
- replayFromStep: zFunction().optional()
13137
- });
13138
- var RunInspectorConfigSchema = external_exports.object({
13139
- workflow: WorkflowInspectorConfigSchema.optional()
13140
- }).optional();
13141
- var BUILTIN_INSPECTOR_TAB_IDS = [
13142
- "workflow",
13143
- "database",
13144
- "state",
13145
- "queue",
13146
- "schedules",
13147
- "connections",
13148
- "console"
13149
- ];
13150
- var BuiltinInspectorTabIdSchema = external_exports.enum(BUILTIN_INSPECTOR_TAB_IDS);
13151
- var CUSTOM_INSPECTOR_TAB_ID_RE = /^[A-Za-z0-9_-]+$/;
13152
- var CustomInspectorTabEntrySchema = external_exports.object({
13153
- id: external_exports.string().regex(
13154
- CUSTOM_INSPECTOR_TAB_ID_RE,
13155
- "inspector.tabs[].id must contain only letters, digits, underscore, or dash"
13156
- ),
13157
- label: external_exports.string().min(1),
13158
- source: external_exports.string().min(1),
13159
- /**
13160
- * Optional icon id. The dashboard maps strings to glyphs (see its
13161
- * icon registry); unknown ids fall back to a generic icon.
13162
- */
13163
- icon: external_exports.string().min(1).optional(),
13164
- hidden: external_exports.literal(false).optional()
13165
- }).strict();
13166
- var HideInspectorTabEntrySchema = external_exports.object({
13167
- id: BuiltinInspectorTabIdSchema,
13168
- hidden: external_exports.literal(true)
13169
- }).strict();
13170
- var InspectorTabEntrySchema = external_exports.union([
13171
- CustomInspectorTabEntrySchema,
13172
- HideInspectorTabEntrySchema
13173
- ]);
13174
- var ActorInspectorConfigSchema = external_exports.object({
13175
- tabs: external_exports.array(InspectorTabEntrySchema).default(() => [])
13176
- }).strict().refine(
13177
- (data) => {
13178
- const ids = data.tabs.map((t) => t.id);
13179
- return new Set(ids).size === ids.length;
13180
- },
13181
- { message: "Duplicate id in inspector.tabs", path: ["tabs"] }
13182
- ).refine(
13183
- (data) => {
13184
- const builtinSet = new Set(BUILTIN_INSPECTOR_TAB_IDS);
13185
- return data.tabs.every(
13186
- (t) => t.hidden === true || !builtinSet.has(t.id)
13187
- );
13188
- },
13189
- {
13190
- message: "Custom inspector tab id collides with a built-in (use hidden: true to hide a built-in)",
13191
- path: ["tabs"]
13192
- }
13193
- );
13194
- var RunConfigSchema = external_exports.object({
13195
- /** Display name for the actor in the Inspector UI. */
13196
- name: external_exports.string().optional(),
13197
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
13198
- icon: external_exports.string().optional(),
13199
- /** The run handler function. */
13200
- run: zFunction(),
13201
- /** Inspector integration for long-running run handlers. */
13202
- inspector: RunInspectorConfigSchema.optional()
13203
- });
13204
- var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("rivetkit.run_function_config");
13205
- function defineRunHandler(run, options) {
13206
- if (options.inspectorKind === void 0 !== (options.createInspector === void 0)) {
13207
- throw new TypeError(
13208
- "defineRunHandler requires inspectorKind and createInspector together"
13209
- );
13210
- }
13211
- Object.defineProperty(run, RUN_FUNCTION_CONFIG_SYMBOL, {
13212
- configurable: false,
13213
- enumerable: false,
13214
- writable: false,
13215
- value: {
13216
- name: options.name,
13217
- icon: options.icon,
13218
- inspectorKind: options.inspectorKind,
13219
- createInspector: options.createInspector
13220
- }
13221
- });
13222
- return run;
13223
- }
13224
- function getRunInspectorKind(run) {
13225
- var _a2;
13226
- if (!run || typeof run !== "function") return void 0;
13227
- return (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.inspectorKind;
13228
- }
13229
- function createRunInspector(run, context2) {
13230
- var _a2, _b;
13231
- if (!run || typeof run !== "function") return void 0;
13232
- return (_b = (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.createInspector) == null ? void 0 : _b.call(_a2, context2);
13233
- }
13234
- var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
13235
- function getRunFunction(run) {
13236
- if (!run) return void 0;
13237
- if (typeof run === "function") return run;
13238
- return run.run;
13239
- }
13240
- function getRunMetadata(run) {
13241
- if (!run) return {};
13242
- if (typeof run === "function") {
13243
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13244
- if (!config3) return {};
13245
- return { name: config3.name, icon: config3.icon };
13246
- }
13247
- return { name: run.name, icon: run.icon };
13248
- }
13249
- function getRunInspectorConfig(run, actor2) {
13250
- if (!run) return void 0;
13251
- if (typeof run === "function") {
13252
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13253
- return (config3 == null ? void 0 : config3.inspectorFactory) ? config3.inspectorFactory(actor2) : config3 == null ? void 0 : config3.inspector;
13254
- }
13255
- return run.inspector;
13256
- }
13257
- function hasRunInspectorConfig(run) {
13258
- if (!run) return false;
13259
- if (typeof run !== "function") return run.inspector !== void 0;
13260
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13261
- 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;
13262
- }
13263
- function disposeRunInspector(run, actorId) {
13264
- var _a2;
13265
- if (!run || typeof run !== "function") {
13266
- return;
13267
- }
13268
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13269
- (_a2 = config3 == null ? void 0 : config3.disposeInspector) == null ? void 0 : _a2.call(config3, actorId);
13270
- }
13271
- var GlobalActorOptionsBaseSchema = external_exports.object({
13272
- /** Display name for the actor in the Inspector UI. */
13273
- name: external_exports.string().optional(),
13274
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
13275
- icon: external_exports.string().optional(),
13276
- /** Enables the experimental Actor Runtime Socket for this actor. */
13277
- enableActorRuntimeSocket: external_exports.boolean().default(false),
13278
- /**
13279
- * Can hibernate WebSockets for onWebSocket.
13280
- *
13281
- * WebSockets using actions/events are hibernatable by default.
13282
- *
13283
- * @experimental
13284
- **/
13285
- canHibernateWebSocket: external_exports.union([external_exports.boolean(), zFunction()]).default(false)
13286
- }).strict();
13287
- var GlobalActorOptionsSchema = GlobalActorOptionsBaseSchema.prefault(
13288
- () => ({})
13289
- );
13290
- var InstanceActorOptionsBaseSchema = external_exports.object({
13291
- createVarsTimeout: external_exports.number().positive().default(5e3),
13292
- createConnStateTimeout: external_exports.number().positive().default(5e3),
13293
- onBeforeConnectTimeout: external_exports.number().positive().default(5e3),
13294
- onConnectTimeout: external_exports.number().positive().default(5e3),
13295
- onMigrateTimeout: external_exports.number().positive().default(3e4),
13296
- sleepGracePeriod: external_exports.number().positive().default(DEFAULT_SLEEP_GRACE_PERIOD),
13297
- /** @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. */
13298
- onDestroyTimeout: external_exports.number().positive().optional(),
13299
- /** @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. */
13300
- waitUntilTimeout: external_exports.number().positive().optional(),
13301
- stateSaveInterval: external_exports.number().positive().default(1e3),
13302
- actionTimeout: external_exports.number().positive().default(6e4),
13303
- connectionLivenessTimeout: external_exports.number().positive().default(2500),
13304
- connectionLivenessInterval: external_exports.number().positive().default(5e3),
13305
- /** @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. */
13306
- noSleep: external_exports.boolean().default(false),
13307
- sleepTimeout: external_exports.number().positive().default(3e4),
13308
- maxQueueSize: external_exports.number().positive().default(1e3),
13309
- /** Maximum pending one-shot and recurring schedules. */
13310
- maxSchedules: external_exports.number().int().nonnegative().default(1e3),
13311
- maxQueueMessageSize: external_exports.number().positive().default(64 * 1024),
13312
- /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
13313
- preloadMaxWorkflowBytes: external_exports.number().nonnegative().optional(),
13314
- /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
13315
- preloadMaxConnectionsBytes: external_exports.number().nonnegative().optional()
13316
- }).strict();
13317
- var InstanceActorOptionsSchema = InstanceActorOptionsBaseSchema.prefault(() => ({}));
13318
- var ActorOptionsSchema = GlobalActorOptionsBaseSchema.extend(
13319
- InstanceActorOptionsBaseSchema.shape
13320
- ).strict().prefault(() => ({}));
13321
- var zSampleRate = external_exports.number().min(0).max(1);
13322
- var zActionSampleRates = external_exports.lazy(
13323
- () => external_exports.record(external_exports.string(), external_exports.union([zSampleRate, zActionSampleRates]))
13324
- );
13325
- var ActorConfigSchema = external_exports.object({
13326
- onCreate: zFunction().optional(),
13327
- onDestroy: zFunction().optional(),
13328
- onMigrate: zFunction().optional(),
13329
- onWake: zFunction().optional(),
13330
- onSleep: zFunction().optional(),
13331
- run: zRunHandler,
13332
- onStateChange: zFunction().optional(),
13333
- onBeforeConnect: zFunction().optional(),
13334
- onConnect: zFunction().optional(),
13335
- onDisconnect: zFunction().optional(),
13336
- onBeforeActionResponse: zFunction().optional(),
13337
- onRequest: zFunction().optional(),
13338
- onWebSocket: zFunction().optional(),
13339
- actions: zActionTree.default(() => ({})),
13340
- actionInputSchemas: external_exports.record(external_exports.string(), external_exports.any()).optional(),
13341
- tracing: external_exports.object({
13342
- sampler: zSampleRate.optional(),
13343
- actions: zActionSampleRates.optional()
13344
- }).strict().optional(),
13345
- connParamsSchema: external_exports.any().optional(),
13346
- events: external_exports.record(external_exports.string(), external_exports.any()).optional(),
13347
- queues: external_exports.record(external_exports.string(), external_exports.any()).optional(),
13348
- state: external_exports.any().optional(),
13349
- createState: zFunction().optional(),
13350
- connState: external_exports.any().optional(),
13351
- createConnState: zFunction().optional(),
13352
- vars: external_exports.any().optional(),
13353
- db: external_exports.any().optional(),
13354
- createVars: zFunction().optional(),
13355
- options: ActorOptionsSchema,
13356
- inspector: ActorInspectorConfigSchema.optional()
13357
- }).strict().refine(
13358
- (data) => !(data.state !== void 0 && data.createState !== void 0),
13359
- {
13360
- message: "Cannot define both 'state' and 'createState'",
13361
- path: ["state"]
13362
- }
13363
- ).refine(
13364
- (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
13365
- {
13366
- message: "Cannot define both 'connState' and 'createConnState'",
13367
- path: ["connState"]
13368
- }
13369
- ).refine(
13370
- (data) => !(data.vars !== void 0 && data.createVars !== void 0),
13371
- {
13372
- message: "Cannot define both 'vars' and 'createVars'",
13373
- path: ["vars"]
13374
- }
13375
- );
13376
- var DocActorOptionsSchema = external_exports.object({
13377
- name: external_exports.string().optional().describe("Display name for the actor in the Inspector UI."),
13378
- icon: external_exports.string().optional().describe(
13379
- "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
13380
- ),
13381
- enableActorRuntimeSocket: external_exports.boolean().optional().describe(
13382
- "Enables the experimental Actor Runtime Socket for this actor. Default: false"
13383
- ),
13384
- createVarsTimeout: external_exports.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
13385
- createConnStateTimeout: external_exports.number().optional().describe(
13386
- "Timeout in ms for createConnState handler. Default: 5000"
13387
- ),
13388
- onMigrateTimeout: external_exports.number().optional().describe("Timeout in ms for onMigrate handler. Default: 30000"),
13389
- onBeforeConnectTimeout: external_exports.number().optional().describe(
13390
- "Timeout in ms for onBeforeConnect handler. Default: 5000"
13391
- ),
13392
- onConnectTimeout: external_exports.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
13393
- sleepGracePeriod: external_exports.number().optional().describe(
13394
- `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}.`
13395
- ),
13396
- onDestroyTimeout: external_exports.number().optional().describe(
13397
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
13398
- ),
13399
- waitUntilTimeout: external_exports.number().optional().describe(
13400
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
13401
- ),
13402
- stateSaveInterval: external_exports.number().optional().describe(
13403
- "Interval in ms between automatic state saves. Default: 1000"
13404
- ),
13405
- actionTimeout: external_exports.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
13406
- connectionLivenessTimeout: external_exports.number().optional().describe(
13407
- "Timeout in ms for connection liveness checks. Default: 2500"
13408
- ),
13409
- connectionLivenessInterval: external_exports.number().optional().describe(
13410
- "Interval in ms between connection liveness checks. Default: 5000"
13411
- ),
13412
- noSleep: external_exports.boolean().optional().describe(
13413
- "Deprecated. If true, the actor will never sleep. Use c.keepAwake(promise) to scope keep-awake to a specific operation instead. Default: false"
13414
- ),
13415
- sleepTimeout: external_exports.number().optional().describe(
13416
- "Time in ms of inactivity before the actor sleeps. Default: 30000"
13417
- ),
13418
- maxQueueSize: external_exports.number().optional().describe(
13419
- "Maximum number of queue messages before rejecting new messages. Default: 1000"
13420
- ),
13421
- maxSchedules: external_exports.number().int().nonnegative().optional().describe(
13422
- "Maximum pending one-shot and recurring schedules before rejecting new schedules. Default: 1000"
13423
- ),
13424
- maxQueueMessageSize: external_exports.number().optional().describe(
13425
- "Maximum size of each queue message in bytes. Default: 65536"
13426
- ),
13427
- canHibernateWebSocket: external_exports.boolean().optional().describe(
13428
- "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
13429
- )
13430
- }).describe("Actor options for timeouts and behavior configuration.");
13431
- var DocActorConfigSchema = external_exports.object({
13432
- state: external_exports.unknown().optional().describe(
13433
- "Initial state value for the actor. Cannot be used with createState."
13434
- ),
13435
- createState: external_exports.unknown().optional().describe(
13436
- "Function to create initial state. Receives context and input. Cannot be used with state."
13437
- ),
13438
- connState: external_exports.unknown().optional().describe(
13439
- "Initial connection state value. Cannot be used with createConnState."
13440
- ),
13441
- createConnState: external_exports.unknown().optional().describe(
13442
- "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."
13443
- ),
13444
- vars: external_exports.unknown().optional().describe(
13445
- "Initial ephemeral variables value. Cannot be used with createVars."
13446
- ),
13447
- createVars: external_exports.unknown().optional().describe(
13448
- "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
13449
- ),
13450
- db: external_exports.unknown().optional().describe("Database provider instance for the actor."),
13451
- onCreate: external_exports.unknown().optional().describe(
13452
- "Called when the actor is first initialized. Use to initialize state."
13453
- ),
13454
- onDestroy: external_exports.unknown().optional().describe("Called when the actor is destroyed."),
13455
- onMigrate: external_exports.unknown().optional().describe(
13456
- "Called on every actor start after persisted state loads and before onWake. Use for repeatable schema migrations."
13457
- ),
13458
- onWake: external_exports.unknown().optional().describe(
13459
- "Called when the actor wakes up and is ready to receive connections and actions."
13460
- ),
13461
- onSleep: external_exports.unknown().optional().describe(
13462
- "Called when the actor is stopping or sleeping. Use to clean up resources."
13463
- ),
13464
- run: external_exports.unknown().optional().describe(
13465
- "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."
13466
- ),
13467
- onStateChange: external_exports.unknown().optional().describe(
13468
- "Called when the actor's state changes. State changes within this hook won't trigger recursion."
13469
- ),
13470
- onBeforeConnect: external_exports.unknown().optional().describe(
13471
- "Called before a client connects. Throw an error to reject the connection. The pending connection is not visible in c.conns while this runs."
13472
- ),
13473
- onConnect: external_exports.unknown().optional().describe(
13474
- "Called when a client successfully connects. The connection is visible in c.conns before this runs."
13475
- ),
13476
- onDisconnect: external_exports.unknown().optional().describe("Called when a client disconnects."),
13477
- onBeforeActionResponse: external_exports.unknown().optional().describe(
13478
- "Called before sending an action response. Use to transform output."
13479
- ),
13480
- onRequest: external_exports.unknown().optional().describe(
13481
- "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
13482
- ),
13483
- onWebSocket: external_exports.unknown().optional().describe(
13484
- "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
13485
- ),
13486
- actions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
13487
- "Tree of action names or nested groups to handler functions. Nested paths use dot-separated low-level action names. Defaults to an empty object."
13488
- ),
13489
- actionInputSchemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
13490
- "Optional schemas for validating action argument tuples in native runtimes. May mirror nested action groups or use dot-separated low-level action names."
13491
- ),
13492
- tracing: external_exports.unknown().optional().describe(
13493
- "Trace sampling for this actor: `sampler` is the share of its invocations that are recorded, from 0 to 1, with optional per-action rates under `actions`. A rate lowers what is recorded and never raises it. Defaults to the process sampler from OTEL_TRACES_SAMPLER."
13494
- ),
13495
- connParamsSchema: external_exports.unknown().optional().describe(
13496
- "Optional schema for validating connection params in native runtimes."
13497
- ),
13498
- events: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of event names to schemas."),
13499
- queues: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of queue names to schemas."),
13500
- options: DocActorOptionsSchema.optional()
13501
- }).describe("Actor configuration passed to the actor() function.");
13502
-
13503
- // ../rivetkit/dist/tsup/chunk-P2OFXH4G.js
13504
- var INTERNAL_ERROR_CODE = "internal_error";
13505
- var INTERNAL_ERROR_DESCRIPTION = "An internal error occurred";
13506
- var USER_ERROR_CODE = "user_error";
13507
- var BRIDGE_RIVET_ERROR_PREFIX = "__RIVET_ERROR_JSON__:";
13508
- function looksLikeRivetErrorOptions(value) {
13509
- return typeof value === "object" && value !== null && ("public" in value || "metadata" in value || "rayId" in value || "statusCode" in value || "actor" in value || "cause" in value);
13510
- }
13511
- function isTypedErrorTag(value) {
13512
- return value === "ActorError" || value === "RivetError";
13513
- }
13514
- function errorMessage(error46, fallback = String(error46)) {
13515
- if (error46 && typeof error46 === "object" && "message" in error46 && typeof error46.message === "string") {
13516
- return error46.message;
13517
- }
13518
- return fallback;
13519
- }
13520
- function isRivetErrorLike(error46) {
13521
- 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));
13522
- }
13523
- function isActorAbortedError(error46) {
13524
- return isRivetErrorLike(error46) && error46.group === "actor" && error46.code === "aborted";
13525
- }
13526
- function isActorSpecifier(value) {
13527
- 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");
13528
- }
13529
- var RivetError = class extends Error {
13530
- __type = "RivetError";
13531
- public;
13532
- metadata;
13533
- rayId;
13534
- statusCode;
13535
- actor;
13536
- group;
13537
- code;
13538
- static isRivetError(error46) {
13539
- return isRivetErrorLike(error46);
13540
- }
13541
- static isActorError(error46) {
13542
- return isRivetErrorLike(error46);
13543
- }
13544
- constructor(group, code, message, options) {
13545
- const normalized = looksLikeRivetErrorOptions(options) ? options : { metadata: options };
13546
- super(message, { cause: normalized.cause });
13547
- this.name = "RivetError";
13548
- this.group = group;
13549
- this.code = code;
13550
- this.public = normalized.public ?? false;
13551
- this.metadata = normalized.metadata;
13552
- this.rayId = normalized.rayId ?? void 0;
13553
- this.statusCode = normalized.statusCode ?? (this.public ? 400 : 500);
13554
- this.actor = normalized.actor;
13555
- }
13556
- toString() {
13557
- return this.message;
13558
- }
13559
- };
13560
- var UserError = class extends RivetError {
13561
- constructor(message, options) {
13562
- super("user", (options == null ? void 0 : options.code) ?? USER_ERROR_CODE, message, {
13563
- public: true,
13564
- metadata: options == null ? void 0 : options.metadata,
13565
- cause: options == null ? void 0 : options.cause
13566
- });
13567
- }
13568
- };
13569
- function toRivetError(error46, fallback) {
13570
- if (typeof error46 === "string") {
13571
- const bridged = decodeBridgeRivetError(error46);
13572
- if (bridged) {
13573
- return bridged;
13574
- }
13575
- }
13576
- if (error46 instanceof Error) {
13577
- const bridged = decodeBridgeRivetError(error46.message);
13578
- if (bridged) {
13579
- return bridged;
13580
- }
13581
- }
13582
- if (isRivetErrorLike(error46)) {
13583
- return new RivetError(error46.group, error46.code, error46.message, {
13584
- public: error46.public,
13585
- statusCode: error46.statusCode,
13586
- metadata: error46.metadata,
13587
- rayId: error46.rayId,
13588
- actor: error46.actor,
13589
- cause: error46 instanceof Error ? error46.cause : void 0
13590
- });
13591
- }
13592
- return new RivetError(
13593
- (fallback == null ? void 0 : fallback.group) ?? "actor",
13594
- (fallback == null ? void 0 : fallback.code) ?? INTERNAL_ERROR_CODE,
13595
- errorMessage(error46, (fallback == null ? void 0 : fallback.message) ?? "Unknown error"),
13596
- {
13597
- public: fallback == null ? void 0 : fallback.public,
13598
- statusCode: fallback == null ? void 0 : fallback.statusCode,
13599
- metadata: fallback == null ? void 0 : fallback.metadata,
13600
- rayId: fallback == null ? void 0 : fallback.rayId,
13601
- actor: fallback == null ? void 0 : fallback.actor,
13602
- cause: error46 instanceof Error ? error46 : void 0
13603
- }
13604
- );
13605
- }
13606
- function encodeBridgeRivetError(error46) {
13607
- return `${BRIDGE_RIVET_ERROR_PREFIX}${JSON.stringify({
13608
- group: error46.group,
13609
- code: error46.code,
13610
- message: error46.message,
13611
- metadata: error46.metadata,
13612
- rayId: error46.rayId,
13613
- public: error46.public,
13614
- statusCode: error46.statusCode,
13615
- actor: error46.actor
13616
- })}`;
13617
- }
13618
- function encodeErrorForBridge(error46) {
13619
- if (isCanonicalStructuredRivetError(error46)) {
13620
- return encodeBridgeRivetError(error46);
13621
- }
13622
- return String(error46);
13623
- }
13624
- function isCanonicalStructuredRivetError(error46) {
13625
- 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";
13626
- }
13627
- function decodeBridgeRivetErrorPayload(value) {
13628
- if (!value.startsWith(BRIDGE_RIVET_ERROR_PREFIX)) {
13629
- return void 0;
13630
- }
13631
- try {
13632
- const raw = JSON.parse(
13633
- value.slice(BRIDGE_RIVET_ERROR_PREFIX.length)
13634
- );
13635
- const payload = {
13636
- ...raw,
13637
- rayId: raw.rayId ?? void 0
13638
- };
13639
- if (!isRivetErrorLike(payload)) {
13640
- return void 0;
13641
- }
13642
- if (payload.actor !== void 0 && payload.actor !== null && !isActorSpecifier(payload.actor)) {
13643
- return void 0;
13644
- }
13645
- return payload;
13646
- } catch {
13647
- return void 0;
13648
- }
13649
- }
13650
- function decodeBridgeRivetError(value) {
13651
- const payload = decodeBridgeRivetErrorPayload(value);
13652
- if (!payload) {
13653
- return void 0;
13654
- }
13655
- return new RivetError(payload.group, payload.code, payload.message, {
13656
- metadata: payload.metadata,
13657
- rayId: payload.rayId,
13658
- public: payload.public,
13659
- statusCode: payload.statusCode,
13660
- actor: payload.actor ?? void 0
13661
- });
13662
- }
13663
- function invalidRequest(error46) {
13664
- return new RivetError(
13665
- "request",
13666
- "invalid",
13667
- `Invalid request: ${errorMessage(error46, String(error46))}`,
13668
- {
13669
- public: true,
13670
- cause: error46 instanceof Error ? error46 : void 0
13671
- }
13672
- );
13673
- }
13674
- function actorNotFound(identifier) {
13675
- return new RivetError(
13676
- "actor",
13677
- "not_found",
13678
- identifier ? `Actor not found: ${identifier} (https://www.rivet.dev/docs/clients/javascript)` : "Actor not found (https://www.rivet.dev/docs/clients/javascript)",
13679
- { public: true }
13680
- );
13681
- }
13682
- function forbiddenError() {
13683
- return new RivetError("auth", "forbidden", "Forbidden", {
13684
- public: true,
13685
- statusCode: 403
13686
- });
13687
- }
13688
- function unsupportedFeature(feature) {
13689
- return new RivetError(
13690
- "feature",
13691
- "unsupported",
13692
- `Unsupported feature: ${feature}`
13693
- );
13694
- }
13695
-
13696
- // ../rivetkit/dist/tsup/chunk-DHWZTUKA.js
13697
- var import_pino = require("pino");
13698
- var cbor = __toESM(require("cbor-x"), 1);
13699
- var import_invariant = __toESM(require_invariant(), 1);
13700
- var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
13701
- var getRivetEndpoint = () => getEnvUniversal("RIVET_ENDPOINT");
13702
- var getRivetToken = () => getEnvUniversal("RIVET_TOKEN");
13703
- var getRivetNamespace = () => getEnvUniversal("RIVET_NAMESPACE");
13704
- var getRivetPool = () => getEnvUniversal("RIVET_POOL");
13705
- var getRivetTotalSlots = () => {
13706
- const value = getEnvUniversal("RIVET_TOTAL_SLOTS");
13707
- return value !== void 0 ? parseInt(value, 10) : void 0;
13708
- };
13709
- var getRivetRunEngine = () => getEnvUniversal("RIVET_RUN_ENGINE") === "1";
13710
- var getRivetRunEngineHost = () => getEnvUniversal("RIVET_RUN_ENGINE_HOST");
13711
- var getRivetRunEnginePort = () => {
13712
- const value = getEnvUniversal("RIVET_RUN_ENGINE_PORT");
13713
- return value !== void 0 ? parseInt(value, 10) : void 0;
13714
- };
13715
- var getRivetRunEngineVersion = () => getEnvUniversal("RIVET_RUN_ENGINE_VERSION");
13716
- var getRivetRunServices = () => {
13717
- const value = getEnvUniversal("RIVET_RUN_SERVICES");
13718
- return value === void 0 ? void 0 : value === "1";
13719
- };
13720
- var getRivetEnvoyVersion = () => {
13721
- const value = getEnvUniversal("RIVET_ENVOY_VERSION");
13722
- return value !== void 0 ? parseInt(value, 10) : void 0;
13723
- };
13724
- var getRivetPublicEndpoint = () => getEnvUniversal("RIVET_PUBLIC_ENDPOINT");
13725
- var getRivetPublicToken = () => getEnvUniversal("RIVET_PUBLIC_TOKEN");
13726
- var getRivetkitRuntime = () => getEnvUniversal("RIVETKIT_RUNTIME");
13727
- var getRivetkitRuntimeMode = () => {
13728
- const value = getEnvUniversal("RIVETKIT_RUNTIME_MODE");
13729
- if (value === void 0) return "envoy";
13730
- if (value === "envoy" || value === "serverless") return value;
13731
- throw new Error(
13732
- `RIVETKIT_RUNTIME_MODE env var must be "envoy" or "serverless"; got "${value}"`
13733
- );
13734
- };
13735
- var getRivetkitPublicDir = () => {
13736
- const value = getEnvUniversal("RIVETKIT_PUBLIC_DIR");
13737
- return value === void 0 || value === "" ? void 0 : value;
13738
- };
13739
- function parsePortEnv(raw) {
13740
- if (raw === void 0 || raw === "") return void 0;
13741
- const parsed = Number.parseInt(raw, 10);
13742
- if (!Number.isFinite(parsed) || parsed < 1 || parsed > 65535 || String(parsed) !== raw.trim()) {
13743
- throw new Error(
13744
- `RIVET_PORT env var must be an integer between 1 and 65535; got "${raw}"`
13745
- );
13746
- }
13747
- return parsed;
13748
- }
13749
- var getLogLevel = () => getEnvUniversal("RIVET_LOG_LEVEL") ?? getEnvUniversal("LOG_LEVEL");
13750
- var getLogTarget = () => getEnvUniversal("RIVET_LOG_TARGET") === "1";
13751
- var getLogTimestamp = () => getEnvUniversal("RIVET_LOG_TIMESTAMP") === "1";
13752
- var getLogMessage = () => getEnvUniversal("RIVET_LOG_MESSAGE") === "1";
13753
- var getLogErrorStack = () => getEnvUniversal("RIVET_LOG_ERROR_STACK") === "1";
13754
- var getNodeEnv = () => getEnvUniversal("NODE_ENV");
13755
- var getNextPhase = () => getEnvUniversal("NEXT_PHASE");
13756
- var isDev = () => getNodeEnv() !== "production";
13757
- function assertUnreachable(x) {
13758
- throw new Error(`Unreachable case: ${x}`);
13759
- }
13760
- function deconstructError(error46, exposeInternalError = false) {
13761
- let statusCode;
13762
- let public_;
13763
- let group;
13764
- let code;
13765
- let message;
13766
- let metadata;
13767
- let rayId;
13768
- let actor2;
13769
- if (isCanonicalStructuredRivetError(error46)) {
13770
- statusCode = typeof error46.statusCode === "number" ? error46.statusCode : error46.public ? 400 : 500;
13771
- public_ = error46.public ?? false;
13772
- group = error46.group;
13773
- code = error46.code;
13774
- message = error46.message;
13775
- metadata = error46.metadata;
13776
- rayId = error46.rayId;
13777
- actor2 = error46.actor;
13778
- } else if (RivetError.isActorError(error46) && error46.public) {
13779
- statusCode = "statusCode" in error46 && error46.statusCode ? error46.statusCode : 400;
13780
- public_ = true;
13781
- group = error46.group;
13782
- code = error46.code;
13783
- message = getErrorMessage(error46);
13784
- metadata = error46.metadata;
13785
- rayId = error46.rayId;
13786
- actor2 = error46.actor;
13787
- } else if (exposeInternalError) {
13788
- if (RivetError.isActorError(error46)) {
13789
- statusCode = 500;
13790
- public_ = false;
13791
- group = error46.group;
13792
- code = error46.code;
13793
- message = getErrorMessage(error46);
13794
- metadata = error46.metadata;
13795
- rayId = error46.rayId;
13796
- actor2 = error46.actor;
13797
- } else {
13798
- statusCode = 500;
13799
- public_ = false;
13800
- group = "rivetkit";
13801
- code = INTERNAL_ERROR_CODE;
13802
- message = getErrorMessage(error46);
13803
- }
13804
- } else {
13805
- statusCode = 500;
13806
- public_ = false;
13807
- group = "rivetkit";
13808
- code = INTERNAL_ERROR_CODE;
13809
- message = INTERNAL_ERROR_DESCRIPTION;
13810
- if (RivetError.isActorError(error46)) {
13811
- actor2 = error46.actor;
13812
- }
13813
- metadata = {
13814
- //url: `https://dashboard.rivet.dev/projects/${actorMetadata.project.slug}/environments/${actorMetadata.environment.slug}/actors?actorId=${actorMetadata.actor.id}`,
13815
- };
13816
- }
13817
- return {
13818
- __type: "ActorError",
13819
- statusCode,
13820
- public: public_,
13821
- group,
13822
- code,
13823
- message,
13824
- metadata,
13825
- rayId,
13826
- actor: actor2
13827
- };
13828
- }
13829
- function stringifyError(error46) {
13830
- if (error46 instanceof Error) {
13831
- if (typeof process !== "undefined" && getLogErrorStack()) {
13832
- let stack;
13833
- try {
13834
- stack = error46.stack;
13835
- } catch {
13836
- stack = void 0;
13837
- }
13838
- return `${error46.name}: ${error46.message}${stack ? `
13839
- ${stack}` : ""}`;
13840
- } else {
13841
- return `${error46.name}: ${error46.message}`;
13842
- }
13843
- } else if (typeof error46 === "string") {
13844
- return error46;
13845
- } else if (typeof error46 === "object" && error46 !== null) {
13846
- try {
13847
- return `${JSON.stringify(error46)}`;
13848
- } catch {
13849
- return "[cannot stringify error]";
13850
- }
13851
- } else {
13852
- return `Unknown error: ${getErrorMessage(error46)}`;
13853
- }
13854
- }
13855
- function getErrorMessage(err) {
13856
- if (err && typeof err === "object" && "message" in err && typeof err.message === "string") {
13857
- return err.message;
13858
- } else {
13859
- return String(err);
13860
- }
13861
- }
13862
- function noopNext() {
13863
- return async () => {
13864
- };
13369
+ function noopNext() {
13370
+ return async () => {
13371
+ };
13865
13372
  }
13866
13373
  var package_default = {
13867
13374
  name: "rivetkit",
13868
- version: "2.3.20",
13375
+ version: "2.3.21",
13869
13376
  description: "Lightweight libraries for building stateful actors on edge platforms",
13870
13377
  license: "Apache-2.0",
13871
13378
  keywords: [
@@ -14078,6 +13585,7 @@ var package_default = {
14078
13585
  "@rivet-dev/agent-os-core": "^0.1.1",
14079
13586
  "@rivet-dev/services": "^0.1.5",
14080
13587
  "@rivetkit/bare-ts": "^0.6.2",
13588
+ "@rivetkit/engine-api-full": "workspace:*",
14081
13589
  "@rivetkit/engine-cli": "workspace:*",
14082
13590
  "@rivetkit/engine-envoy-protocol": "workspace:*",
14083
13591
  "@rivetkit/on-change": "6.0.1",
@@ -15171,7 +14679,7 @@ function Config({ initialBufferLength = 1024, maxBufferLength = 1024 * 1024 * 32
15171
14679
  };
15172
14680
  }
15173
14681
 
15174
- // ../rivetkit/dist/tsup/chunk-SNNVRHLX.js
14682
+ // ../rivetkit/dist/tsup/chunk-CJXBGTVT.js
15175
14683
  var config2 = /* @__PURE__ */ Config({});
15176
14684
  function readWorkflowCbor(bc) {
15177
14685
  return readData(bc);
@@ -15294,180 +14802,675 @@ function readWorkflowSleepEntry(bc) {
15294
14802
  state: readWorkflowSleepState(bc)
15295
14803
  };
15296
14804
  }
15297
- function readWorkflowMessageEntry(bc) {
15298
- return {
15299
- name: readString(bc),
15300
- messageData: readWorkflowCbor(bc)
15301
- };
14805
+ function readWorkflowMessageEntry(bc) {
14806
+ return {
14807
+ name: readString(bc),
14808
+ messageData: readWorkflowCbor(bc)
14809
+ };
14810
+ }
14811
+ function readWorkflowRollbackCheckpointEntry(bc) {
14812
+ return {
14813
+ name: readString(bc)
14814
+ };
14815
+ }
14816
+ function readWorkflowBranchStatus(bc) {
14817
+ return {
14818
+ status: readWorkflowBranchStatusType(bc),
14819
+ output: read0(bc),
14820
+ error: read1(bc)
14821
+ };
14822
+ }
14823
+ function read2(bc) {
14824
+ const len = readUintSafe(bc);
14825
+ const result = /* @__PURE__ */ new Map();
14826
+ for (let i = 0; i < len; i++) {
14827
+ const offset = bc.offset;
14828
+ const key = readString(bc);
14829
+ if (result.has(key)) {
14830
+ bc.offset = offset;
14831
+ throw new BareError(offset, "duplicated key");
14832
+ }
14833
+ result.set(key, readWorkflowBranchStatus(bc));
14834
+ }
14835
+ return result;
14836
+ }
14837
+ function readWorkflowJoinEntry(bc) {
14838
+ return {
14839
+ branches: read2(bc)
14840
+ };
14841
+ }
14842
+ function readWorkflowRaceEntry(bc) {
14843
+ return {
14844
+ winner: read1(bc),
14845
+ branches: read2(bc)
14846
+ };
14847
+ }
14848
+ function readWorkflowRemovedEntry(bc) {
14849
+ return {
14850
+ originalType: readString(bc),
14851
+ originalName: read1(bc)
14852
+ };
14853
+ }
14854
+ function readWorkflowVersionCheckEntry(bc) {
14855
+ return {
14856
+ resolved: readU32(bc),
14857
+ latest: readU32(bc)
14858
+ };
14859
+ }
14860
+ function readWorkflowEntryKind(bc) {
14861
+ const offset = bc.offset;
14862
+ const tag = readU8(bc);
14863
+ switch (tag) {
14864
+ case 0:
14865
+ return { tag: "WorkflowStepEntry", val: readWorkflowStepEntry(bc) };
14866
+ case 1:
14867
+ return { tag: "WorkflowLoopEntry", val: readWorkflowLoopEntry(bc) };
14868
+ case 2:
14869
+ return {
14870
+ tag: "WorkflowSleepEntry",
14871
+ val: readWorkflowSleepEntry(bc)
14872
+ };
14873
+ case 3:
14874
+ return {
14875
+ tag: "WorkflowMessageEntry",
14876
+ val: readWorkflowMessageEntry(bc)
14877
+ };
14878
+ case 4:
14879
+ return {
14880
+ tag: "WorkflowRollbackCheckpointEntry",
14881
+ val: readWorkflowRollbackCheckpointEntry(bc)
14882
+ };
14883
+ case 5:
14884
+ return { tag: "WorkflowJoinEntry", val: readWorkflowJoinEntry(bc) };
14885
+ case 6:
14886
+ return { tag: "WorkflowRaceEntry", val: readWorkflowRaceEntry(bc) };
14887
+ case 7:
14888
+ return {
14889
+ tag: "WorkflowRemovedEntry",
14890
+ val: readWorkflowRemovedEntry(bc)
14891
+ };
14892
+ case 8:
14893
+ return {
14894
+ tag: "WorkflowVersionCheckEntry",
14895
+ val: readWorkflowVersionCheckEntry(bc)
14896
+ };
14897
+ default: {
14898
+ bc.offset = offset;
14899
+ throw new BareError(offset, "invalid tag");
14900
+ }
14901
+ }
14902
+ }
14903
+ function readWorkflowEntry(bc) {
14904
+ return {
14905
+ id: readString(bc),
14906
+ location: readWorkflowLocation(bc),
14907
+ kind: readWorkflowEntryKind(bc)
14908
+ };
14909
+ }
14910
+ function read3(bc) {
14911
+ return readBool(bc) ? readU64(bc) : null;
14912
+ }
14913
+ function readWorkflowEntryMetadata(bc) {
14914
+ return {
14915
+ status: readWorkflowEntryStatus(bc),
14916
+ error: read1(bc),
14917
+ attempts: readU32(bc),
14918
+ lastAttemptAt: readU64(bc),
14919
+ createdAt: readU64(bc),
14920
+ completedAt: read3(bc),
14921
+ rollbackCompletedAt: read3(bc),
14922
+ rollbackError: read1(bc)
14923
+ };
14924
+ }
14925
+ function read4(bc) {
14926
+ const len = readUintSafe(bc);
14927
+ if (len === 0) {
14928
+ return [];
14929
+ }
14930
+ const result = [readString(bc)];
14931
+ for (let i = 1; i < len; i++) {
14932
+ result[i] = readString(bc);
14933
+ }
14934
+ return result;
14935
+ }
14936
+ function read5(bc) {
14937
+ const len = readUintSafe(bc);
14938
+ if (len === 0) {
14939
+ return [];
14940
+ }
14941
+ const result = [readWorkflowEntry(bc)];
14942
+ for (let i = 1; i < len; i++) {
14943
+ result[i] = readWorkflowEntry(bc);
14944
+ }
14945
+ return result;
14946
+ }
14947
+ function read6(bc) {
14948
+ const len = readUintSafe(bc);
14949
+ const result = /* @__PURE__ */ new Map();
14950
+ for (let i = 0; i < len; i++) {
14951
+ const offset = bc.offset;
14952
+ const key = readString(bc);
14953
+ if (result.has(key)) {
14954
+ bc.offset = offset;
14955
+ throw new BareError(offset, "duplicated key");
14956
+ }
14957
+ result.set(key, readWorkflowEntryMetadata(bc));
14958
+ }
14959
+ return result;
14960
+ }
14961
+ function readWorkflowHistory(bc) {
14962
+ return {
14963
+ nameRegistry: read4(bc),
14964
+ entries: read5(bc),
14965
+ entryMetadata: read6(bc)
14966
+ };
14967
+ }
14968
+ function decodeWorkflowHistory(bytes) {
14969
+ const bc = new ByteCursor(bytes, config2);
14970
+ const result = readWorkflowHistory(bc);
14971
+ if (bc.offset < bc.view.byteLength) {
14972
+ throw new BareError(bc.offset, "remaining bytes");
14973
+ }
14974
+ return result;
14975
+ }
14976
+ function decodeWorkflowHistoryTransport(data) {
14977
+ return decodeWorkflowHistory(toUint8Array(data));
14978
+ }
14979
+
14980
+ // ../rivetkit/dist/tsup/chunk-CSOHAAZK.js
14981
+ function flattenActionHandlers(actions) {
14982
+ const flattened = /* @__PURE__ */ Object.create(null);
14983
+ for (const { name, handler } of collectActionEntries(actions)) {
14984
+ flattened[name] = handler;
14985
+ }
14986
+ return flattened;
14987
+ }
14988
+ function flattenActionInputSchemas(actions, schemas) {
14989
+ if (schemas === void 0) return void 0;
14990
+ if (!isRecord(schemas)) {
14991
+ throw new TypeError("actionInputSchemas must be an object");
14992
+ }
14993
+ const flattened = /* @__PURE__ */ Object.create(null);
14994
+ for (const { name, path: path2 } of collectActionEntries(actions)) {
14995
+ const nestedSchema = lookupNestedSchema(schemas, path2);
14996
+ const flatSchema = schemas[name];
14997
+ if (nestedSchema !== void 0 && flatSchema !== void 0 && nestedSchema !== flatSchema) {
14998
+ throw new TypeError(
14999
+ `Action input schema \`${name}\` is defined by both a nested path and a dotted key`
15000
+ );
15001
+ }
15002
+ const schema = nestedSchema ?? flatSchema;
15003
+ if (schema !== void 0) {
15004
+ flattened[name] = schema;
15005
+ }
15006
+ }
15007
+ return flattened;
15008
+ }
15009
+ function flattenActionTraceSamplers(actions, rates = {}) {
15010
+ const handlers = flattenActionHandlers(actions);
15011
+ const flattened = Object.fromEntries(flattenSampleRates(rates, []));
15012
+ for (const name of Object.keys(flattened)) {
15013
+ if (!Object.hasOwn(handlers, name)) {
15014
+ throw new TypeError(
15015
+ `tracing.actions.${name} does not name an action`
15016
+ );
15017
+ }
15018
+ }
15019
+ return flattened;
15302
15020
  }
15303
- function readWorkflowRollbackCheckpointEntry(bc) {
15304
- return {
15305
- name: readString(bc)
15306
- };
15021
+ function flattenSampleRates(rates, path2) {
15022
+ return Object.entries(rates).flatMap(
15023
+ ([segment, rate]) => {
15024
+ const childPath = [...path2, segment];
15025
+ return typeof rate === "number" ? [[childPath.join("."), rate]] : flattenSampleRates(rate, childPath);
15026
+ }
15027
+ );
15307
15028
  }
15308
- function readWorkflowBranchStatus(bc) {
15309
- return {
15310
- status: readWorkflowBranchStatusType(bc),
15311
- output: read0(bc),
15312
- error: read1(bc)
15313
- };
15029
+ function collectActionEntries(actions) {
15030
+ const entries = [];
15031
+ const names = /* @__PURE__ */ new Set();
15032
+ visitActionGroup(actions ?? {}, [], entries, names);
15033
+ return entries;
15314
15034
  }
15315
- function read2(bc) {
15316
- const len = readUintSafe(bc);
15317
- const result = /* @__PURE__ */ new Map();
15318
- for (let i = 0; i < len; i++) {
15319
- const offset = bc.offset;
15320
- const key = readString(bc);
15321
- if (result.has(key)) {
15322
- bc.offset = offset;
15323
- throw new BareError(offset, "duplicated key");
15035
+ function visitActionGroup(value, path2, entries, names) {
15036
+ if (!isRecord(value)) {
15037
+ throw new TypeError(
15038
+ `${formatActionPath(path2)} must be an action handler or group`
15039
+ );
15040
+ }
15041
+ for (const [segment, child] of Object.entries(value)) {
15042
+ const childPath = [...path2, segment];
15043
+ if (typeof child === "function") {
15044
+ const name = childPath.join(".");
15045
+ if (names.has(name)) {
15046
+ throw new TypeError(
15047
+ `Multiple action definitions flatten to \`${name}\``
15048
+ );
15049
+ }
15050
+ names.add(name);
15051
+ entries.push({
15052
+ name,
15053
+ path: childPath,
15054
+ handler: child
15055
+ });
15056
+ } else {
15057
+ visitActionGroup(child, childPath, entries, names);
15324
15058
  }
15325
- result.set(key, readWorkflowBranchStatus(bc));
15326
15059
  }
15327
- return result;
15328
- }
15329
- function readWorkflowJoinEntry(bc) {
15330
- return {
15331
- branches: read2(bc)
15332
- };
15333
15060
  }
15334
- function readWorkflowRaceEntry(bc) {
15335
- return {
15336
- winner: read1(bc),
15337
- branches: read2(bc)
15338
- };
15061
+ function lookupNestedSchema(schemas, path2) {
15062
+ let value = schemas;
15063
+ for (const segment of path2) {
15064
+ if (!isRecord(value) || !Object.hasOwn(value, segment)) {
15065
+ return void 0;
15066
+ }
15067
+ value = value[segment];
15068
+ }
15069
+ return value;
15339
15070
  }
15340
- function readWorkflowRemovedEntry(bc) {
15341
- return {
15342
- originalType: readString(bc),
15343
- originalName: read1(bc)
15344
- };
15071
+ function isRecord(value) {
15072
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
15073
+ return false;
15074
+ }
15075
+ const prototype = Object.getPrototypeOf(value);
15076
+ return prototype === Object.prototype || prototype === null;
15345
15077
  }
15346
- function readWorkflowVersionCheckEntry(bc) {
15347
- return {
15348
- resolved: readU32(bc),
15349
- latest: readU32(bc)
15350
- };
15078
+ function formatActionPath(path2) {
15079
+ return path2.length === 0 ? "actions" : `Action \`${path2.join(".")}\``;
15351
15080
  }
15352
- function readWorkflowEntryKind(bc) {
15353
- const offset = bc.offset;
15354
- const tag = readU8(bc);
15355
- switch (tag) {
15356
- case 0:
15357
- return { tag: "WorkflowStepEntry", val: readWorkflowStepEntry(bc) };
15358
- case 1:
15359
- return { tag: "WorkflowLoopEntry", val: readWorkflowLoopEntry(bc) };
15360
- case 2:
15361
- return {
15362
- tag: "WorkflowSleepEntry",
15363
- val: readWorkflowSleepEntry(bc)
15364
- };
15365
- case 3:
15366
- return {
15367
- tag: "WorkflowMessageEntry",
15368
- val: readWorkflowMessageEntry(bc)
15369
- };
15370
- case 4:
15371
- return {
15372
- tag: "WorkflowRollbackCheckpointEntry",
15373
- val: readWorkflowRollbackCheckpointEntry(bc)
15374
- };
15375
- case 5:
15376
- return { tag: "WorkflowJoinEntry", val: readWorkflowJoinEntry(bc) };
15377
- case 6:
15378
- return { tag: "WorkflowRaceEntry", val: readWorkflowRaceEntry(bc) };
15379
- case 7:
15380
- return {
15381
- tag: "WorkflowRemovedEntry",
15382
- val: readWorkflowRemovedEntry(bc)
15383
- };
15384
- case 8:
15385
- return {
15386
- tag: "WorkflowVersionCheckEntry",
15387
- val: readWorkflowVersionCheckEntry(bc)
15388
- };
15389
- default: {
15390
- bc.offset = offset;
15391
- throw new BareError(offset, "invalid tag");
15392
- }
15081
+ var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
15082
+ var ACTOR_CONTEXT_INTERNAL_SYMBOL = /* @__PURE__ */ Symbol(
15083
+ "rivetkit.actor_context_internal"
15084
+ );
15085
+ var RAW_STATE_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.raw_state");
15086
+ var CONN_STATE_MANAGER_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.conn_state_manager");
15087
+ var zFunction = () => external_exports.custom((val) => typeof val === "function");
15088
+ var zActionTree = external_exports.custom((value) => {
15089
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
15090
+ return false;
15091
+ }
15092
+ const prototype = Object.getPrototypeOf(value);
15093
+ return prototype === Object.prototype || prototype === null;
15094
+ }).superRefine((actions, ctx) => {
15095
+ try {
15096
+ flattenActionHandlers(actions);
15097
+ } catch (error46) {
15098
+ ctx.addIssue({
15099
+ code: "custom",
15100
+ message: error46 instanceof Error ? error46.message : "Invalid action definition"
15101
+ });
15102
+ }
15103
+ });
15104
+ var WorkflowInspectorConfigSchema = external_exports.object({
15105
+ getHistory: zFunction(),
15106
+ getState: zFunction().optional(),
15107
+ onHistoryUpdated: zFunction().optional(),
15108
+ replayFromStep: zFunction().optional()
15109
+ });
15110
+ var RunInspectorConfigSchema = external_exports.object({
15111
+ workflow: WorkflowInspectorConfigSchema.optional()
15112
+ }).optional();
15113
+ var BUILTIN_INSPECTOR_TAB_IDS = [
15114
+ "workflow",
15115
+ "database",
15116
+ "state",
15117
+ "queue",
15118
+ "schedules",
15119
+ "connections",
15120
+ "console"
15121
+ ];
15122
+ var BuiltinInspectorTabIdSchema = external_exports.enum(BUILTIN_INSPECTOR_TAB_IDS);
15123
+ var CUSTOM_INSPECTOR_TAB_ID_RE = /^[A-Za-z0-9_-]+$/;
15124
+ var CustomInspectorTabEntrySchema = external_exports.object({
15125
+ id: external_exports.string().regex(
15126
+ CUSTOM_INSPECTOR_TAB_ID_RE,
15127
+ "inspector.tabs[].id must contain only letters, digits, underscore, or dash"
15128
+ ),
15129
+ label: external_exports.string().min(1),
15130
+ source: external_exports.string().min(1),
15131
+ /**
15132
+ * Optional icon id. The dashboard maps strings to glyphs (see its
15133
+ * icon registry); unknown ids fall back to a generic icon.
15134
+ */
15135
+ icon: external_exports.string().min(1).optional(),
15136
+ hidden: external_exports.literal(false).optional()
15137
+ }).strict();
15138
+ var HideInspectorTabEntrySchema = external_exports.object({
15139
+ id: BuiltinInspectorTabIdSchema,
15140
+ hidden: external_exports.literal(true)
15141
+ }).strict();
15142
+ var InspectorTabEntrySchema = external_exports.union([
15143
+ CustomInspectorTabEntrySchema,
15144
+ HideInspectorTabEntrySchema
15145
+ ]);
15146
+ var ActorInspectorConfigSchema = external_exports.object({
15147
+ tabs: external_exports.array(InspectorTabEntrySchema).default(() => [])
15148
+ }).strict().refine(
15149
+ (data) => {
15150
+ const ids = data.tabs.map((t) => t.id);
15151
+ return new Set(ids).size === ids.length;
15152
+ },
15153
+ { message: "Duplicate id in inspector.tabs", path: ["tabs"] }
15154
+ ).refine(
15155
+ (data) => {
15156
+ const builtinSet = new Set(BUILTIN_INSPECTOR_TAB_IDS);
15157
+ return data.tabs.every(
15158
+ (t) => t.hidden === true || !builtinSet.has(t.id)
15159
+ );
15160
+ },
15161
+ {
15162
+ message: "Custom inspector tab id collides with a built-in (use hidden: true to hide a built-in)",
15163
+ path: ["tabs"]
15164
+ }
15165
+ );
15166
+ var RunConfigSchema = external_exports.object({
15167
+ /** Display name for the actor in the Inspector UI. */
15168
+ name: external_exports.string().optional(),
15169
+ /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
15170
+ icon: external_exports.string().optional(),
15171
+ /** The run handler function. */
15172
+ run: zFunction(),
15173
+ /** Inspector integration for long-running run handlers. */
15174
+ inspector: RunInspectorConfigSchema.optional()
15175
+ });
15176
+ var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("rivetkit.run_function_config");
15177
+ function defineRunHandler(run, options) {
15178
+ if (options.inspectorKind === void 0 !== (options.createInspector === void 0)) {
15179
+ throw new TypeError(
15180
+ "defineRunHandler requires inspectorKind and createInspector together"
15181
+ );
15393
15182
  }
15183
+ Object.defineProperty(run, RUN_FUNCTION_CONFIG_SYMBOL, {
15184
+ configurable: false,
15185
+ enumerable: false,
15186
+ writable: false,
15187
+ value: {
15188
+ name: options.name,
15189
+ icon: options.icon,
15190
+ inspectorKind: options.inspectorKind,
15191
+ createInspector: options.createInspector
15192
+ }
15193
+ });
15194
+ return run;
15394
15195
  }
15395
- function readWorkflowEntry(bc) {
15396
- return {
15397
- id: readString(bc),
15398
- location: readWorkflowLocation(bc),
15399
- kind: readWorkflowEntryKind(bc)
15400
- };
15401
- }
15402
- function read3(bc) {
15403
- return readBool(bc) ? readU64(bc) : null;
15196
+ function getRunInspectorKind(run) {
15197
+ var _a2;
15198
+ if (!run || typeof run !== "function") return void 0;
15199
+ return (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.inspectorKind;
15404
15200
  }
15405
- function readWorkflowEntryMetadata(bc) {
15406
- return {
15407
- status: readWorkflowEntryStatus(bc),
15408
- error: read1(bc),
15409
- attempts: readU32(bc),
15410
- lastAttemptAt: readU64(bc),
15411
- createdAt: readU64(bc),
15412
- completedAt: read3(bc),
15413
- rollbackCompletedAt: read3(bc),
15414
- rollbackError: read1(bc)
15415
- };
15201
+ function createRunInspector(run, context2) {
15202
+ var _a2, _b;
15203
+ if (!run || typeof run !== "function") return void 0;
15204
+ return (_b = (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.createInspector) == null ? void 0 : _b.call(_a2, context2);
15416
15205
  }
15417
- function read4(bc) {
15418
- const len = readUintSafe(bc);
15419
- if (len === 0) {
15420
- return [];
15421
- }
15422
- const result = [readString(bc)];
15423
- for (let i = 1; i < len; i++) {
15424
- result[i] = readString(bc);
15425
- }
15426
- return result;
15206
+ var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
15207
+ function getRunFunction(run) {
15208
+ if (!run) return void 0;
15209
+ if (typeof run === "function") return run;
15210
+ return run.run;
15427
15211
  }
15428
- function read5(bc) {
15429
- const len = readUintSafe(bc);
15430
- if (len === 0) {
15431
- return [];
15432
- }
15433
- const result = [readWorkflowEntry(bc)];
15434
- for (let i = 1; i < len; i++) {
15435
- result[i] = readWorkflowEntry(bc);
15212
+ function getRunMetadata(run) {
15213
+ if (!run) return {};
15214
+ if (typeof run === "function") {
15215
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15216
+ if (!config3) return {};
15217
+ return { name: config3.name, icon: config3.icon };
15436
15218
  }
15437
- return result;
15219
+ return { name: run.name, icon: run.icon };
15438
15220
  }
15439
- function read6(bc) {
15440
- const len = readUintSafe(bc);
15441
- const result = /* @__PURE__ */ new Map();
15442
- for (let i = 0; i < len; i++) {
15443
- const offset = bc.offset;
15444
- const key = readString(bc);
15445
- if (result.has(key)) {
15446
- bc.offset = offset;
15447
- throw new BareError(offset, "duplicated key");
15448
- }
15449
- result.set(key, readWorkflowEntryMetadata(bc));
15221
+ function getRunInspectorConfig(run, actor2) {
15222
+ if (!run) return void 0;
15223
+ if (typeof run === "function") {
15224
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15225
+ return (config3 == null ? void 0 : config3.inspectorFactory) ? config3.inspectorFactory(actor2) : config3 == null ? void 0 : config3.inspector;
15450
15226
  }
15451
- return result;
15227
+ return run.inspector;
15452
15228
  }
15453
- function readWorkflowHistory(bc) {
15454
- return {
15455
- nameRegistry: read4(bc),
15456
- entries: read5(bc),
15457
- entryMetadata: read6(bc)
15458
- };
15229
+ function hasRunInspectorConfig(run) {
15230
+ if (!run) return false;
15231
+ if (typeof run !== "function") return run.inspector !== void 0;
15232
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15233
+ 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;
15459
15234
  }
15460
- function decodeWorkflowHistory(bytes) {
15461
- const bc = new ByteCursor(bytes, config2);
15462
- const result = readWorkflowHistory(bc);
15463
- if (bc.offset < bc.view.byteLength) {
15464
- throw new BareError(bc.offset, "remaining bytes");
15235
+ function disposeRunInspector(run, actorId) {
15236
+ var _a2;
15237
+ if (!run || typeof run !== "function") {
15238
+ return;
15465
15239
  }
15466
- return result;
15467
- }
15468
- function decodeWorkflowHistoryTransport(data) {
15469
- return decodeWorkflowHistory(toUint8Array(data));
15240
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15241
+ (_a2 = config3 == null ? void 0 : config3.disposeInspector) == null ? void 0 : _a2.call(config3, actorId);
15470
15242
  }
15243
+ var GlobalActorOptionsBaseSchema = external_exports.object({
15244
+ /** Display name for the actor in the Inspector UI. */
15245
+ name: external_exports.string().optional(),
15246
+ /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
15247
+ icon: external_exports.string().optional(),
15248
+ /** Enables the experimental Actor Runtime Socket for this actor. */
15249
+ enableActorRuntimeSocket: external_exports.boolean().default(false),
15250
+ /**
15251
+ * Can hibernate WebSockets for onWebSocket.
15252
+ *
15253
+ * WebSockets using actions/events are hibernatable by default.
15254
+ *
15255
+ * @experimental
15256
+ **/
15257
+ canHibernateWebSocket: external_exports.union([external_exports.boolean(), zFunction()]).default(false)
15258
+ }).strict();
15259
+ var GlobalActorOptionsSchema = GlobalActorOptionsBaseSchema.prefault(
15260
+ () => ({})
15261
+ );
15262
+ var InstanceActorOptionsBaseSchema = external_exports.object({
15263
+ createVarsTimeout: external_exports.number().positive().default(5e3),
15264
+ createConnStateTimeout: external_exports.number().positive().default(5e3),
15265
+ onBeforeConnectTimeout: external_exports.number().positive().default(5e3),
15266
+ onConnectTimeout: external_exports.number().positive().default(5e3),
15267
+ onMigrateTimeout: external_exports.number().positive().default(3e4),
15268
+ sleepGracePeriod: external_exports.number().positive().default(DEFAULT_SLEEP_GRACE_PERIOD),
15269
+ /** @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. */
15270
+ onDestroyTimeout: external_exports.number().positive().optional(),
15271
+ /** @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. */
15272
+ waitUntilTimeout: external_exports.number().positive().optional(),
15273
+ stateSaveInterval: external_exports.number().positive().default(1e3),
15274
+ actionTimeout: external_exports.number().positive().default(6e4),
15275
+ connectionLivenessTimeout: external_exports.number().positive().default(2500),
15276
+ connectionLivenessInterval: external_exports.number().positive().default(5e3),
15277
+ /** @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. */
15278
+ noSleep: external_exports.boolean().default(false),
15279
+ sleepTimeout: external_exports.number().positive().default(3e4),
15280
+ maxQueueSize: external_exports.number().positive().default(1e3),
15281
+ /** Maximum pending one-shot and recurring schedules. */
15282
+ maxSchedules: external_exports.number().int().nonnegative().default(1e3),
15283
+ maxQueueMessageSize: external_exports.number().positive().default(64 * 1024),
15284
+ /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
15285
+ preloadMaxWorkflowBytes: external_exports.number().nonnegative().optional(),
15286
+ /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
15287
+ preloadMaxConnectionsBytes: external_exports.number().nonnegative().optional()
15288
+ }).strict();
15289
+ var InstanceActorOptionsSchema = InstanceActorOptionsBaseSchema.prefault(() => ({}));
15290
+ var ActorOptionsSchema = GlobalActorOptionsBaseSchema.extend(
15291
+ InstanceActorOptionsBaseSchema.shape
15292
+ ).strict().prefault(() => ({}));
15293
+ var zSampleRate = external_exports.number().min(0).max(1);
15294
+ var zActionSampleRates = external_exports.lazy(
15295
+ () => external_exports.record(external_exports.string(), external_exports.union([zSampleRate, zActionSampleRates]))
15296
+ );
15297
+ var ActorConfigSchema = external_exports.object({
15298
+ onCreate: zFunction().optional(),
15299
+ onDestroy: zFunction().optional(),
15300
+ onMigrate: zFunction().optional(),
15301
+ onWake: zFunction().optional(),
15302
+ onSleep: zFunction().optional(),
15303
+ run: zRunHandler,
15304
+ onStateChange: zFunction().optional(),
15305
+ onBeforeConnect: zFunction().optional(),
15306
+ onConnect: zFunction().optional(),
15307
+ onDisconnect: zFunction().optional(),
15308
+ onBeforeActionResponse: zFunction().optional(),
15309
+ onRequest: zFunction().optional(),
15310
+ onWebSocket: zFunction().optional(),
15311
+ actions: zActionTree.default(() => ({})),
15312
+ actionInputSchemas: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15313
+ tracing: external_exports.object({
15314
+ sampler: zSampleRate.optional(),
15315
+ actions: zActionSampleRates.optional()
15316
+ }).strict().optional(),
15317
+ connParamsSchema: external_exports.any().optional(),
15318
+ events: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15319
+ queues: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15320
+ state: external_exports.any().optional(),
15321
+ createState: zFunction().optional(),
15322
+ connState: external_exports.any().optional(),
15323
+ createConnState: zFunction().optional(),
15324
+ vars: external_exports.any().optional(),
15325
+ db: external_exports.any().optional(),
15326
+ createVars: zFunction().optional(),
15327
+ options: ActorOptionsSchema,
15328
+ inspector: ActorInspectorConfigSchema.optional()
15329
+ }).strict().refine(
15330
+ (data) => !(data.state !== void 0 && data.createState !== void 0),
15331
+ {
15332
+ message: "Cannot define both 'state' and 'createState'",
15333
+ path: ["state"]
15334
+ }
15335
+ ).refine(
15336
+ (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
15337
+ {
15338
+ message: "Cannot define both 'connState' and 'createConnState'",
15339
+ path: ["connState"]
15340
+ }
15341
+ ).refine(
15342
+ (data) => !(data.vars !== void 0 && data.createVars !== void 0),
15343
+ {
15344
+ message: "Cannot define both 'vars' and 'createVars'",
15345
+ path: ["vars"]
15346
+ }
15347
+ );
15348
+ var DocActorOptionsSchema = external_exports.object({
15349
+ name: external_exports.string().optional().describe("Display name for the actor in the Inspector UI."),
15350
+ icon: external_exports.string().optional().describe(
15351
+ "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
15352
+ ),
15353
+ enableActorRuntimeSocket: external_exports.boolean().optional().describe(
15354
+ "Enables the experimental Actor Runtime Socket for this actor. Default: false"
15355
+ ),
15356
+ createVarsTimeout: external_exports.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
15357
+ createConnStateTimeout: external_exports.number().optional().describe(
15358
+ "Timeout in ms for createConnState handler. Default: 5000"
15359
+ ),
15360
+ onMigrateTimeout: external_exports.number().optional().describe("Timeout in ms for onMigrate handler. Default: 30000"),
15361
+ onBeforeConnectTimeout: external_exports.number().optional().describe(
15362
+ "Timeout in ms for onBeforeConnect handler. Default: 5000"
15363
+ ),
15364
+ onConnectTimeout: external_exports.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
15365
+ sleepGracePeriod: external_exports.number().optional().describe(
15366
+ `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}.`
15367
+ ),
15368
+ onDestroyTimeout: external_exports.number().optional().describe(
15369
+ "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
15370
+ ),
15371
+ waitUntilTimeout: external_exports.number().optional().describe(
15372
+ "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
15373
+ ),
15374
+ stateSaveInterval: external_exports.number().optional().describe(
15375
+ "Interval in ms between automatic state saves. Default: 1000"
15376
+ ),
15377
+ actionTimeout: external_exports.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
15378
+ connectionLivenessTimeout: external_exports.number().optional().describe(
15379
+ "Timeout in ms for connection liveness checks. Default: 2500"
15380
+ ),
15381
+ connectionLivenessInterval: external_exports.number().optional().describe(
15382
+ "Interval in ms between connection liveness checks. Default: 5000"
15383
+ ),
15384
+ noSleep: external_exports.boolean().optional().describe(
15385
+ "Deprecated. If true, the actor will never sleep. Use c.keepAwake(promise) to scope keep-awake to a specific operation instead. Default: false"
15386
+ ),
15387
+ sleepTimeout: external_exports.number().optional().describe(
15388
+ "Time in ms of inactivity before the actor sleeps. Default: 30000"
15389
+ ),
15390
+ maxQueueSize: external_exports.number().optional().describe(
15391
+ "Maximum number of queue messages before rejecting new messages. Default: 1000"
15392
+ ),
15393
+ maxSchedules: external_exports.number().int().nonnegative().optional().describe(
15394
+ "Maximum pending one-shot and recurring schedules before rejecting new schedules. Default: 1000"
15395
+ ),
15396
+ maxQueueMessageSize: external_exports.number().optional().describe(
15397
+ "Maximum size of each queue message in bytes. Default: 65536"
15398
+ ),
15399
+ canHibernateWebSocket: external_exports.boolean().optional().describe(
15400
+ "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
15401
+ )
15402
+ }).describe("Actor options for timeouts and behavior configuration.");
15403
+ var DocActorConfigSchema = external_exports.object({
15404
+ state: external_exports.unknown().optional().describe(
15405
+ "Initial state value for the actor. Cannot be used with createState."
15406
+ ),
15407
+ createState: external_exports.unknown().optional().describe(
15408
+ "Function to create initial state. Receives context and input. Cannot be used with state."
15409
+ ),
15410
+ connState: external_exports.unknown().optional().describe(
15411
+ "Initial connection state value. Cannot be used with createConnState."
15412
+ ),
15413
+ createConnState: external_exports.unknown().optional().describe(
15414
+ "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."
15415
+ ),
15416
+ vars: external_exports.unknown().optional().describe(
15417
+ "Initial ephemeral variables value. Cannot be used with createVars."
15418
+ ),
15419
+ createVars: external_exports.unknown().optional().describe(
15420
+ "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
15421
+ ),
15422
+ db: external_exports.unknown().optional().describe("Database provider instance for the actor."),
15423
+ onCreate: external_exports.unknown().optional().describe(
15424
+ "Called when the actor is first initialized. Use to initialize state."
15425
+ ),
15426
+ onDestroy: external_exports.unknown().optional().describe("Called when the actor is destroyed."),
15427
+ onMigrate: external_exports.unknown().optional().describe(
15428
+ "Called on every actor start after persisted state loads and before onWake. Use for repeatable schema migrations."
15429
+ ),
15430
+ onWake: external_exports.unknown().optional().describe(
15431
+ "Called when the actor wakes up and is ready to receive connections and actions."
15432
+ ),
15433
+ onSleep: external_exports.unknown().optional().describe(
15434
+ "Called when the actor is stopping or sleeping. Use to clean up resources."
15435
+ ),
15436
+ run: external_exports.unknown().optional().describe(
15437
+ "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."
15438
+ ),
15439
+ onStateChange: external_exports.unknown().optional().describe(
15440
+ "Called when the actor's state changes. State changes within this hook won't trigger recursion."
15441
+ ),
15442
+ onBeforeConnect: external_exports.unknown().optional().describe(
15443
+ "Called before a client connects. Throw an error to reject the connection. The pending connection is not visible in c.conns while this runs."
15444
+ ),
15445
+ onConnect: external_exports.unknown().optional().describe(
15446
+ "Called when a client successfully connects. The connection is visible in c.conns before this runs."
15447
+ ),
15448
+ onDisconnect: external_exports.unknown().optional().describe("Called when a client disconnects."),
15449
+ onBeforeActionResponse: external_exports.unknown().optional().describe(
15450
+ "Called before sending an action response. Use to transform output."
15451
+ ),
15452
+ onRequest: external_exports.unknown().optional().describe(
15453
+ "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
15454
+ ),
15455
+ onWebSocket: external_exports.unknown().optional().describe(
15456
+ "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
15457
+ ),
15458
+ actions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
15459
+ "Tree of action names or nested groups to handler functions. Nested paths use dot-separated low-level action names. Defaults to an empty object."
15460
+ ),
15461
+ actionInputSchemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
15462
+ "Optional schemas for validating action argument tuples in native runtimes. May mirror nested action groups or use dot-separated low-level action names."
15463
+ ),
15464
+ tracing: external_exports.unknown().optional().describe(
15465
+ "Trace sampling for this actor: `sampler` is the share of its invocations that are recorded, from 0 to 1, with optional per-action rates under `actions`. A rate lowers what is recorded and never raises it. Defaults to the process sampler from OTEL_TRACES_SAMPLER."
15466
+ ),
15467
+ connParamsSchema: external_exports.unknown().optional().describe(
15468
+ "Optional schema for validating connection params in native runtimes."
15469
+ ),
15470
+ events: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of event names to schemas."),
15471
+ queues: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of queue names to schemas."),
15472
+ options: DocActorOptionsSchema.optional()
15473
+ }).describe("Actor configuration passed to the actor() function.");
15471
15474
 
15472
15475
  // ../rivetkit/dist/tsup/chunk-JI6GZ2C2.js
15473
15476
  var EMPTY_KEY = "/";
@@ -15586,7 +15589,7 @@ function removePrefixFromKey(prefixedKey) {
15586
15589
  return prefixedKey.slice(KEYS.KV.length);
15587
15590
  }
15588
15591
 
15589
- // ../rivetkit/dist/tsup/chunk-553CIQJY.js
15592
+ // ../rivetkit/dist/tsup/chunk-2CI2IEVN.js
15590
15593
  function logger() {
15591
15594
  return getLogger("actor-client");
15592
15595
  }
@@ -15707,7 +15710,7 @@ var AsyncMutex = class {
15707
15710
  }
15708
15711
  };
15709
15712
 
15710
- // ../rivetkit/dist/tsup/chunk-5G2J26VM.js
15713
+ // ../rivetkit/dist/tsup/chunk-PYRI75DL.js
15711
15714
  var import_invariant2 = __toESM(require_invariant(), 1);
15712
15715
 
15713
15716
  // ../../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
@@ -16922,7 +16925,7 @@ var TraceAPI = (
16922
16925
  // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js
16923
16926
  var trace = TraceAPI.getInstance();
16924
16927
 
16925
- // ../rivetkit/dist/tsup/chunk-5G2J26VM.js
16928
+ // ../rivetkit/dist/tsup/chunk-PYRI75DL.js
16926
16929
  var import_invariant3 = __toESM(require_invariant(), 1);
16927
16930
  var import_invariant4 = __toESM(require_invariant(), 1);
16928
16931
  var PATH_CONNECT = "/connect";
@@ -19396,7 +19399,8 @@ async function sendHttpRequest(opts) {
19396
19399
  {
19397
19400
  metadata: responseData.metadata,
19398
19401
  rayId: rayId ?? void 0,
19399
- actor: responseData.actor
19402
+ actor: responseData.actor,
19403
+ statusCode: response.status
19400
19404
  }
19401
19405
  );
19402
19406
  } catch (error46) {
@@ -20304,6 +20308,22 @@ var ActorHandleRaw = class {
20304
20308
  "dynamic actor resolution did not produce a direct actor id"
20305
20309
  );
20306
20310
  }
20311
+ /** Issue a token scoped to this actor. Defaults to actor gateway read access. */
20312
+ async issueToken(options = {}) {
20313
+ const actorId = await this.resolve();
20314
+ const permissions = options.permissions ?? {
20315
+ actor_gateway: ["read"]
20316
+ };
20317
+ const grants = Object.keys(permissions).flatMap((resource) => {
20318
+ const operations = permissions[resource];
20319
+ return operations ? [{ resource, target: { id: actorId }, operations }] : [];
20320
+ });
20321
+ return this.#driver.issueToken({
20322
+ subject: options.subject,
20323
+ expiresIn: options.expiresIn,
20324
+ grants
20325
+ });
20326
+ }
20307
20327
  /**
20308
20328
  * Returns the raw URL for routing traffic to the actor.
20309
20329
  */
@@ -20336,6 +20356,8 @@ var ACTOR_CONNS_SYMBOL = /* @__PURE__ */ Symbol("actorConns");
20336
20356
  var CREATE_ACTOR_CONN_PROXY = /* @__PURE__ */ Symbol("createActorConnProxy");
20337
20357
  var ClientRaw = class {
20338
20358
  #disposed = false;
20359
+ /** Issue namespace-scoped tokens with an explicit grant list. */
20360
+ auth;
20339
20361
  [ACTOR_CONNS_SYMBOL] = /* @__PURE__ */ new Set();
20340
20362
  #driver;
20341
20363
  #encodingKind;
@@ -20347,6 +20369,9 @@ var ClientRaw = class {
20347
20369
  */
20348
20370
  constructor(driver, options = {}) {
20349
20371
  this.#driver = driver;
20372
+ this.auth = {
20373
+ issueToken: (issueOptions) => this.#driver.issueToken(issueOptions)
20374
+ };
20350
20375
  this.#encodingKind = options.encoding ?? "bare";
20351
20376
  this.#gatewayOptions = options.gateway ?? {};
20352
20377
  this.#currentActorInvocation = options.currentActorInvocation;
@@ -20638,6 +20663,72 @@ function createActorProxy(handle) {
20638
20663
  }
20639
20664
  });
20640
20665
  }
20666
+ function isInvalidToken(group, code) {
20667
+ return group === "auth" && (code === "invalid_token" || code === "token_expired");
20668
+ }
20669
+ function isInvalidTokenResponse(response) {
20670
+ if (response.status !== 401) return false;
20671
+ const error46 = response.headers.get("x-rivet-error");
20672
+ if (!error46) return false;
20673
+ const separator = error46.indexOf(".");
20674
+ return separator > 0 && isInvalidToken(error46.slice(0, separator), error46.slice(separator + 1));
20675
+ }
20676
+ var TokenProvider = class {
20677
+ constructor(getToken) {
20678
+ this.getToken = getToken;
20679
+ }
20680
+ #cached;
20681
+ #pending;
20682
+ #pendingForce = false;
20683
+ async current() {
20684
+ if (this.#cached && (this.#cached.expiresAt === void 0 || Date.now() < this.#cached.expiresAt - 5e3)) {
20685
+ return this.#cached.token;
20686
+ }
20687
+ return this.#load(false);
20688
+ }
20689
+ /** A late rejection for an older token must never erase a newer credential. */
20690
+ async refreshIfCurrent(failedToken) {
20691
+ var _a2;
20692
+ if (this.#pending !== void 0) {
20693
+ const wasForced = this.#pendingForce;
20694
+ const refreshed = await this.#pending;
20695
+ if (wasForced || refreshed !== failedToken) return refreshed;
20696
+ }
20697
+ if (((_a2 = this.#cached) == null ? void 0 : _a2.token) !== failedToken) {
20698
+ return this.current();
20699
+ }
20700
+ return this.#load(true);
20701
+ }
20702
+ #load(forceRefresh) {
20703
+ if (this.#pending !== void 0) return this.#pending;
20704
+ const pending = Promise.resolve().then(() => this.getToken({ forceRefresh })).then((token) => {
20705
+ if (typeof token !== "string" || token.length === 0) {
20706
+ throw new Error(
20707
+ "getToken must resolve to a nonempty string"
20708
+ );
20709
+ }
20710
+ this.#cached = { token, expiresAt: jwtExpiration(token) };
20711
+ return token;
20712
+ }).finally(() => {
20713
+ if (this.#pending === pending) this.#pending = void 0;
20714
+ });
20715
+ this.#pending = pending;
20716
+ this.#pendingForce = forceRefresh;
20717
+ return pending;
20718
+ }
20719
+ };
20720
+ function jwtExpiration(token) {
20721
+ try {
20722
+ const payload = token.split(".")[1];
20723
+ if (!payload) return void 0;
20724
+ const claims = JSON.parse(
20725
+ atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
20726
+ );
20727
+ return typeof claims.exp === "number" && Number.isSafeInteger(claims.exp) ? claims.exp * 1e3 : void 0;
20728
+ } catch {
20729
+ return void 0;
20730
+ }
20731
+ }
20641
20732
  var CONNECT_SYMBOL = /* @__PURE__ */ Symbol("connect");
20642
20733
  var ActorConnRaw = class {
20643
20734
  #disposed = false;
@@ -20666,6 +20757,7 @@ var ActorConnRaw = class {
20666
20757
  /** Promise used to indicate the socket has connected successfully. This will be rejected if the connection fails. */
20667
20758
  #onOpenPromise;
20668
20759
  #websocket;
20760
+ #authRetryAvailable = true;
20669
20761
  #client;
20670
20762
  #driver;
20671
20763
  #currentActorInvocation;
@@ -20911,6 +21003,10 @@ var ActorConnRaw = class {
20911
21003
  if (error46 instanceof ActorConnDisposed) {
20912
21004
  return false;
20913
21005
  }
21006
+ if (error46 instanceof RivetError && isInvalidToken(error46.group, error46.code) && this.#driver.refreshAuthToken && this.#authRetryAvailable) {
21007
+ this.#authRetryAvailable = false;
21008
+ return true;
21009
+ }
20914
21010
  if (error46 instanceof RivetError && this.#shouldReconnectForStaleActor(error46.group, error46.code)) {
20915
21011
  return true;
20916
21012
  }
@@ -21035,6 +21131,7 @@ var ActorConnRaw = class {
21035
21131
  messageQueueLength: this.#messageQueue.length,
21036
21132
  connId: this.#connId
21037
21133
  });
21134
+ this.#authRetryAvailable = true;
21038
21135
  this.#setConnStatus("connected");
21039
21136
  if (this.#onOpenPromise) {
21040
21137
  this.#onOpenPromise.resolve(void 0);
@@ -21177,7 +21274,8 @@ var ActorConnRaw = class {
21177
21274
  }
21178
21275
  /** Called by the onclose event from drivers. */
21179
21276
  async #handleOnClose(event2) {
21180
- var _a2;
21277
+ var _a2, _b, _c;
21278
+ const failedSocket = this.#websocket;
21181
21279
  const closeEvent = event2;
21182
21280
  const wasClean = closeEvent.wasClean;
21183
21281
  const wasConnected = this.#connStatus === "connected";
@@ -21199,9 +21297,24 @@ var ActorConnRaw = class {
21199
21297
  const parsed = parseWebSocketCloseReason(reason);
21200
21298
  if (parsed) {
21201
21299
  const { group, code, rayId } = parsed;
21300
+ if (isInvalidToken(group, code) && closeEvent.code === 1008 && failedSocket) {
21301
+ try {
21302
+ if (!await ((_b = (_a2 = this.#driver).refreshAuthToken) == null ? void 0 : _b.call(
21303
+ _a2,
21304
+ failedSocket
21305
+ ))) {
21306
+ this.#authRetryAvailable = false;
21307
+ }
21308
+ } catch {
21309
+ logger().warn("token renewal failed");
21310
+ this.#authRetryAvailable = false;
21311
+ }
21312
+ } else if (isInvalidToken(group, code)) {
21313
+ this.#authRetryAvailable = false;
21314
+ }
21202
21315
  if (this.#shouldReconnectForStaleActor(group, code)) {
21203
21316
  this.#clearResolvedActorIdentity();
21204
- (_a2 = this.#onOpenPromise) == null ? void 0 : _a2.reject(
21317
+ (_c = this.#onOpenPromise) == null ? void 0 : _c.reject(
21205
21318
  new RivetError(
21206
21319
  group,
21207
21320
  code,
@@ -21248,7 +21361,7 @@ var ActorConnRaw = class {
21248
21361
  if (error46 instanceof RivetError) {
21249
21362
  this.#dispatchActorError(error46);
21250
21363
  }
21251
- if (wasConnected) {
21364
+ if (wasConnected && this.#authRetryAvailable) {
21252
21365
  logger().debug({
21253
21366
  msg: "triggering reconnect",
21254
21367
  connId: this.#connId
@@ -21717,6 +21830,23 @@ var ActorConnRaw = class {
21717
21830
  );
21718
21831
  }
21719
21832
  };
21833
+ var ENGINE_HOST = "127.0.0.1";
21834
+ var ENGINE_PORT = 6420;
21835
+ var ENGINE_ENDPOINT = buildEngineEndpoint(ENGINE_HOST, ENGINE_PORT);
21836
+ function buildEngineEndpoint(host, port) {
21837
+ const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
21838
+ return `http://${urlHost}:${port}`;
21839
+ }
21840
+ function isLocalEngineEndpoint(endpoint) {
21841
+ let url2;
21842
+ try {
21843
+ url2 = new URL(endpoint);
21844
+ } catch {
21845
+ return false;
21846
+ }
21847
+ const hostname3 = url2.hostname.toLowerCase();
21848
+ return hostname3 === "localhost" || hostname3 === "0.0.0.0" || hostname3 === "::" || hostname3 === "[::]" || hostname3 === "::1" || hostname3 === "[::1]" || /^127(?:\.\d{1,3}){0,3}$/.test(hostname3);
21849
+ }
21720
21850
  function tryParseEndpoint(ctx, options) {
21721
21851
  const {
21722
21852
  endpoint,
@@ -21811,6 +21941,8 @@ var ClientConfigSchemaBase = v4_default.object({
21811
21941
  }),
21812
21942
  /** Token to use to authenticate with the API. */
21813
21943
  token: v4_default.string().optional().transform((val) => val ?? getRivetToken()),
21944
+ /** Issue and renew a client token on demand. Overrides the static token when provided. */
21945
+ getToken: v4_default.custom().optional(),
21814
21946
  /** Namespace to connect to. */
21815
21947
  namespace: v4_default.string().optional().transform((val) => val ?? getRivetNamespace()),
21816
21948
  /** Name of the envoy pool. This is used to group together envoys in to different pools. */
@@ -21855,7 +21987,7 @@ function transformClientConfig(config3, ctx) {
21855
21987
  ...config3,
21856
21988
  endpoint: parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint,
21857
21989
  namespace: (parsedEndpoint == null ? void 0 : parsedEndpoint.namespace) ?? config3.namespace ?? "default",
21858
- token: (parsedEndpoint == null ? void 0 : parsedEndpoint.token) ?? config3.token
21990
+ token: (parsedEndpoint == null ? void 0 : parsedEndpoint.token) ?? config3.token ?? (config3.endpoint && isLocalEngineEndpoint(config3.endpoint) ? "default" : void 0)
21859
21991
  };
21860
21992
  }
21861
21993
  function convertRegistryConfigToClientConfig(config3) {
@@ -21863,6 +21995,7 @@ function convertRegistryConfigToClientConfig(config3) {
21863
21995
  return {
21864
21996
  endpoint: config3.endpoint,
21865
21997
  token: config3.token,
21998
+ getToken: void 0,
21866
21999
  namespace: config3.namespace,
21867
22000
  poolName: config3.envoy.poolName,
21868
22001
  headers: config3.headers,
@@ -22194,7 +22327,8 @@ async function openWebSocketToGateway(runConfig, gatewayUrl, encoding, params, o
22194
22327
  const ackHookToken = typeof process !== "undefined" && process.env.VITEST ? crypto.randomUUID() : void 0;
22195
22328
  logger2().debug({
22196
22329
  msg: "opening websocket to actor via guard",
22197
- gatewayUrl
22330
+ // Gateway URLs can embed credentials; never include the path or query in logs.
22331
+ origin: new URL(gatewayUrl).origin
22198
22332
  });
22199
22333
  const ws = new WebSocket2(
22200
22334
  gatewayUrl,
@@ -22284,6 +22418,14 @@ async function apiCall(config3, method2, path2, body) {
22284
22418
  responseFromBare: (value) => value
22285
22419
  });
22286
22420
  }
22421
+ async function issueToken(config3, options) {
22422
+ return apiCall(config3, "POST", "/auth/tokens", {
22423
+ namespace: config3.namespace,
22424
+ subject: options.subject,
22425
+ duration: options.expiresIn,
22426
+ grants: options.grants
22427
+ });
22428
+ }
22287
22429
  async function getActor(config3, _, actorId) {
22288
22430
  return apiCall(
22289
22431
  config3,
@@ -22525,6 +22667,8 @@ function closeWebSocketIfOpen(ws, code, reason) {
22525
22667
  var RemoteEngineControlClient = class {
22526
22668
  #config;
22527
22669
  #metadataPromise;
22670
+ #tokenProvider;
22671
+ #webSocketTokens = /* @__PURE__ */ new WeakMap();
22528
22672
  constructor(runConfig) {
22529
22673
  if (getNextPhase() === "phase-production-build") {
22530
22674
  logger2().info(
@@ -22533,6 +22677,8 @@ var RemoteEngineControlClient = class {
22533
22677
  runConfig.disableMetadataLookup = true;
22534
22678
  }
22535
22679
  this.#config = { ...runConfig };
22680
+ if (runConfig.getToken)
22681
+ this.#tokenProvider = new TokenProvider(runConfig.getToken);
22536
22682
  if (!runConfig.disableMetadataLookup) {
22537
22683
  this.#metadataPromise = lookupMetadataCached(this.#config).then(
22538
22684
  (metadataData) => {
@@ -22541,14 +22687,13 @@ var RemoteEngineControlClient = class {
22541
22687
  if (metadataData.clientNamespace) {
22542
22688
  this.#config.namespace = metadataData.clientNamespace;
22543
22689
  }
22544
- if (metadataData.clientToken) {
22690
+ if (metadataData.clientToken && !this.#tokenProvider) {
22545
22691
  this.#config.token = metadataData.clientToken;
22546
22692
  }
22547
22693
  logger2().info({
22548
22694
  msg: "overriding client endpoint",
22549
22695
  endpoint: metadataData.clientEndpoint,
22550
- namespace: metadataData.clientNamespace,
22551
- token: metadataData.clientToken
22696
+ namespace: metadataData.clientNamespace
22552
22697
  });
22553
22698
  }
22554
22699
  logger2().info({
@@ -22561,12 +22706,47 @@ var RemoteEngineControlClient = class {
22561
22706
  );
22562
22707
  }
22563
22708
  }
22709
+ async #authorizedConfig() {
22710
+ if (!this.#tokenProvider) return this.#config;
22711
+ return { ...this.#config, token: await this.#tokenProvider.current() };
22712
+ }
22713
+ async #withCredential(request, readOnly = false) {
22714
+ const config3 = await this.#authorizedConfig();
22715
+ try {
22716
+ return await request(config3);
22717
+ } catch (error46) {
22718
+ if (this.#tokenProvider && config3.token && error46 instanceof RivetError && error46.statusCode === 401 && isInvalidToken(error46.group, error46.code)) {
22719
+ if (readOnly) {
22720
+ const token = await this.#tokenProvider.refreshIfCurrent(
22721
+ config3.token
22722
+ );
22723
+ return request({ ...this.#config, token });
22724
+ }
22725
+ await this.#tokenProvider.refreshIfCurrent(config3.token);
22726
+ }
22727
+ throw error46;
22728
+ }
22729
+ }
22730
+ async issueToken(options) {
22731
+ await this.#metadataPromise;
22732
+ const response = await this.#withCredential(
22733
+ (config3) => issueToken(config3, options)
22734
+ );
22735
+ return {
22736
+ token: response.token,
22737
+ issuedAt: response.issued_ts,
22738
+ expiresAt: response.expires_ts
22739
+ };
22740
+ }
22564
22741
  async getForId({
22565
22742
  name,
22566
22743
  actorId
22567
22744
  }) {
22568
22745
  await this.#metadataPromise;
22569
- const response = await getActor(this.#config, name, actorId);
22746
+ const response = await this.#withCredential(
22747
+ (config3) => getActor(config3, name, actorId),
22748
+ true
22749
+ );
22570
22750
  const actor2 = response.actors[0];
22571
22751
  if (!actor2) return void 0;
22572
22752
  if (actor2.name !== name) {
@@ -22587,7 +22767,10 @@ var RemoteEngineControlClient = class {
22587
22767
  await this.#metadataPromise;
22588
22768
  logger2().debug({ msg: "getWithKey: searching for actor", name, key });
22589
22769
  try {
22590
- const response = await getActorByKey(this.#config, name, key);
22770
+ const response = await this.#withCredential(
22771
+ (config3) => getActorByKey(config3, name, key),
22772
+ true
22773
+ );
22591
22774
  const actor2 = response.actors[0];
22592
22775
  if (!actor2) return void 0;
22593
22776
  logger2().debug({
@@ -22620,16 +22803,18 @@ var RemoteEngineControlClient = class {
22620
22803
  key
22621
22804
  });
22622
22805
  try {
22623
- const { actor: actor2, created } = await getOrCreateActor(this.#config, {
22624
- datacenter: region,
22625
- name,
22626
- key: serializeActorKey(key),
22627
- runner_name_selector: poolName ?? this.#config.poolName,
22628
- input: actorInput ? uint8ArrayToBase642(
22629
- encodeCborCompat(actorInput)
22630
- ) : void 0,
22631
- crash_policy: crashPolicy ?? "sleep"
22632
- });
22806
+ const { actor: actor2, created } = await this.#withCredential(
22807
+ (config3) => getOrCreateActor(config3, {
22808
+ datacenter: region,
22809
+ name,
22810
+ key: serializeActorKey(key),
22811
+ runner_name_selector: poolName ?? this.#config.poolName,
22812
+ input: actorInput ? uint8ArrayToBase642(
22813
+ encodeCborCompat(actorInput)
22814
+ ) : void 0,
22815
+ crash_policy: crashPolicy ?? "sleep"
22816
+ })
22817
+ );
22633
22818
  logger2().info({
22634
22819
  msg: "getOrCreateWithKey: actor ready",
22635
22820
  actorId: actor2.actor_id,
@@ -22645,7 +22830,10 @@ var RemoteEngineControlClient = class {
22645
22830
  name,
22646
22831
  key
22647
22832
  });
22648
- const response = await getActorByKey(this.#config, name, key);
22833
+ const response = await this.#withCredential(
22834
+ (config3) => getActorByKey(config3, name, key),
22835
+ true
22836
+ );
22649
22837
  const existing = response.actors[0];
22650
22838
  if (!existing) throw error46;
22651
22839
  logger2().info({
@@ -22669,14 +22857,18 @@ var RemoteEngineControlClient = class {
22669
22857
  }) {
22670
22858
  await this.#metadataPromise;
22671
22859
  logger2().info({ msg: "creating actor via engine api", name, key });
22672
- const result = await createActor(this.#config, {
22673
- datacenter: region,
22674
- name,
22675
- runner_name_selector: poolName ?? this.#config.poolName,
22676
- key: serializeActorKey(key),
22677
- input: input ? uint8ArrayToBase642(encodeCborCompat(input)) : void 0,
22678
- crash_policy: crashPolicy ?? "sleep"
22679
- });
22860
+ const result = await this.#withCredential(
22861
+ (config3) => createActor(config3, {
22862
+ datacenter: region,
22863
+ name,
22864
+ runner_name_selector: poolName ?? this.#config.poolName,
22865
+ key: serializeActorKey(key),
22866
+ input: input ? uint8ArrayToBase642(
22867
+ encodeCborCompat(input)
22868
+ ) : void 0,
22869
+ crash_policy: crashPolicy ?? "sleep"
22870
+ })
22871
+ );
22680
22872
  logger2().info({
22681
22873
  msg: "actor created",
22682
22874
  actorId: result.actor.actor_id,
@@ -22688,43 +22880,61 @@ var RemoteEngineControlClient = class {
22688
22880
  async listActors({ name }) {
22689
22881
  await this.#metadataPromise;
22690
22882
  logger2().debug({ msg: "listing actors via engine api", name });
22691
- const response = await listActorsByName(this.#config, name);
22883
+ const response = await this.#withCredential(
22884
+ (config3) => listActorsByName(config3, name),
22885
+ true
22886
+ );
22692
22887
  return response.actors.map(apiActorToOutput);
22693
22888
  }
22694
22889
  async destroyActor(actorId) {
22695
22890
  await this.#metadataPromise;
22696
22891
  logger2().info({ msg: "destroying actor via engine api", actorId });
22697
- await destroyActor(this.#config, actorId);
22892
+ await this.#withCredential((config3) => destroyActor(config3, actorId));
22698
22893
  logger2().info({ msg: "actor destroyed", actorId });
22699
22894
  }
22700
22895
  async sendRequest(target, actorRequest, options = {}) {
22896
+ var _a2;
22701
22897
  await this.#metadataPromise;
22702
- const path2 = requestPath(actorRequest);
22703
- const gatewayUrl = this.#buildGatewayUrlForTarget(
22704
- target,
22705
- path2,
22706
- options
22707
- );
22898
+ const config3 = await this.#authorizedConfig();
22708
22899
  const httpOptions = {
22709
22900
  ...options,
22710
22901
  directActorId: shouldSkipReadyWait(options) ? directActorIdFromTarget(target) : void 0
22711
22902
  };
22712
- return sendHttpRequestToGateway(
22713
- this.#config,
22714
- gatewayUrl,
22903
+ const send = (current) => sendHttpRequestToGateway(
22904
+ current,
22905
+ this.#buildGatewayUrlForTarget(
22906
+ current,
22907
+ target,
22908
+ requestPath(actorRequest),
22909
+ options
22910
+ ),
22715
22911
  actorRequest,
22716
22912
  httpOptions
22717
22913
  );
22914
+ const response = await send(config3);
22915
+ if (!this.#tokenProvider || !config3.token || !isInvalidTokenResponse(response))
22916
+ return response;
22917
+ if ((actorRequest.method === "GET" || actorRequest.method === "HEAD") && !("getOrCreateForKey" in target)) {
22918
+ const token = await this.#tokenProvider.refreshIfCurrent(
22919
+ config3.token
22920
+ );
22921
+ await ((_a2 = response.body) == null ? void 0 : _a2.cancel());
22922
+ return send({ ...this.#config, token });
22923
+ }
22924
+ await this.#tokenProvider.refreshIfCurrent(config3.token);
22925
+ return response;
22718
22926
  }
22719
22927
  async openWebSocket(path2, target, encoding, params, options = {}) {
22720
22928
  await this.#metadataPromise;
22929
+ const config3 = await this.#authorizedConfig();
22721
22930
  const gatewayUrl = this.#buildGatewayUrlForTarget(
22931
+ config3,
22722
22932
  target,
22723
22933
  path2,
22724
22934
  options
22725
22935
  );
22726
- return openWebSocketToGateway(
22727
- this.#config,
22936
+ const ws = await openWebSocketToGateway(
22937
+ config3,
22728
22938
  gatewayUrl,
22729
22939
  encoding,
22730
22940
  params,
@@ -22733,25 +22943,59 @@ var RemoteEngineControlClient = class {
22733
22943
  directActorId: shouldSkipReadyWait(options) ? directActorIdFromTarget(target) : void 0
22734
22944
  }
22735
22945
  );
22946
+ this.#watchWebSocketAuth(ws, config3.token);
22947
+ return ws;
22948
+ }
22949
+ async refreshAuthToken(ws) {
22950
+ const context2 = this.#webSocketTokens.get(ws);
22951
+ if (!(context2 == null ? void 0 : context2.refresh)) return false;
22952
+ await context2.refresh;
22953
+ return true;
22954
+ }
22955
+ #watchWebSocketAuth(ws, token) {
22956
+ const tokenProvider = this.#tokenProvider;
22957
+ if (!tokenProvider || !token) return;
22958
+ const context2 = {};
22959
+ this.#webSocketTokens.set(ws, context2);
22960
+ ws.addEventListener(
22961
+ "close",
22962
+ (event2) => {
22963
+ if (event2.code !== 1008 || !event2.reason) return;
22964
+ const separator = event2.reason.indexOf(".");
22965
+ if (separator < 0) return;
22966
+ const code = event2.reason.slice(separator + 1).split(/[\s:#]/, 1)[0];
22967
+ if (isInvalidToken(event2.reason.slice(0, separator), code)) {
22968
+ context2.refresh = tokenProvider.refreshIfCurrent(token).catch((error46) => {
22969
+ logger2().warn(
22970
+ "failed to renew authentication token"
22971
+ );
22972
+ throw error46;
22973
+ });
22974
+ context2.refresh.catch(() => {
22975
+ });
22976
+ }
22977
+ }
22978
+ );
22736
22979
  }
22737
22980
  async buildGatewayUrl(target, options = {}) {
22738
22981
  await this.#metadataPromise;
22739
- return this.#buildGatewayUrlForTarget(target, "", options);
22982
+ return this.#buildGatewayUrlForTarget(
22983
+ await this.#authorizedConfig(),
22984
+ target,
22985
+ "",
22986
+ options
22987
+ );
22740
22988
  }
22741
22989
  async proxyRequest(_c, actorRequest, actorId) {
22742
- await this.#metadataPromise;
22743
- const gatewayUrl = this.#buildGatewayUrlForTarget(
22744
- { directId: actorId },
22745
- requestPath(actorRequest)
22746
- );
22747
- return sendHttpRequestToGateway(this.#config, gatewayUrl, actorRequest);
22990
+ return this.sendRequest({ directId: actorId }, actorRequest);
22748
22991
  }
22749
22992
  async proxyWebSocket(c, path2, actorId, encoding, params) {
22750
- var _a2, _b;
22993
+ var _a2;
22751
22994
  await this.#metadataPromise;
22752
- const upgradeWebSocket = (_b = (_a2 = this.#config).getUpgradeWebSocket) == null ? void 0 : _b.call(_a2);
22995
+ const config3 = await this.#authorizedConfig();
22996
+ const upgradeWebSocket = (_a2 = config3.getUpgradeWebSocket) == null ? void 0 : _a2.call(config3);
22753
22997
  (0, import_invariant4.default)(upgradeWebSocket, "missing getUpgradeWebSocket");
22754
- const endpoint = getEndpoint(this.#config);
22998
+ const endpoint = getEndpoint(config3);
22755
22999
  const guardUrl = combineUrlPath(endpoint, path2);
22756
23000
  const wsGuardUrl = guardUrl.replace("http://", "ws://");
22757
23001
  logger2().debug({
@@ -22761,7 +23005,7 @@ var RemoteEngineControlClient = class {
22761
23005
  guardUrl
22762
23006
  });
22763
23007
  const protocols = buildWebSocketProtocols(
22764
- this.#config,
23008
+ config3,
22765
23009
  encoding,
22766
23010
  params,
22767
23011
  void 0,
@@ -22779,8 +23023,8 @@ var RemoteEngineControlClient = class {
22779
23023
  setGetUpgradeWebSocket(getUpgradeWebSocket) {
22780
23024
  this.#config.getUpgradeWebSocket = getUpgradeWebSocket;
22781
23025
  }
22782
- #buildGatewayUrlForTarget(target, path2, options = {}) {
22783
- const endpoint = getEndpoint(this.#config);
23026
+ #buildGatewayUrlForTarget(config3, target, path2, options = {}) {
23027
+ const endpoint = getEndpoint(config3);
22784
23028
  if (shouldSkipReadyWait(options) && directActorIdFromTarget(target) && canUseDirectSkipReadyWaitPath(path2)) {
22785
23029
  return combineUrlPath(endpoint, path2);
22786
23030
  }
@@ -22788,7 +23032,7 @@ var RemoteEngineControlClient = class {
22788
23032
  return buildActorGatewayUrl(
22789
23033
  endpoint,
22790
23034
  target.directId,
22791
- this.#config.token,
23035
+ config3.token,
22792
23036
  path2
22793
23037
  );
22794
23038
  }
@@ -22796,20 +23040,20 @@ var RemoteEngineControlClient = class {
22796
23040
  return buildActorGatewayUrl(
22797
23041
  endpoint,
22798
23042
  target.getForId.actorId,
22799
- this.#config.token,
23043
+ config3.token,
22800
23044
  path2
22801
23045
  );
22802
23046
  }
22803
23047
  if ("getForKey" in target || "getOrCreateForKey" in target) {
22804
23048
  return buildActorQueryGatewayUrl(
22805
23049
  endpoint,
22806
- this.#config.namespace,
23050
+ config3.namespace,
22807
23051
  target,
22808
- this.#config.token,
23052
+ config3.token,
22809
23053
  path2,
22810
- this.#config.maxInputSize,
23054
+ config3.maxInputSize,
22811
23055
  void 0,
22812
- "getOrCreateForKey" in target ? target.getOrCreateForKey.poolName ?? this.#config.poolName : void 0,
23056
+ "getOrCreateForKey" in target ? target.getOrCreateForKey.poolName ?? config3.poolName : void 0,
22813
23057
  options
22814
23058
  );
22815
23059
  }
@@ -22858,7 +23102,7 @@ function apiActorToOutput(actor2) {
22858
23102
  };
22859
23103
  }
22860
23104
 
22861
- // ../rivetkit/dist/tsup/chunk-W2PXGWMR.js
23105
+ // ../rivetkit/dist/tsup/chunk-5EGLHQJJ.js
22862
23106
  var nativeStateTransactionOpeners = /* @__PURE__ */ new WeakMap();
22863
23107
  var nativeStateTransactionClientBinders = /* @__PURE__ */ new WeakMap();
22864
23108
  function registerNativeStateTransactionOpener(provider, opener) {
@@ -24600,23 +24844,6 @@ var InlineWebSocketAdapter = class {
24600
24844
  }
24601
24845
  }
24602
24846
  };
24603
- var ENGINE_HOST = "127.0.0.1";
24604
- var ENGINE_PORT = 6420;
24605
- var ENGINE_ENDPOINT = buildEngineEndpoint(ENGINE_HOST, ENGINE_PORT);
24606
- function buildEngineEndpoint(host, port) {
24607
- const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
24608
- return `http://${urlHost}:${port}`;
24609
- }
24610
- function isLocalEngineEndpoint(endpoint) {
24611
- let url2;
24612
- try {
24613
- url2 = new URL(endpoint);
24614
- } catch {
24615
- return false;
24616
- }
24617
- const hostname3 = url2.hostname.toLowerCase();
24618
- return hostname3 === "localhost" || hostname3 === "0.0.0.0" || hostname3 === "::" || hostname3 === "[::]" || hostname3 === "::1" || hostname3 === "[::1]" || /^127(?:\.\d{1,3}){0,3}$/.test(hostname3);
24619
- }
24620
24847
  function logger22() {
24621
24848
  return getLogger("registry");
24622
24849
  }
@@ -24714,20 +24941,9 @@ async function configureServerlessPool(config3) {
24714
24941
  });
24715
24942
  throw lastError;
24716
24943
  }
24717
- var warnedMissingVersion = false;
24718
24944
  var EnvoyConfigSchema = external_exports.object({
24719
24945
  poolName: external_exports.string().default(() => getRivetPool() ?? "default"),
24720
- version: external_exports.number().default(() => {
24721
- const version2 = getRivetEnvoyVersion();
24722
- if (version2 !== void 0) return version2;
24723
- if (getNodeEnv() === "production" && !warnedMissingVersion) {
24724
- warnedMissingVersion = true;
24725
- getLogger("rivetkit").error(
24726
- "RIVET_ENVOY_VERSION is not set. Actors will not be versioned, which means they won't be drained on deploy. This is only needed when self-hosting or using a custom envoy (not needed for Rivet Compute). Set this as a build arg in your Dockerfile. See https://rivet.dev/docs/actors/versions"
24727
- );
24728
- }
24729
- return 1;
24730
- }),
24946
+ version: external_exports.number().default(() => getRivetEnvoyVersion() ?? 1),
24731
24947
  // Deprecated.
24732
24948
  totalSlots: external_exports.number().default(() => getRivetTotalSlots() ?? 1e5),
24733
24949
  envoyKey: external_exports.string().optional()
@@ -25027,7 +25243,7 @@ var RegistryConfigSchema = external_exports.object({
25027
25243
  config3.startEngine || parsedEndpoint
25028
25244
  );
25029
25245
  const namespace = (parsedEndpoint == null ? void 0 : parsedEndpoint.namespace) ?? config3.namespace ?? "default";
25030
- const token = (parsedEndpoint == null ? void 0 : parsedEndpoint.token) ?? config3.token ?? "dev";
25246
+ const token = (parsedEndpoint == null ? void 0 : parsedEndpoint.token) ?? config3.token ?? (endpoint && isLocalEngineEndpoint(endpoint) ? "default" : void 0);
25031
25247
  const parsedPublicEndpoint = config3.serverless.publicEndpoint ? tryParseEndpoint(ctx, {
25032
25248
  endpoint: config3.serverless.publicEndpoint,
25033
25249
  path: ["serverless", "publicEndpoint"]
@@ -31992,7 +32208,23 @@ var Registry = class {
31992
32208
  * Starts an actor envoy for standalone server deployments.
31993
32209
  */
31994
32210
  #startEnvoy(config3, printWelcome) {
32211
+ var _a2;
31995
32212
  if (!this.#runtimeServePromise) {
32213
+ const configuredEnvoyVersion = (_a2 = this.#config.envoy) == null ? void 0 : _a2.version;
32214
+ const envoyVersionSource = configuredEnvoyVersion !== void 0 ? "config" : getRivetEnvoyVersion() !== void 0 ? "environment" : "default";
32215
+ logger22().info({
32216
+ msg: "starting rivetkit envoy",
32217
+ rivetkitVersion: VERSION,
32218
+ envoyVersion: config3.envoy.version,
32219
+ envoyVersionSource
32220
+ });
32221
+ if (envoyVersionSource === "default" && getNodeEnv() === "production") {
32222
+ logger22().error({
32223
+ msg: "envoy version defaulted because neither config.envoy.version nor RIVET_ENVOY_VERSION is set; actors will not drain automatically across deploys. See https://rivet.dev/docs/actors/versions",
32224
+ envoyVersion: config3.envoy.version,
32225
+ envoyVersionSource
32226
+ });
32227
+ }
31996
32228
  const configuredRegistryPromise = this.#buildConfiguredRegistry(config3);
31997
32229
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
31998
32230
  this.#runtimeServeLifecyclePromise = configuredRegistryPromise.then(