@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.mjs CHANGED
@@ -297,6 +297,205 @@ var require_retry2 = __commonJS({
297
297
  // src/mod.ts
298
298
  import * as wasmBindings from "@rivetkit/rivetkit-wasm";
299
299
 
300
+ // ../rivetkit/dist/tsup/chunk-P2OFXH4G.js
301
+ var INTERNAL_ERROR_CODE = "internal_error";
302
+ var INTERNAL_ERROR_DESCRIPTION = "An internal error occurred";
303
+ var USER_ERROR_CODE = "user_error";
304
+ var BRIDGE_RIVET_ERROR_PREFIX = "__RIVET_ERROR_JSON__:";
305
+ function looksLikeRivetErrorOptions(value) {
306
+ return typeof value === "object" && value !== null && ("public" in value || "metadata" in value || "rayId" in value || "statusCode" in value || "actor" in value || "cause" in value);
307
+ }
308
+ function isTypedErrorTag(value) {
309
+ return value === "ActorError" || value === "RivetError";
310
+ }
311
+ function errorMessage(error46, fallback = String(error46)) {
312
+ if (error46 && typeof error46 === "object" && "message" in error46 && typeof error46.message === "string") {
313
+ return error46.message;
314
+ }
315
+ return fallback;
316
+ }
317
+ function isRivetErrorLike(error46) {
318
+ 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));
319
+ }
320
+ function isActorAbortedError(error46) {
321
+ return isRivetErrorLike(error46) && error46.group === "actor" && error46.code === "aborted";
322
+ }
323
+ function isActorSpecifier(value) {
324
+ 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");
325
+ }
326
+ var RivetError = class extends Error {
327
+ __type = "RivetError";
328
+ public;
329
+ metadata;
330
+ rayId;
331
+ statusCode;
332
+ actor;
333
+ group;
334
+ code;
335
+ static isRivetError(error46) {
336
+ return isRivetErrorLike(error46);
337
+ }
338
+ static isActorError(error46) {
339
+ return isRivetErrorLike(error46);
340
+ }
341
+ constructor(group, code, message, options) {
342
+ const normalized = looksLikeRivetErrorOptions(options) ? options : { metadata: options };
343
+ super(message, { cause: normalized.cause });
344
+ this.name = "RivetError";
345
+ this.group = group;
346
+ this.code = code;
347
+ this.public = normalized.public ?? false;
348
+ this.metadata = normalized.metadata;
349
+ this.rayId = normalized.rayId ?? void 0;
350
+ this.statusCode = normalized.statusCode ?? (this.public ? 400 : 500);
351
+ this.actor = normalized.actor;
352
+ }
353
+ toString() {
354
+ return this.message;
355
+ }
356
+ };
357
+ var UserError = class extends RivetError {
358
+ constructor(message, options) {
359
+ super("user", (options == null ? void 0 : options.code) ?? USER_ERROR_CODE, message, {
360
+ public: true,
361
+ metadata: options == null ? void 0 : options.metadata,
362
+ cause: options == null ? void 0 : options.cause
363
+ });
364
+ }
365
+ };
366
+ function toRivetError(error46, fallback) {
367
+ if (typeof error46 === "string") {
368
+ const bridged = decodeBridgeRivetError(error46);
369
+ if (bridged) {
370
+ return bridged;
371
+ }
372
+ }
373
+ if (error46 instanceof Error) {
374
+ const bridged = decodeBridgeRivetError(error46.message);
375
+ if (bridged) {
376
+ return bridged;
377
+ }
378
+ }
379
+ if (isRivetErrorLike(error46)) {
380
+ return new RivetError(error46.group, error46.code, error46.message, {
381
+ public: error46.public,
382
+ statusCode: error46.statusCode,
383
+ metadata: error46.metadata,
384
+ rayId: error46.rayId,
385
+ actor: error46.actor,
386
+ cause: error46 instanceof Error ? error46.cause : void 0
387
+ });
388
+ }
389
+ return new RivetError(
390
+ (fallback == null ? void 0 : fallback.group) ?? "actor",
391
+ (fallback == null ? void 0 : fallback.code) ?? INTERNAL_ERROR_CODE,
392
+ errorMessage(error46, (fallback == null ? void 0 : fallback.message) ?? "Unknown error"),
393
+ {
394
+ public: fallback == null ? void 0 : fallback.public,
395
+ statusCode: fallback == null ? void 0 : fallback.statusCode,
396
+ metadata: fallback == null ? void 0 : fallback.metadata,
397
+ rayId: fallback == null ? void 0 : fallback.rayId,
398
+ actor: fallback == null ? void 0 : fallback.actor,
399
+ cause: error46 instanceof Error ? error46 : void 0
400
+ }
401
+ );
402
+ }
403
+ function encodeBridgeRivetError(error46) {
404
+ return `${BRIDGE_RIVET_ERROR_PREFIX}${JSON.stringify({
405
+ group: error46.group,
406
+ code: error46.code,
407
+ message: error46.message,
408
+ metadata: error46.metadata,
409
+ rayId: error46.rayId,
410
+ public: error46.public,
411
+ statusCode: error46.statusCode,
412
+ actor: error46.actor
413
+ })}`;
414
+ }
415
+ function encodeErrorForBridge(error46) {
416
+ if (isCanonicalStructuredRivetError(error46)) {
417
+ return encodeBridgeRivetError(error46);
418
+ }
419
+ return String(error46);
420
+ }
421
+ function isCanonicalStructuredRivetError(error46) {
422
+ 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";
423
+ }
424
+ function decodeBridgeRivetErrorPayload(value) {
425
+ if (!value.startsWith(BRIDGE_RIVET_ERROR_PREFIX)) {
426
+ return void 0;
427
+ }
428
+ try {
429
+ const raw = JSON.parse(
430
+ value.slice(BRIDGE_RIVET_ERROR_PREFIX.length)
431
+ );
432
+ const payload = {
433
+ ...raw,
434
+ rayId: raw.rayId ?? void 0
435
+ };
436
+ if (!isRivetErrorLike(payload)) {
437
+ return void 0;
438
+ }
439
+ if (payload.actor !== void 0 && payload.actor !== null && !isActorSpecifier(payload.actor)) {
440
+ return void 0;
441
+ }
442
+ return payload;
443
+ } catch {
444
+ return void 0;
445
+ }
446
+ }
447
+ function decodeBridgeRivetError(value) {
448
+ const payload = decodeBridgeRivetErrorPayload(value);
449
+ if (!payload) {
450
+ return void 0;
451
+ }
452
+ return new RivetError(payload.group, payload.code, payload.message, {
453
+ metadata: payload.metadata,
454
+ rayId: payload.rayId,
455
+ public: payload.public,
456
+ statusCode: payload.statusCode,
457
+ actor: payload.actor ?? void 0
458
+ });
459
+ }
460
+ function invalidRequest(error46) {
461
+ return new RivetError(
462
+ "request",
463
+ "invalid",
464
+ `Invalid request: ${errorMessage(error46, String(error46))}`,
465
+ {
466
+ public: true,
467
+ cause: error46 instanceof Error ? error46 : void 0
468
+ }
469
+ );
470
+ }
471
+ function actorNotFound(identifier) {
472
+ return new RivetError(
473
+ "actor",
474
+ "not_found",
475
+ identifier ? `Actor not found: ${identifier} (https://www.rivet.dev/docs/clients/javascript)` : "Actor not found (https://www.rivet.dev/docs/clients/javascript)",
476
+ { public: true }
477
+ );
478
+ }
479
+ function forbiddenError() {
480
+ return new RivetError("auth", "forbidden", "Forbidden", {
481
+ public: true,
482
+ statusCode: 403
483
+ });
484
+ }
485
+ function unsupportedFeature(feature) {
486
+ return new RivetError(
487
+ "feature",
488
+ "unsupported",
489
+ `Unsupported feature: ${feature}`
490
+ );
491
+ }
492
+
493
+ // ../rivetkit/dist/tsup/chunk-RGIZNZYO.js
494
+ import {
495
+ pino,
496
+ stdTimeFunctions
497
+ } from "pino";
498
+
300
499
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/classic/external.js
301
500
  var external_exports = {};
302
501
  __export(external_exports, {
@@ -12967,870 +13166,178 @@ var classic_default = external_exports;
12967
13166
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/index.js
12968
13167
  var v4_default = classic_default;
12969
13168
 
12970
- // ../rivetkit/dist/tsup/chunk-CSOHAAZK.js
12971
- function flattenActionHandlers(actions) {
12972
- const flattened = /* @__PURE__ */ Object.create(null);
12973
- for (const { name, handler } of collectActionEntries(actions)) {
12974
- flattened[name] = handler;
13169
+ // ../rivetkit/dist/tsup/chunk-RGIZNZYO.js
13170
+ var import_invariant = __toESM(require_invariant(), 1);
13171
+ import * as cbor from "cbor-x";
13172
+ var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
13173
+ var getRivetEndpoint = () => getEnvUniversal("RIVET_ENDPOINT");
13174
+ var getRivetToken = () => getEnvUniversal("RIVET_TOKEN");
13175
+ var getRivetNamespace = () => getEnvUniversal("RIVET_NAMESPACE");
13176
+ var getRivetPool = () => getEnvUniversal("RIVET_POOL");
13177
+ var getRivetTotalSlots = () => {
13178
+ const value = getEnvUniversal("RIVET_TOTAL_SLOTS");
13179
+ return value !== void 0 ? parseInt(value, 10) : void 0;
13180
+ };
13181
+ var getRivetRunEngine = () => getEnvUniversal("RIVET_RUN_ENGINE") === "1";
13182
+ var getRivetRunEngineHost = () => getEnvUniversal("RIVET_RUN_ENGINE_HOST");
13183
+ var getRivetRunEnginePort = () => {
13184
+ const value = getEnvUniversal("RIVET_RUN_ENGINE_PORT");
13185
+ return value !== void 0 ? parseInt(value, 10) : void 0;
13186
+ };
13187
+ var getRivetRunEngineVersion = () => getEnvUniversal("RIVET_RUN_ENGINE_VERSION");
13188
+ var getRivetRunServices = () => {
13189
+ const value = getEnvUniversal("RIVET_RUN_SERVICES");
13190
+ return value === void 0 ? void 0 : value === "1";
13191
+ };
13192
+ var getRivetEnvoyVersion = () => {
13193
+ const value = getEnvUniversal("RIVET_ENVOY_VERSION");
13194
+ return value !== void 0 ? parseInt(value, 10) : void 0;
13195
+ };
13196
+ var getRivetPublicEndpoint = () => getEnvUniversal("RIVET_PUBLIC_ENDPOINT");
13197
+ var getRivetPublicToken = () => getEnvUniversal("RIVET_PUBLIC_TOKEN");
13198
+ var getRivetkitRuntime = () => getEnvUniversal("RIVETKIT_RUNTIME");
13199
+ var getRivetkitRuntimeMode = () => {
13200
+ const value = getEnvUniversal("RIVETKIT_RUNTIME_MODE");
13201
+ if (value === void 0) return "envoy";
13202
+ if (value === "envoy" || value === "serverless") return value;
13203
+ throw new Error(
13204
+ `RIVETKIT_RUNTIME_MODE env var must be "envoy" or "serverless"; got "${value}"`
13205
+ );
13206
+ };
13207
+ var getRivetkitPublicDir = () => {
13208
+ const value = getEnvUniversal("RIVETKIT_PUBLIC_DIR");
13209
+ return value === void 0 || value === "" ? void 0 : value;
13210
+ };
13211
+ function parsePortEnv(raw) {
13212
+ if (raw === void 0 || raw === "") return void 0;
13213
+ const parsed = Number.parseInt(raw, 10);
13214
+ if (!Number.isFinite(parsed) || parsed < 1 || parsed > 65535 || String(parsed) !== raw.trim()) {
13215
+ throw new Error(
13216
+ `RIVET_PORT env var must be an integer between 1 and 65535; got "${raw}"`
13217
+ );
12975
13218
  }
12976
- return flattened;
13219
+ return parsed;
12977
13220
  }
12978
- function flattenActionInputSchemas(actions, schemas) {
12979
- if (schemas === void 0) return void 0;
12980
- if (!isRecord(schemas)) {
12981
- throw new TypeError("actionInputSchemas must be an object");
12982
- }
12983
- const flattened = /* @__PURE__ */ Object.create(null);
12984
- for (const { name, path: path2 } of collectActionEntries(actions)) {
12985
- const nestedSchema = lookupNestedSchema(schemas, path2);
12986
- const flatSchema = schemas[name];
12987
- if (nestedSchema !== void 0 && flatSchema !== void 0 && nestedSchema !== flatSchema) {
12988
- throw new TypeError(
12989
- `Action input schema \`${name}\` is defined by both a nested path and a dotted key`
12990
- );
12991
- }
12992
- const schema = nestedSchema ?? flatSchema;
12993
- if (schema !== void 0) {
12994
- flattened[name] = schema;
12995
- }
12996
- }
12997
- return flattened;
13221
+ var getLogLevel = () => getEnvUniversal("RIVET_LOG_LEVEL") ?? getEnvUniversal("LOG_LEVEL");
13222
+ var getLogTarget = () => getEnvUniversal("RIVET_LOG_TARGET") === "1";
13223
+ var getLogTimestamp = () => getEnvUniversal("RIVET_LOG_TIMESTAMP") === "1";
13224
+ var getLogMessage = () => getEnvUniversal("RIVET_LOG_MESSAGE") === "1";
13225
+ var getLogErrorStack = () => getEnvUniversal("RIVET_LOG_ERROR_STACK") === "1";
13226
+ var getNodeEnv = () => getEnvUniversal("NODE_ENV");
13227
+ var getNextPhase = () => getEnvUniversal("NEXT_PHASE");
13228
+ var isDev = () => getNodeEnv() !== "production";
13229
+ function assertUnreachable(x) {
13230
+ throw new Error(`Unreachable case: ${x}`);
12998
13231
  }
12999
- function flattenActionTraceSamplers(actions, rates = {}) {
13000
- const handlers = flattenActionHandlers(actions);
13001
- const flattened = Object.fromEntries(flattenSampleRates(rates, []));
13002
- for (const name of Object.keys(flattened)) {
13003
- if (!Object.hasOwn(handlers, name)) {
13004
- throw new TypeError(
13005
- `tracing.actions.${name} does not name an action`
13006
- );
13232
+ function deconstructError(error46, exposeInternalError = false) {
13233
+ let statusCode;
13234
+ let public_;
13235
+ let group;
13236
+ let code;
13237
+ let message;
13238
+ let metadata;
13239
+ let rayId;
13240
+ let actor2;
13241
+ if (isCanonicalStructuredRivetError(error46)) {
13242
+ statusCode = typeof error46.statusCode === "number" ? error46.statusCode : error46.public ? 400 : 500;
13243
+ public_ = error46.public ?? false;
13244
+ group = error46.group;
13245
+ code = error46.code;
13246
+ message = error46.message;
13247
+ metadata = error46.metadata;
13248
+ rayId = error46.rayId;
13249
+ actor2 = error46.actor;
13250
+ } else if (RivetError.isActorError(error46) && error46.public) {
13251
+ statusCode = "statusCode" in error46 && error46.statusCode ? error46.statusCode : 400;
13252
+ public_ = true;
13253
+ group = error46.group;
13254
+ code = error46.code;
13255
+ message = getErrorMessage(error46);
13256
+ metadata = error46.metadata;
13257
+ rayId = error46.rayId;
13258
+ actor2 = error46.actor;
13259
+ } else if (exposeInternalError) {
13260
+ if (RivetError.isActorError(error46)) {
13261
+ statusCode = 500;
13262
+ public_ = false;
13263
+ group = error46.group;
13264
+ code = error46.code;
13265
+ message = getErrorMessage(error46);
13266
+ metadata = error46.metadata;
13267
+ rayId = error46.rayId;
13268
+ actor2 = error46.actor;
13269
+ } else {
13270
+ statusCode = 500;
13271
+ public_ = false;
13272
+ group = "rivetkit";
13273
+ code = INTERNAL_ERROR_CODE;
13274
+ message = getErrorMessage(error46);
13007
13275
  }
13008
- }
13009
- return flattened;
13010
- }
13011
- function flattenSampleRates(rates, path2) {
13012
- return Object.entries(rates).flatMap(
13013
- ([segment, rate]) => {
13014
- const childPath = [...path2, segment];
13015
- return typeof rate === "number" ? [[childPath.join("."), rate]] : flattenSampleRates(rate, childPath);
13276
+ } else {
13277
+ statusCode = 500;
13278
+ public_ = false;
13279
+ group = "rivetkit";
13280
+ code = INTERNAL_ERROR_CODE;
13281
+ message = INTERNAL_ERROR_DESCRIPTION;
13282
+ if (RivetError.isActorError(error46)) {
13283
+ actor2 = error46.actor;
13016
13284
  }
13017
- );
13018
- }
13019
- function collectActionEntries(actions) {
13020
- const entries = [];
13021
- const names = /* @__PURE__ */ new Set();
13022
- visitActionGroup(actions ?? {}, [], entries, names);
13023
- return entries;
13024
- }
13025
- function visitActionGroup(value, path2, entries, names) {
13026
- if (!isRecord(value)) {
13027
- throw new TypeError(
13028
- `${formatActionPath(path2)} must be an action handler or group`
13029
- );
13285
+ metadata = {
13286
+ //url: `https://dashboard.rivet.dev/projects/${actorMetadata.project.slug}/environments/${actorMetadata.environment.slug}/actors?actorId=${actorMetadata.actor.id}`,
13287
+ };
13030
13288
  }
13031
- for (const [segment, child] of Object.entries(value)) {
13032
- const childPath = [...path2, segment];
13033
- if (typeof child === "function") {
13034
- const name = childPath.join(".");
13035
- if (names.has(name)) {
13036
- throw new TypeError(
13037
- `Multiple action definitions flatten to \`${name}\``
13038
- );
13289
+ return {
13290
+ __type: "ActorError",
13291
+ statusCode,
13292
+ public: public_,
13293
+ group,
13294
+ code,
13295
+ message,
13296
+ metadata,
13297
+ rayId,
13298
+ actor: actor2
13299
+ };
13300
+ }
13301
+ function stringifyError(error46) {
13302
+ if (error46 instanceof Error) {
13303
+ if (typeof process !== "undefined" && getLogErrorStack()) {
13304
+ let stack;
13305
+ try {
13306
+ stack = error46.stack;
13307
+ } catch {
13308
+ stack = void 0;
13039
13309
  }
13040
- names.add(name);
13041
- entries.push({
13042
- name,
13043
- path: childPath,
13044
- handler: child
13045
- });
13310
+ return `${error46.name}: ${error46.message}${stack ? `
13311
+ ${stack}` : ""}`;
13046
13312
  } else {
13047
- visitActionGroup(child, childPath, entries, names);
13313
+ return `${error46.name}: ${error46.message}`;
13048
13314
  }
13049
- }
13050
- }
13051
- function lookupNestedSchema(schemas, path2) {
13052
- let value = schemas;
13053
- for (const segment of path2) {
13054
- if (!isRecord(value) || !Object.hasOwn(value, segment)) {
13055
- return void 0;
13315
+ } else if (typeof error46 === "string") {
13316
+ return error46;
13317
+ } else if (typeof error46 === "object" && error46 !== null) {
13318
+ try {
13319
+ return `${JSON.stringify(error46)}`;
13320
+ } catch {
13321
+ return "[cannot stringify error]";
13056
13322
  }
13057
- value = value[segment];
13323
+ } else {
13324
+ return `Unknown error: ${getErrorMessage(error46)}`;
13058
13325
  }
13059
- return value;
13060
13326
  }
13061
- function isRecord(value) {
13062
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
13063
- return false;
13327
+ function getErrorMessage(err) {
13328
+ if (err && typeof err === "object" && "message" in err && typeof err.message === "string") {
13329
+ return err.message;
13330
+ } else {
13331
+ return String(err);
13064
13332
  }
13065
- const prototype = Object.getPrototypeOf(value);
13066
- return prototype === Object.prototype || prototype === null;
13067
13333
  }
13068
- function formatActionPath(path2) {
13069
- return path2.length === 0 ? "actions" : `Action \`${path2.join(".")}\``;
13070
- }
13071
- var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
13072
- var ACTOR_CONTEXT_INTERNAL_SYMBOL = /* @__PURE__ */ Symbol(
13073
- "rivetkit.actor_context_internal"
13074
- );
13075
- var RAW_STATE_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.raw_state");
13076
- var CONN_STATE_MANAGER_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.conn_state_manager");
13077
- var zFunction = () => external_exports.custom((val) => typeof val === "function");
13078
- var zActionTree = external_exports.custom((value) => {
13079
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
13080
- return false;
13081
- }
13082
- const prototype = Object.getPrototypeOf(value);
13083
- return prototype === Object.prototype || prototype === null;
13084
- }).superRefine((actions, ctx) => {
13085
- try {
13086
- flattenActionHandlers(actions);
13087
- } catch (error46) {
13088
- ctx.addIssue({
13089
- code: "custom",
13090
- message: error46 instanceof Error ? error46.message : "Invalid action definition"
13091
- });
13092
- }
13093
- });
13094
- var WorkflowInspectorConfigSchema = external_exports.object({
13095
- getHistory: zFunction(),
13096
- getState: zFunction().optional(),
13097
- onHistoryUpdated: zFunction().optional(),
13098
- replayFromStep: zFunction().optional()
13099
- });
13100
- var RunInspectorConfigSchema = external_exports.object({
13101
- workflow: WorkflowInspectorConfigSchema.optional()
13102
- }).optional();
13103
- var BUILTIN_INSPECTOR_TAB_IDS = [
13104
- "workflow",
13105
- "database",
13106
- "state",
13107
- "queue",
13108
- "schedules",
13109
- "connections",
13110
- "console"
13111
- ];
13112
- var BuiltinInspectorTabIdSchema = external_exports.enum(BUILTIN_INSPECTOR_TAB_IDS);
13113
- var CUSTOM_INSPECTOR_TAB_ID_RE = /^[A-Za-z0-9_-]+$/;
13114
- var CustomInspectorTabEntrySchema = external_exports.object({
13115
- id: external_exports.string().regex(
13116
- CUSTOM_INSPECTOR_TAB_ID_RE,
13117
- "inspector.tabs[].id must contain only letters, digits, underscore, or dash"
13118
- ),
13119
- label: external_exports.string().min(1),
13120
- source: external_exports.string().min(1),
13121
- /**
13122
- * Optional icon id. The dashboard maps strings to glyphs (see its
13123
- * icon registry); unknown ids fall back to a generic icon.
13124
- */
13125
- icon: external_exports.string().min(1).optional(),
13126
- hidden: external_exports.literal(false).optional()
13127
- }).strict();
13128
- var HideInspectorTabEntrySchema = external_exports.object({
13129
- id: BuiltinInspectorTabIdSchema,
13130
- hidden: external_exports.literal(true)
13131
- }).strict();
13132
- var InspectorTabEntrySchema = external_exports.union([
13133
- CustomInspectorTabEntrySchema,
13134
- HideInspectorTabEntrySchema
13135
- ]);
13136
- var ActorInspectorConfigSchema = external_exports.object({
13137
- tabs: external_exports.array(InspectorTabEntrySchema).default(() => [])
13138
- }).strict().refine(
13139
- (data) => {
13140
- const ids = data.tabs.map((t) => t.id);
13141
- return new Set(ids).size === ids.length;
13142
- },
13143
- { message: "Duplicate id in inspector.tabs", path: ["tabs"] }
13144
- ).refine(
13145
- (data) => {
13146
- const builtinSet = new Set(BUILTIN_INSPECTOR_TAB_IDS);
13147
- return data.tabs.every(
13148
- (t) => t.hidden === true || !builtinSet.has(t.id)
13149
- );
13150
- },
13151
- {
13152
- message: "Custom inspector tab id collides with a built-in (use hidden: true to hide a built-in)",
13153
- path: ["tabs"]
13154
- }
13155
- );
13156
- var RunConfigSchema = external_exports.object({
13157
- /** Display name for the actor in the Inspector UI. */
13158
- name: external_exports.string().optional(),
13159
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
13160
- icon: external_exports.string().optional(),
13161
- /** The run handler function. */
13162
- run: zFunction(),
13163
- /** Inspector integration for long-running run handlers. */
13164
- inspector: RunInspectorConfigSchema.optional()
13165
- });
13166
- var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("rivetkit.run_function_config");
13167
- function defineRunHandler(run, options) {
13168
- if (options.inspectorKind === void 0 !== (options.createInspector === void 0)) {
13169
- throw new TypeError(
13170
- "defineRunHandler requires inspectorKind and createInspector together"
13171
- );
13172
- }
13173
- Object.defineProperty(run, RUN_FUNCTION_CONFIG_SYMBOL, {
13174
- configurable: false,
13175
- enumerable: false,
13176
- writable: false,
13177
- value: {
13178
- name: options.name,
13179
- icon: options.icon,
13180
- inspectorKind: options.inspectorKind,
13181
- createInspector: options.createInspector
13182
- }
13183
- });
13184
- return run;
13185
- }
13186
- function getRunInspectorKind(run) {
13187
- var _a2;
13188
- if (!run || typeof run !== "function") return void 0;
13189
- return (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.inspectorKind;
13190
- }
13191
- function createRunInspector(run, context2) {
13192
- var _a2, _b;
13193
- if (!run || typeof run !== "function") return void 0;
13194
- return (_b = (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.createInspector) == null ? void 0 : _b.call(_a2, context2);
13195
- }
13196
- var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
13197
- function getRunFunction(run) {
13198
- if (!run) return void 0;
13199
- if (typeof run === "function") return run;
13200
- return run.run;
13201
- }
13202
- function getRunMetadata(run) {
13203
- if (!run) return {};
13204
- if (typeof run === "function") {
13205
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13206
- if (!config3) return {};
13207
- return { name: config3.name, icon: config3.icon };
13208
- }
13209
- return { name: run.name, icon: run.icon };
13210
- }
13211
- function getRunInspectorConfig(run, actor2) {
13212
- if (!run) return void 0;
13213
- if (typeof run === "function") {
13214
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13215
- return (config3 == null ? void 0 : config3.inspectorFactory) ? config3.inspectorFactory(actor2) : config3 == null ? void 0 : config3.inspector;
13216
- }
13217
- return run.inspector;
13218
- }
13219
- function hasRunInspectorConfig(run) {
13220
- if (!run) return false;
13221
- if (typeof run !== "function") return run.inspector !== void 0;
13222
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13223
- 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;
13224
- }
13225
- function disposeRunInspector(run, actorId) {
13226
- var _a2;
13227
- if (!run || typeof run !== "function") {
13228
- return;
13229
- }
13230
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13231
- (_a2 = config3 == null ? void 0 : config3.disposeInspector) == null ? void 0 : _a2.call(config3, actorId);
13232
- }
13233
- var GlobalActorOptionsBaseSchema = external_exports.object({
13234
- /** Display name for the actor in the Inspector UI. */
13235
- name: external_exports.string().optional(),
13236
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
13237
- icon: external_exports.string().optional(),
13238
- /** Enables the experimental Actor Runtime Socket for this actor. */
13239
- enableActorRuntimeSocket: external_exports.boolean().default(false),
13240
- /**
13241
- * Can hibernate WebSockets for onWebSocket.
13242
- *
13243
- * WebSockets using actions/events are hibernatable by default.
13244
- *
13245
- * @experimental
13246
- **/
13247
- canHibernateWebSocket: external_exports.union([external_exports.boolean(), zFunction()]).default(false)
13248
- }).strict();
13249
- var GlobalActorOptionsSchema = GlobalActorOptionsBaseSchema.prefault(
13250
- () => ({})
13251
- );
13252
- var InstanceActorOptionsBaseSchema = external_exports.object({
13253
- createVarsTimeout: external_exports.number().positive().default(5e3),
13254
- createConnStateTimeout: external_exports.number().positive().default(5e3),
13255
- onBeforeConnectTimeout: external_exports.number().positive().default(5e3),
13256
- onConnectTimeout: external_exports.number().positive().default(5e3),
13257
- onMigrateTimeout: external_exports.number().positive().default(3e4),
13258
- sleepGracePeriod: external_exports.number().positive().default(DEFAULT_SLEEP_GRACE_PERIOD),
13259
- /** @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. */
13260
- onDestroyTimeout: external_exports.number().positive().optional(),
13261
- /** @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. */
13262
- waitUntilTimeout: external_exports.number().positive().optional(),
13263
- stateSaveInterval: external_exports.number().positive().default(1e3),
13264
- actionTimeout: external_exports.number().positive().default(6e4),
13265
- connectionLivenessTimeout: external_exports.number().positive().default(2500),
13266
- connectionLivenessInterval: external_exports.number().positive().default(5e3),
13267
- /** @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. */
13268
- noSleep: external_exports.boolean().default(false),
13269
- sleepTimeout: external_exports.number().positive().default(3e4),
13270
- maxQueueSize: external_exports.number().positive().default(1e3),
13271
- /** Maximum pending one-shot and recurring schedules. */
13272
- maxSchedules: external_exports.number().int().nonnegative().default(1e3),
13273
- maxQueueMessageSize: external_exports.number().positive().default(64 * 1024),
13274
- /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
13275
- preloadMaxWorkflowBytes: external_exports.number().nonnegative().optional(),
13276
- /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
13277
- preloadMaxConnectionsBytes: external_exports.number().nonnegative().optional()
13278
- }).strict();
13279
- var InstanceActorOptionsSchema = InstanceActorOptionsBaseSchema.prefault(() => ({}));
13280
- var ActorOptionsSchema = GlobalActorOptionsBaseSchema.extend(
13281
- InstanceActorOptionsBaseSchema.shape
13282
- ).strict().prefault(() => ({}));
13283
- var zSampleRate = external_exports.number().min(0).max(1);
13284
- var zActionSampleRates = external_exports.lazy(
13285
- () => external_exports.record(external_exports.string(), external_exports.union([zSampleRate, zActionSampleRates]))
13286
- );
13287
- var ActorConfigSchema = external_exports.object({
13288
- onCreate: zFunction().optional(),
13289
- onDestroy: zFunction().optional(),
13290
- onMigrate: zFunction().optional(),
13291
- onWake: zFunction().optional(),
13292
- onSleep: zFunction().optional(),
13293
- run: zRunHandler,
13294
- onStateChange: zFunction().optional(),
13295
- onBeforeConnect: zFunction().optional(),
13296
- onConnect: zFunction().optional(),
13297
- onDisconnect: zFunction().optional(),
13298
- onBeforeActionResponse: zFunction().optional(),
13299
- onRequest: zFunction().optional(),
13300
- onWebSocket: zFunction().optional(),
13301
- actions: zActionTree.default(() => ({})),
13302
- actionInputSchemas: external_exports.record(external_exports.string(), external_exports.any()).optional(),
13303
- tracing: external_exports.object({
13304
- sampler: zSampleRate.optional(),
13305
- actions: zActionSampleRates.optional()
13306
- }).strict().optional(),
13307
- connParamsSchema: external_exports.any().optional(),
13308
- events: external_exports.record(external_exports.string(), external_exports.any()).optional(),
13309
- queues: external_exports.record(external_exports.string(), external_exports.any()).optional(),
13310
- state: external_exports.any().optional(),
13311
- createState: zFunction().optional(),
13312
- connState: external_exports.any().optional(),
13313
- createConnState: zFunction().optional(),
13314
- vars: external_exports.any().optional(),
13315
- db: external_exports.any().optional(),
13316
- createVars: zFunction().optional(),
13317
- options: ActorOptionsSchema,
13318
- inspector: ActorInspectorConfigSchema.optional()
13319
- }).strict().refine(
13320
- (data) => !(data.state !== void 0 && data.createState !== void 0),
13321
- {
13322
- message: "Cannot define both 'state' and 'createState'",
13323
- path: ["state"]
13324
- }
13325
- ).refine(
13326
- (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
13327
- {
13328
- message: "Cannot define both 'connState' and 'createConnState'",
13329
- path: ["connState"]
13330
- }
13331
- ).refine(
13332
- (data) => !(data.vars !== void 0 && data.createVars !== void 0),
13333
- {
13334
- message: "Cannot define both 'vars' and 'createVars'",
13335
- path: ["vars"]
13336
- }
13337
- );
13338
- var DocActorOptionsSchema = external_exports.object({
13339
- name: external_exports.string().optional().describe("Display name for the actor in the Inspector UI."),
13340
- icon: external_exports.string().optional().describe(
13341
- "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
13342
- ),
13343
- enableActorRuntimeSocket: external_exports.boolean().optional().describe(
13344
- "Enables the experimental Actor Runtime Socket for this actor. Default: false"
13345
- ),
13346
- createVarsTimeout: external_exports.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
13347
- createConnStateTimeout: external_exports.number().optional().describe(
13348
- "Timeout in ms for createConnState handler. Default: 5000"
13349
- ),
13350
- onMigrateTimeout: external_exports.number().optional().describe("Timeout in ms for onMigrate handler. Default: 30000"),
13351
- onBeforeConnectTimeout: external_exports.number().optional().describe(
13352
- "Timeout in ms for onBeforeConnect handler. Default: 5000"
13353
- ),
13354
- onConnectTimeout: external_exports.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
13355
- sleepGracePeriod: external_exports.number().optional().describe(
13356
- `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}.`
13357
- ),
13358
- onDestroyTimeout: external_exports.number().optional().describe(
13359
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
13360
- ),
13361
- waitUntilTimeout: external_exports.number().optional().describe(
13362
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
13363
- ),
13364
- stateSaveInterval: external_exports.number().optional().describe(
13365
- "Interval in ms between automatic state saves. Default: 1000"
13366
- ),
13367
- actionTimeout: external_exports.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
13368
- connectionLivenessTimeout: external_exports.number().optional().describe(
13369
- "Timeout in ms for connection liveness checks. Default: 2500"
13370
- ),
13371
- connectionLivenessInterval: external_exports.number().optional().describe(
13372
- "Interval in ms between connection liveness checks. Default: 5000"
13373
- ),
13374
- noSleep: external_exports.boolean().optional().describe(
13375
- "Deprecated. If true, the actor will never sleep. Use c.keepAwake(promise) to scope keep-awake to a specific operation instead. Default: false"
13376
- ),
13377
- sleepTimeout: external_exports.number().optional().describe(
13378
- "Time in ms of inactivity before the actor sleeps. Default: 30000"
13379
- ),
13380
- maxQueueSize: external_exports.number().optional().describe(
13381
- "Maximum number of queue messages before rejecting new messages. Default: 1000"
13382
- ),
13383
- maxSchedules: external_exports.number().int().nonnegative().optional().describe(
13384
- "Maximum pending one-shot and recurring schedules before rejecting new schedules. Default: 1000"
13385
- ),
13386
- maxQueueMessageSize: external_exports.number().optional().describe(
13387
- "Maximum size of each queue message in bytes. Default: 65536"
13388
- ),
13389
- canHibernateWebSocket: external_exports.boolean().optional().describe(
13390
- "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
13391
- )
13392
- }).describe("Actor options for timeouts and behavior configuration.");
13393
- var DocActorConfigSchema = external_exports.object({
13394
- state: external_exports.unknown().optional().describe(
13395
- "Initial state value for the actor. Cannot be used with createState."
13396
- ),
13397
- createState: external_exports.unknown().optional().describe(
13398
- "Function to create initial state. Receives context and input. Cannot be used with state."
13399
- ),
13400
- connState: external_exports.unknown().optional().describe(
13401
- "Initial connection state value. Cannot be used with createConnState."
13402
- ),
13403
- createConnState: external_exports.unknown().optional().describe(
13404
- "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."
13405
- ),
13406
- vars: external_exports.unknown().optional().describe(
13407
- "Initial ephemeral variables value. Cannot be used with createVars."
13408
- ),
13409
- createVars: external_exports.unknown().optional().describe(
13410
- "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
13411
- ),
13412
- db: external_exports.unknown().optional().describe("Database provider instance for the actor."),
13413
- onCreate: external_exports.unknown().optional().describe(
13414
- "Called when the actor is first initialized. Use to initialize state."
13415
- ),
13416
- onDestroy: external_exports.unknown().optional().describe("Called when the actor is destroyed."),
13417
- onMigrate: external_exports.unknown().optional().describe(
13418
- "Called on every actor start after persisted state loads and before onWake. Use for repeatable schema migrations."
13419
- ),
13420
- onWake: external_exports.unknown().optional().describe(
13421
- "Called when the actor wakes up and is ready to receive connections and actions."
13422
- ),
13423
- onSleep: external_exports.unknown().optional().describe(
13424
- "Called when the actor is stopping or sleeping. Use to clean up resources."
13425
- ),
13426
- run: external_exports.unknown().optional().describe(
13427
- "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."
13428
- ),
13429
- onStateChange: external_exports.unknown().optional().describe(
13430
- "Called when the actor's state changes. State changes within this hook won't trigger recursion."
13431
- ),
13432
- onBeforeConnect: external_exports.unknown().optional().describe(
13433
- "Called before a client connects. Throw an error to reject the connection. The pending connection is not visible in c.conns while this runs."
13434
- ),
13435
- onConnect: external_exports.unknown().optional().describe(
13436
- "Called when a client successfully connects. The connection is visible in c.conns before this runs."
13437
- ),
13438
- onDisconnect: external_exports.unknown().optional().describe("Called when a client disconnects."),
13439
- onBeforeActionResponse: external_exports.unknown().optional().describe(
13440
- "Called before sending an action response. Use to transform output."
13441
- ),
13442
- onRequest: external_exports.unknown().optional().describe(
13443
- "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
13444
- ),
13445
- onWebSocket: external_exports.unknown().optional().describe(
13446
- "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
13447
- ),
13448
- actions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
13449
- "Tree of action names or nested groups to handler functions. Nested paths use dot-separated low-level action names. Defaults to an empty object."
13450
- ),
13451
- actionInputSchemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
13452
- "Optional schemas for validating action argument tuples in native runtimes. May mirror nested action groups or use dot-separated low-level action names."
13453
- ),
13454
- tracing: external_exports.unknown().optional().describe(
13455
- "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."
13456
- ),
13457
- connParamsSchema: external_exports.unknown().optional().describe(
13458
- "Optional schema for validating connection params in native runtimes."
13459
- ),
13460
- events: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of event names to schemas."),
13461
- queues: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of queue names to schemas."),
13462
- options: DocActorOptionsSchema.optional()
13463
- }).describe("Actor configuration passed to the actor() function.");
13464
-
13465
- // ../rivetkit/dist/tsup/chunk-P2OFXH4G.js
13466
- var INTERNAL_ERROR_CODE = "internal_error";
13467
- var INTERNAL_ERROR_DESCRIPTION = "An internal error occurred";
13468
- var USER_ERROR_CODE = "user_error";
13469
- var BRIDGE_RIVET_ERROR_PREFIX = "__RIVET_ERROR_JSON__:";
13470
- function looksLikeRivetErrorOptions(value) {
13471
- return typeof value === "object" && value !== null && ("public" in value || "metadata" in value || "rayId" in value || "statusCode" in value || "actor" in value || "cause" in value);
13472
- }
13473
- function isTypedErrorTag(value) {
13474
- return value === "ActorError" || value === "RivetError";
13475
- }
13476
- function errorMessage(error46, fallback = String(error46)) {
13477
- if (error46 && typeof error46 === "object" && "message" in error46 && typeof error46.message === "string") {
13478
- return error46.message;
13479
- }
13480
- return fallback;
13481
- }
13482
- function isRivetErrorLike(error46) {
13483
- 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));
13484
- }
13485
- function isActorAbortedError(error46) {
13486
- return isRivetErrorLike(error46) && error46.group === "actor" && error46.code === "aborted";
13487
- }
13488
- function isActorSpecifier(value) {
13489
- 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");
13490
- }
13491
- var RivetError = class extends Error {
13492
- __type = "RivetError";
13493
- public;
13494
- metadata;
13495
- rayId;
13496
- statusCode;
13497
- actor;
13498
- group;
13499
- code;
13500
- static isRivetError(error46) {
13501
- return isRivetErrorLike(error46);
13502
- }
13503
- static isActorError(error46) {
13504
- return isRivetErrorLike(error46);
13505
- }
13506
- constructor(group, code, message, options) {
13507
- const normalized = looksLikeRivetErrorOptions(options) ? options : { metadata: options };
13508
- super(message, { cause: normalized.cause });
13509
- this.name = "RivetError";
13510
- this.group = group;
13511
- this.code = code;
13512
- this.public = normalized.public ?? false;
13513
- this.metadata = normalized.metadata;
13514
- this.rayId = normalized.rayId ?? void 0;
13515
- this.statusCode = normalized.statusCode ?? (this.public ? 400 : 500);
13516
- this.actor = normalized.actor;
13517
- }
13518
- toString() {
13519
- return this.message;
13520
- }
13521
- };
13522
- var UserError = class extends RivetError {
13523
- constructor(message, options) {
13524
- super("user", (options == null ? void 0 : options.code) ?? USER_ERROR_CODE, message, {
13525
- public: true,
13526
- metadata: options == null ? void 0 : options.metadata,
13527
- cause: options == null ? void 0 : options.cause
13528
- });
13529
- }
13530
- };
13531
- function toRivetError(error46, fallback) {
13532
- if (typeof error46 === "string") {
13533
- const bridged = decodeBridgeRivetError(error46);
13534
- if (bridged) {
13535
- return bridged;
13536
- }
13537
- }
13538
- if (error46 instanceof Error) {
13539
- const bridged = decodeBridgeRivetError(error46.message);
13540
- if (bridged) {
13541
- return bridged;
13542
- }
13543
- }
13544
- if (isRivetErrorLike(error46)) {
13545
- return new RivetError(error46.group, error46.code, error46.message, {
13546
- public: error46.public,
13547
- statusCode: error46.statusCode,
13548
- metadata: error46.metadata,
13549
- rayId: error46.rayId,
13550
- actor: error46.actor,
13551
- cause: error46 instanceof Error ? error46.cause : void 0
13552
- });
13553
- }
13554
- return new RivetError(
13555
- (fallback == null ? void 0 : fallback.group) ?? "actor",
13556
- (fallback == null ? void 0 : fallback.code) ?? INTERNAL_ERROR_CODE,
13557
- errorMessage(error46, (fallback == null ? void 0 : fallback.message) ?? "Unknown error"),
13558
- {
13559
- public: fallback == null ? void 0 : fallback.public,
13560
- statusCode: fallback == null ? void 0 : fallback.statusCode,
13561
- metadata: fallback == null ? void 0 : fallback.metadata,
13562
- rayId: fallback == null ? void 0 : fallback.rayId,
13563
- actor: fallback == null ? void 0 : fallback.actor,
13564
- cause: error46 instanceof Error ? error46 : void 0
13565
- }
13566
- );
13567
- }
13568
- function encodeBridgeRivetError(error46) {
13569
- return `${BRIDGE_RIVET_ERROR_PREFIX}${JSON.stringify({
13570
- group: error46.group,
13571
- code: error46.code,
13572
- message: error46.message,
13573
- metadata: error46.metadata,
13574
- rayId: error46.rayId,
13575
- public: error46.public,
13576
- statusCode: error46.statusCode,
13577
- actor: error46.actor
13578
- })}`;
13579
- }
13580
- function encodeErrorForBridge(error46) {
13581
- if (isCanonicalStructuredRivetError(error46)) {
13582
- return encodeBridgeRivetError(error46);
13583
- }
13584
- return String(error46);
13585
- }
13586
- function isCanonicalStructuredRivetError(error46) {
13587
- 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";
13588
- }
13589
- function decodeBridgeRivetErrorPayload(value) {
13590
- if (!value.startsWith(BRIDGE_RIVET_ERROR_PREFIX)) {
13591
- return void 0;
13592
- }
13593
- try {
13594
- const raw = JSON.parse(
13595
- value.slice(BRIDGE_RIVET_ERROR_PREFIX.length)
13596
- );
13597
- const payload = {
13598
- ...raw,
13599
- rayId: raw.rayId ?? void 0
13600
- };
13601
- if (!isRivetErrorLike(payload)) {
13602
- return void 0;
13603
- }
13604
- if (payload.actor !== void 0 && payload.actor !== null && !isActorSpecifier(payload.actor)) {
13605
- return void 0;
13606
- }
13607
- return payload;
13608
- } catch {
13609
- return void 0;
13610
- }
13611
- }
13612
- function decodeBridgeRivetError(value) {
13613
- const payload = decodeBridgeRivetErrorPayload(value);
13614
- if (!payload) {
13615
- return void 0;
13616
- }
13617
- return new RivetError(payload.group, payload.code, payload.message, {
13618
- metadata: payload.metadata,
13619
- rayId: payload.rayId,
13620
- public: payload.public,
13621
- statusCode: payload.statusCode,
13622
- actor: payload.actor ?? void 0
13623
- });
13624
- }
13625
- function invalidRequest(error46) {
13626
- return new RivetError(
13627
- "request",
13628
- "invalid",
13629
- `Invalid request: ${errorMessage(error46, String(error46))}`,
13630
- {
13631
- public: true,
13632
- cause: error46 instanceof Error ? error46 : void 0
13633
- }
13634
- );
13635
- }
13636
- function actorNotFound(identifier) {
13637
- return new RivetError(
13638
- "actor",
13639
- "not_found",
13640
- identifier ? `Actor not found: ${identifier} (https://www.rivet.dev/docs/clients/javascript)` : "Actor not found (https://www.rivet.dev/docs/clients/javascript)",
13641
- { public: true }
13642
- );
13643
- }
13644
- function forbiddenError() {
13645
- return new RivetError("auth", "forbidden", "Forbidden", {
13646
- public: true,
13647
- statusCode: 403
13648
- });
13649
- }
13650
- function unsupportedFeature(feature) {
13651
- return new RivetError(
13652
- "feature",
13653
- "unsupported",
13654
- `Unsupported feature: ${feature}`
13655
- );
13656
- }
13657
-
13658
- // ../rivetkit/dist/tsup/chunk-DHWZTUKA.js
13659
- import {
13660
- pino,
13661
- stdTimeFunctions
13662
- } from "pino";
13663
- var import_invariant = __toESM(require_invariant(), 1);
13664
- import * as cbor from "cbor-x";
13665
- var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
13666
- var getRivetEndpoint = () => getEnvUniversal("RIVET_ENDPOINT");
13667
- var getRivetToken = () => getEnvUniversal("RIVET_TOKEN");
13668
- var getRivetNamespace = () => getEnvUniversal("RIVET_NAMESPACE");
13669
- var getRivetPool = () => getEnvUniversal("RIVET_POOL");
13670
- var getRivetTotalSlots = () => {
13671
- const value = getEnvUniversal("RIVET_TOTAL_SLOTS");
13672
- return value !== void 0 ? parseInt(value, 10) : void 0;
13673
- };
13674
- var getRivetRunEngine = () => getEnvUniversal("RIVET_RUN_ENGINE") === "1";
13675
- var getRivetRunEngineHost = () => getEnvUniversal("RIVET_RUN_ENGINE_HOST");
13676
- var getRivetRunEnginePort = () => {
13677
- const value = getEnvUniversal("RIVET_RUN_ENGINE_PORT");
13678
- return value !== void 0 ? parseInt(value, 10) : void 0;
13679
- };
13680
- var getRivetRunEngineVersion = () => getEnvUniversal("RIVET_RUN_ENGINE_VERSION");
13681
- var getRivetRunServices = () => {
13682
- const value = getEnvUniversal("RIVET_RUN_SERVICES");
13683
- return value === void 0 ? void 0 : value === "1";
13684
- };
13685
- var getRivetEnvoyVersion = () => {
13686
- const value = getEnvUniversal("RIVET_ENVOY_VERSION");
13687
- return value !== void 0 ? parseInt(value, 10) : void 0;
13688
- };
13689
- var getRivetPublicEndpoint = () => getEnvUniversal("RIVET_PUBLIC_ENDPOINT");
13690
- var getRivetPublicToken = () => getEnvUniversal("RIVET_PUBLIC_TOKEN");
13691
- var getRivetkitRuntime = () => getEnvUniversal("RIVETKIT_RUNTIME");
13692
- var getRivetkitRuntimeMode = () => {
13693
- const value = getEnvUniversal("RIVETKIT_RUNTIME_MODE");
13694
- if (value === void 0) return "envoy";
13695
- if (value === "envoy" || value === "serverless") return value;
13696
- throw new Error(
13697
- `RIVETKIT_RUNTIME_MODE env var must be "envoy" or "serverless"; got "${value}"`
13698
- );
13699
- };
13700
- var getRivetkitPublicDir = () => {
13701
- const value = getEnvUniversal("RIVETKIT_PUBLIC_DIR");
13702
- return value === void 0 || value === "" ? void 0 : value;
13703
- };
13704
- function parsePortEnv(raw) {
13705
- if (raw === void 0 || raw === "") return void 0;
13706
- const parsed = Number.parseInt(raw, 10);
13707
- if (!Number.isFinite(parsed) || parsed < 1 || parsed > 65535 || String(parsed) !== raw.trim()) {
13708
- throw new Error(
13709
- `RIVET_PORT env var must be an integer between 1 and 65535; got "${raw}"`
13710
- );
13711
- }
13712
- return parsed;
13713
- }
13714
- var getLogLevel = () => getEnvUniversal("RIVET_LOG_LEVEL") ?? getEnvUniversal("LOG_LEVEL");
13715
- var getLogTarget = () => getEnvUniversal("RIVET_LOG_TARGET") === "1";
13716
- var getLogTimestamp = () => getEnvUniversal("RIVET_LOG_TIMESTAMP") === "1";
13717
- var getLogMessage = () => getEnvUniversal("RIVET_LOG_MESSAGE") === "1";
13718
- var getLogErrorStack = () => getEnvUniversal("RIVET_LOG_ERROR_STACK") === "1";
13719
- var getNodeEnv = () => getEnvUniversal("NODE_ENV");
13720
- var getNextPhase = () => getEnvUniversal("NEXT_PHASE");
13721
- var isDev = () => getNodeEnv() !== "production";
13722
- function assertUnreachable(x) {
13723
- throw new Error(`Unreachable case: ${x}`);
13724
- }
13725
- function deconstructError(error46, exposeInternalError = false) {
13726
- let statusCode;
13727
- let public_;
13728
- let group;
13729
- let code;
13730
- let message;
13731
- let metadata;
13732
- let rayId;
13733
- let actor2;
13734
- if (isCanonicalStructuredRivetError(error46)) {
13735
- statusCode = typeof error46.statusCode === "number" ? error46.statusCode : error46.public ? 400 : 500;
13736
- public_ = error46.public ?? false;
13737
- group = error46.group;
13738
- code = error46.code;
13739
- message = error46.message;
13740
- metadata = error46.metadata;
13741
- rayId = error46.rayId;
13742
- actor2 = error46.actor;
13743
- } else if (RivetError.isActorError(error46) && error46.public) {
13744
- statusCode = "statusCode" in error46 && error46.statusCode ? error46.statusCode : 400;
13745
- public_ = true;
13746
- group = error46.group;
13747
- code = error46.code;
13748
- message = getErrorMessage(error46);
13749
- metadata = error46.metadata;
13750
- rayId = error46.rayId;
13751
- actor2 = error46.actor;
13752
- } else if (exposeInternalError) {
13753
- if (RivetError.isActorError(error46)) {
13754
- statusCode = 500;
13755
- public_ = false;
13756
- group = error46.group;
13757
- code = error46.code;
13758
- message = getErrorMessage(error46);
13759
- metadata = error46.metadata;
13760
- rayId = error46.rayId;
13761
- actor2 = error46.actor;
13762
- } else {
13763
- statusCode = 500;
13764
- public_ = false;
13765
- group = "rivetkit";
13766
- code = INTERNAL_ERROR_CODE;
13767
- message = getErrorMessage(error46);
13768
- }
13769
- } else {
13770
- statusCode = 500;
13771
- public_ = false;
13772
- group = "rivetkit";
13773
- code = INTERNAL_ERROR_CODE;
13774
- message = INTERNAL_ERROR_DESCRIPTION;
13775
- if (RivetError.isActorError(error46)) {
13776
- actor2 = error46.actor;
13777
- }
13778
- metadata = {
13779
- //url: `https://dashboard.rivet.dev/projects/${actorMetadata.project.slug}/environments/${actorMetadata.environment.slug}/actors?actorId=${actorMetadata.actor.id}`,
13780
- };
13781
- }
13782
- return {
13783
- __type: "ActorError",
13784
- statusCode,
13785
- public: public_,
13786
- group,
13787
- code,
13788
- message,
13789
- metadata,
13790
- rayId,
13791
- actor: actor2
13792
- };
13793
- }
13794
- function stringifyError(error46) {
13795
- if (error46 instanceof Error) {
13796
- if (typeof process !== "undefined" && getLogErrorStack()) {
13797
- let stack;
13798
- try {
13799
- stack = error46.stack;
13800
- } catch {
13801
- stack = void 0;
13802
- }
13803
- return `${error46.name}: ${error46.message}${stack ? `
13804
- ${stack}` : ""}`;
13805
- } else {
13806
- return `${error46.name}: ${error46.message}`;
13807
- }
13808
- } else if (typeof error46 === "string") {
13809
- return error46;
13810
- } else if (typeof error46 === "object" && error46 !== null) {
13811
- try {
13812
- return `${JSON.stringify(error46)}`;
13813
- } catch {
13814
- return "[cannot stringify error]";
13815
- }
13816
- } else {
13817
- return `Unknown error: ${getErrorMessage(error46)}`;
13818
- }
13819
- }
13820
- function getErrorMessage(err) {
13821
- if (err && typeof err === "object" && "message" in err && typeof err.message === "string") {
13822
- return err.message;
13823
- } else {
13824
- return String(err);
13825
- }
13826
- }
13827
- function noopNext() {
13828
- return async () => {
13829
- };
13334
+ function noopNext() {
13335
+ return async () => {
13336
+ };
13830
13337
  }
13831
13338
  var package_default = {
13832
13339
  name: "rivetkit",
13833
- version: "2.3.20",
13340
+ version: "2.3.21",
13834
13341
  description: "Lightweight libraries for building stateful actors on edge platforms",
13835
13342
  license: "Apache-2.0",
13836
13343
  keywords: [
@@ -14043,6 +13550,7 @@ var package_default = {
14043
13550
  "@rivet-dev/agent-os-core": "^0.1.1",
14044
13551
  "@rivet-dev/services": "^0.1.5",
14045
13552
  "@rivetkit/bare-ts": "^0.6.2",
13553
+ "@rivetkit/engine-api-full": "workspace:*",
14046
13554
  "@rivetkit/engine-cli": "workspace:*",
14047
13555
  "@rivetkit/engine-envoy-protocol": "workspace:*",
14048
13556
  "@rivetkit/on-change": "6.0.1",
@@ -15136,7 +14644,7 @@ function Config({ initialBufferLength = 1024, maxBufferLength = 1024 * 1024 * 32
15136
14644
  };
15137
14645
  }
15138
14646
 
15139
- // ../rivetkit/dist/tsup/chunk-SNNVRHLX.js
14647
+ // ../rivetkit/dist/tsup/chunk-CJXBGTVT.js
15140
14648
  var config2 = /* @__PURE__ */ Config({});
15141
14649
  function readWorkflowCbor(bc) {
15142
14650
  return readData(bc);
@@ -15259,180 +14767,675 @@ function readWorkflowSleepEntry(bc) {
15259
14767
  state: readWorkflowSleepState(bc)
15260
14768
  };
15261
14769
  }
15262
- function readWorkflowMessageEntry(bc) {
15263
- return {
15264
- name: readString(bc),
15265
- messageData: readWorkflowCbor(bc)
15266
- };
14770
+ function readWorkflowMessageEntry(bc) {
14771
+ return {
14772
+ name: readString(bc),
14773
+ messageData: readWorkflowCbor(bc)
14774
+ };
14775
+ }
14776
+ function readWorkflowRollbackCheckpointEntry(bc) {
14777
+ return {
14778
+ name: readString(bc)
14779
+ };
14780
+ }
14781
+ function readWorkflowBranchStatus(bc) {
14782
+ return {
14783
+ status: readWorkflowBranchStatusType(bc),
14784
+ output: read0(bc),
14785
+ error: read1(bc)
14786
+ };
14787
+ }
14788
+ function read2(bc) {
14789
+ const len = readUintSafe(bc);
14790
+ const result = /* @__PURE__ */ new Map();
14791
+ for (let i = 0; i < len; i++) {
14792
+ const offset = bc.offset;
14793
+ const key = readString(bc);
14794
+ if (result.has(key)) {
14795
+ bc.offset = offset;
14796
+ throw new BareError(offset, "duplicated key");
14797
+ }
14798
+ result.set(key, readWorkflowBranchStatus(bc));
14799
+ }
14800
+ return result;
14801
+ }
14802
+ function readWorkflowJoinEntry(bc) {
14803
+ return {
14804
+ branches: read2(bc)
14805
+ };
14806
+ }
14807
+ function readWorkflowRaceEntry(bc) {
14808
+ return {
14809
+ winner: read1(bc),
14810
+ branches: read2(bc)
14811
+ };
14812
+ }
14813
+ function readWorkflowRemovedEntry(bc) {
14814
+ return {
14815
+ originalType: readString(bc),
14816
+ originalName: read1(bc)
14817
+ };
14818
+ }
14819
+ function readWorkflowVersionCheckEntry(bc) {
14820
+ return {
14821
+ resolved: readU32(bc),
14822
+ latest: readU32(bc)
14823
+ };
14824
+ }
14825
+ function readWorkflowEntryKind(bc) {
14826
+ const offset = bc.offset;
14827
+ const tag = readU8(bc);
14828
+ switch (tag) {
14829
+ case 0:
14830
+ return { tag: "WorkflowStepEntry", val: readWorkflowStepEntry(bc) };
14831
+ case 1:
14832
+ return { tag: "WorkflowLoopEntry", val: readWorkflowLoopEntry(bc) };
14833
+ case 2:
14834
+ return {
14835
+ tag: "WorkflowSleepEntry",
14836
+ val: readWorkflowSleepEntry(bc)
14837
+ };
14838
+ case 3:
14839
+ return {
14840
+ tag: "WorkflowMessageEntry",
14841
+ val: readWorkflowMessageEntry(bc)
14842
+ };
14843
+ case 4:
14844
+ return {
14845
+ tag: "WorkflowRollbackCheckpointEntry",
14846
+ val: readWorkflowRollbackCheckpointEntry(bc)
14847
+ };
14848
+ case 5:
14849
+ return { tag: "WorkflowJoinEntry", val: readWorkflowJoinEntry(bc) };
14850
+ case 6:
14851
+ return { tag: "WorkflowRaceEntry", val: readWorkflowRaceEntry(bc) };
14852
+ case 7:
14853
+ return {
14854
+ tag: "WorkflowRemovedEntry",
14855
+ val: readWorkflowRemovedEntry(bc)
14856
+ };
14857
+ case 8:
14858
+ return {
14859
+ tag: "WorkflowVersionCheckEntry",
14860
+ val: readWorkflowVersionCheckEntry(bc)
14861
+ };
14862
+ default: {
14863
+ bc.offset = offset;
14864
+ throw new BareError(offset, "invalid tag");
14865
+ }
14866
+ }
14867
+ }
14868
+ function readWorkflowEntry(bc) {
14869
+ return {
14870
+ id: readString(bc),
14871
+ location: readWorkflowLocation(bc),
14872
+ kind: readWorkflowEntryKind(bc)
14873
+ };
14874
+ }
14875
+ function read3(bc) {
14876
+ return readBool(bc) ? readU64(bc) : null;
14877
+ }
14878
+ function readWorkflowEntryMetadata(bc) {
14879
+ return {
14880
+ status: readWorkflowEntryStatus(bc),
14881
+ error: read1(bc),
14882
+ attempts: readU32(bc),
14883
+ lastAttemptAt: readU64(bc),
14884
+ createdAt: readU64(bc),
14885
+ completedAt: read3(bc),
14886
+ rollbackCompletedAt: read3(bc),
14887
+ rollbackError: read1(bc)
14888
+ };
14889
+ }
14890
+ function read4(bc) {
14891
+ const len = readUintSafe(bc);
14892
+ if (len === 0) {
14893
+ return [];
14894
+ }
14895
+ const result = [readString(bc)];
14896
+ for (let i = 1; i < len; i++) {
14897
+ result[i] = readString(bc);
14898
+ }
14899
+ return result;
14900
+ }
14901
+ function read5(bc) {
14902
+ const len = readUintSafe(bc);
14903
+ if (len === 0) {
14904
+ return [];
14905
+ }
14906
+ const result = [readWorkflowEntry(bc)];
14907
+ for (let i = 1; i < len; i++) {
14908
+ result[i] = readWorkflowEntry(bc);
14909
+ }
14910
+ return result;
14911
+ }
14912
+ function read6(bc) {
14913
+ const len = readUintSafe(bc);
14914
+ const result = /* @__PURE__ */ new Map();
14915
+ for (let i = 0; i < len; i++) {
14916
+ const offset = bc.offset;
14917
+ const key = readString(bc);
14918
+ if (result.has(key)) {
14919
+ bc.offset = offset;
14920
+ throw new BareError(offset, "duplicated key");
14921
+ }
14922
+ result.set(key, readWorkflowEntryMetadata(bc));
14923
+ }
14924
+ return result;
14925
+ }
14926
+ function readWorkflowHistory(bc) {
14927
+ return {
14928
+ nameRegistry: read4(bc),
14929
+ entries: read5(bc),
14930
+ entryMetadata: read6(bc)
14931
+ };
14932
+ }
14933
+ function decodeWorkflowHistory(bytes) {
14934
+ const bc = new ByteCursor(bytes, config2);
14935
+ const result = readWorkflowHistory(bc);
14936
+ if (bc.offset < bc.view.byteLength) {
14937
+ throw new BareError(bc.offset, "remaining bytes");
14938
+ }
14939
+ return result;
14940
+ }
14941
+ function decodeWorkflowHistoryTransport(data) {
14942
+ return decodeWorkflowHistory(toUint8Array(data));
14943
+ }
14944
+
14945
+ // ../rivetkit/dist/tsup/chunk-CSOHAAZK.js
14946
+ function flattenActionHandlers(actions) {
14947
+ const flattened = /* @__PURE__ */ Object.create(null);
14948
+ for (const { name, handler } of collectActionEntries(actions)) {
14949
+ flattened[name] = handler;
14950
+ }
14951
+ return flattened;
14952
+ }
14953
+ function flattenActionInputSchemas(actions, schemas) {
14954
+ if (schemas === void 0) return void 0;
14955
+ if (!isRecord(schemas)) {
14956
+ throw new TypeError("actionInputSchemas must be an object");
14957
+ }
14958
+ const flattened = /* @__PURE__ */ Object.create(null);
14959
+ for (const { name, path: path2 } of collectActionEntries(actions)) {
14960
+ const nestedSchema = lookupNestedSchema(schemas, path2);
14961
+ const flatSchema = schemas[name];
14962
+ if (nestedSchema !== void 0 && flatSchema !== void 0 && nestedSchema !== flatSchema) {
14963
+ throw new TypeError(
14964
+ `Action input schema \`${name}\` is defined by both a nested path and a dotted key`
14965
+ );
14966
+ }
14967
+ const schema = nestedSchema ?? flatSchema;
14968
+ if (schema !== void 0) {
14969
+ flattened[name] = schema;
14970
+ }
14971
+ }
14972
+ return flattened;
14973
+ }
14974
+ function flattenActionTraceSamplers(actions, rates = {}) {
14975
+ const handlers = flattenActionHandlers(actions);
14976
+ const flattened = Object.fromEntries(flattenSampleRates(rates, []));
14977
+ for (const name of Object.keys(flattened)) {
14978
+ if (!Object.hasOwn(handlers, name)) {
14979
+ throw new TypeError(
14980
+ `tracing.actions.${name} does not name an action`
14981
+ );
14982
+ }
14983
+ }
14984
+ return flattened;
15267
14985
  }
15268
- function readWorkflowRollbackCheckpointEntry(bc) {
15269
- return {
15270
- name: readString(bc)
15271
- };
14986
+ function flattenSampleRates(rates, path2) {
14987
+ return Object.entries(rates).flatMap(
14988
+ ([segment, rate]) => {
14989
+ const childPath = [...path2, segment];
14990
+ return typeof rate === "number" ? [[childPath.join("."), rate]] : flattenSampleRates(rate, childPath);
14991
+ }
14992
+ );
15272
14993
  }
15273
- function readWorkflowBranchStatus(bc) {
15274
- return {
15275
- status: readWorkflowBranchStatusType(bc),
15276
- output: read0(bc),
15277
- error: read1(bc)
15278
- };
14994
+ function collectActionEntries(actions) {
14995
+ const entries = [];
14996
+ const names = /* @__PURE__ */ new Set();
14997
+ visitActionGroup(actions ?? {}, [], entries, names);
14998
+ return entries;
15279
14999
  }
15280
- function read2(bc) {
15281
- const len = readUintSafe(bc);
15282
- const result = /* @__PURE__ */ new Map();
15283
- for (let i = 0; i < len; i++) {
15284
- const offset = bc.offset;
15285
- const key = readString(bc);
15286
- if (result.has(key)) {
15287
- bc.offset = offset;
15288
- throw new BareError(offset, "duplicated key");
15000
+ function visitActionGroup(value, path2, entries, names) {
15001
+ if (!isRecord(value)) {
15002
+ throw new TypeError(
15003
+ `${formatActionPath(path2)} must be an action handler or group`
15004
+ );
15005
+ }
15006
+ for (const [segment, child] of Object.entries(value)) {
15007
+ const childPath = [...path2, segment];
15008
+ if (typeof child === "function") {
15009
+ const name = childPath.join(".");
15010
+ if (names.has(name)) {
15011
+ throw new TypeError(
15012
+ `Multiple action definitions flatten to \`${name}\``
15013
+ );
15014
+ }
15015
+ names.add(name);
15016
+ entries.push({
15017
+ name,
15018
+ path: childPath,
15019
+ handler: child
15020
+ });
15021
+ } else {
15022
+ visitActionGroup(child, childPath, entries, names);
15289
15023
  }
15290
- result.set(key, readWorkflowBranchStatus(bc));
15291
15024
  }
15292
- return result;
15293
- }
15294
- function readWorkflowJoinEntry(bc) {
15295
- return {
15296
- branches: read2(bc)
15297
- };
15298
15025
  }
15299
- function readWorkflowRaceEntry(bc) {
15300
- return {
15301
- winner: read1(bc),
15302
- branches: read2(bc)
15303
- };
15026
+ function lookupNestedSchema(schemas, path2) {
15027
+ let value = schemas;
15028
+ for (const segment of path2) {
15029
+ if (!isRecord(value) || !Object.hasOwn(value, segment)) {
15030
+ return void 0;
15031
+ }
15032
+ value = value[segment];
15033
+ }
15034
+ return value;
15304
15035
  }
15305
- function readWorkflowRemovedEntry(bc) {
15306
- return {
15307
- originalType: readString(bc),
15308
- originalName: read1(bc)
15309
- };
15036
+ function isRecord(value) {
15037
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
15038
+ return false;
15039
+ }
15040
+ const prototype = Object.getPrototypeOf(value);
15041
+ return prototype === Object.prototype || prototype === null;
15310
15042
  }
15311
- function readWorkflowVersionCheckEntry(bc) {
15312
- return {
15313
- resolved: readU32(bc),
15314
- latest: readU32(bc)
15315
- };
15043
+ function formatActionPath(path2) {
15044
+ return path2.length === 0 ? "actions" : `Action \`${path2.join(".")}\``;
15316
15045
  }
15317
- function readWorkflowEntryKind(bc) {
15318
- const offset = bc.offset;
15319
- const tag = readU8(bc);
15320
- switch (tag) {
15321
- case 0:
15322
- return { tag: "WorkflowStepEntry", val: readWorkflowStepEntry(bc) };
15323
- case 1:
15324
- return { tag: "WorkflowLoopEntry", val: readWorkflowLoopEntry(bc) };
15325
- case 2:
15326
- return {
15327
- tag: "WorkflowSleepEntry",
15328
- val: readWorkflowSleepEntry(bc)
15329
- };
15330
- case 3:
15331
- return {
15332
- tag: "WorkflowMessageEntry",
15333
- val: readWorkflowMessageEntry(bc)
15334
- };
15335
- case 4:
15336
- return {
15337
- tag: "WorkflowRollbackCheckpointEntry",
15338
- val: readWorkflowRollbackCheckpointEntry(bc)
15339
- };
15340
- case 5:
15341
- return { tag: "WorkflowJoinEntry", val: readWorkflowJoinEntry(bc) };
15342
- case 6:
15343
- return { tag: "WorkflowRaceEntry", val: readWorkflowRaceEntry(bc) };
15344
- case 7:
15345
- return {
15346
- tag: "WorkflowRemovedEntry",
15347
- val: readWorkflowRemovedEntry(bc)
15348
- };
15349
- case 8:
15350
- return {
15351
- tag: "WorkflowVersionCheckEntry",
15352
- val: readWorkflowVersionCheckEntry(bc)
15353
- };
15354
- default: {
15355
- bc.offset = offset;
15356
- throw new BareError(offset, "invalid tag");
15357
- }
15046
+ var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
15047
+ var ACTOR_CONTEXT_INTERNAL_SYMBOL = /* @__PURE__ */ Symbol(
15048
+ "rivetkit.actor_context_internal"
15049
+ );
15050
+ var RAW_STATE_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.raw_state");
15051
+ var CONN_STATE_MANAGER_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.conn_state_manager");
15052
+ var zFunction = () => external_exports.custom((val) => typeof val === "function");
15053
+ var zActionTree = external_exports.custom((value) => {
15054
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
15055
+ return false;
15056
+ }
15057
+ const prototype = Object.getPrototypeOf(value);
15058
+ return prototype === Object.prototype || prototype === null;
15059
+ }).superRefine((actions, ctx) => {
15060
+ try {
15061
+ flattenActionHandlers(actions);
15062
+ } catch (error46) {
15063
+ ctx.addIssue({
15064
+ code: "custom",
15065
+ message: error46 instanceof Error ? error46.message : "Invalid action definition"
15066
+ });
15067
+ }
15068
+ });
15069
+ var WorkflowInspectorConfigSchema = external_exports.object({
15070
+ getHistory: zFunction(),
15071
+ getState: zFunction().optional(),
15072
+ onHistoryUpdated: zFunction().optional(),
15073
+ replayFromStep: zFunction().optional()
15074
+ });
15075
+ var RunInspectorConfigSchema = external_exports.object({
15076
+ workflow: WorkflowInspectorConfigSchema.optional()
15077
+ }).optional();
15078
+ var BUILTIN_INSPECTOR_TAB_IDS = [
15079
+ "workflow",
15080
+ "database",
15081
+ "state",
15082
+ "queue",
15083
+ "schedules",
15084
+ "connections",
15085
+ "console"
15086
+ ];
15087
+ var BuiltinInspectorTabIdSchema = external_exports.enum(BUILTIN_INSPECTOR_TAB_IDS);
15088
+ var CUSTOM_INSPECTOR_TAB_ID_RE = /^[A-Za-z0-9_-]+$/;
15089
+ var CustomInspectorTabEntrySchema = external_exports.object({
15090
+ id: external_exports.string().regex(
15091
+ CUSTOM_INSPECTOR_TAB_ID_RE,
15092
+ "inspector.tabs[].id must contain only letters, digits, underscore, or dash"
15093
+ ),
15094
+ label: external_exports.string().min(1),
15095
+ source: external_exports.string().min(1),
15096
+ /**
15097
+ * Optional icon id. The dashboard maps strings to glyphs (see its
15098
+ * icon registry); unknown ids fall back to a generic icon.
15099
+ */
15100
+ icon: external_exports.string().min(1).optional(),
15101
+ hidden: external_exports.literal(false).optional()
15102
+ }).strict();
15103
+ var HideInspectorTabEntrySchema = external_exports.object({
15104
+ id: BuiltinInspectorTabIdSchema,
15105
+ hidden: external_exports.literal(true)
15106
+ }).strict();
15107
+ var InspectorTabEntrySchema = external_exports.union([
15108
+ CustomInspectorTabEntrySchema,
15109
+ HideInspectorTabEntrySchema
15110
+ ]);
15111
+ var ActorInspectorConfigSchema = external_exports.object({
15112
+ tabs: external_exports.array(InspectorTabEntrySchema).default(() => [])
15113
+ }).strict().refine(
15114
+ (data) => {
15115
+ const ids = data.tabs.map((t) => t.id);
15116
+ return new Set(ids).size === ids.length;
15117
+ },
15118
+ { message: "Duplicate id in inspector.tabs", path: ["tabs"] }
15119
+ ).refine(
15120
+ (data) => {
15121
+ const builtinSet = new Set(BUILTIN_INSPECTOR_TAB_IDS);
15122
+ return data.tabs.every(
15123
+ (t) => t.hidden === true || !builtinSet.has(t.id)
15124
+ );
15125
+ },
15126
+ {
15127
+ message: "Custom inspector tab id collides with a built-in (use hidden: true to hide a built-in)",
15128
+ path: ["tabs"]
15129
+ }
15130
+ );
15131
+ var RunConfigSchema = external_exports.object({
15132
+ /** Display name for the actor in the Inspector UI. */
15133
+ name: external_exports.string().optional(),
15134
+ /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
15135
+ icon: external_exports.string().optional(),
15136
+ /** The run handler function. */
15137
+ run: zFunction(),
15138
+ /** Inspector integration for long-running run handlers. */
15139
+ inspector: RunInspectorConfigSchema.optional()
15140
+ });
15141
+ var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("rivetkit.run_function_config");
15142
+ function defineRunHandler(run, options) {
15143
+ if (options.inspectorKind === void 0 !== (options.createInspector === void 0)) {
15144
+ throw new TypeError(
15145
+ "defineRunHandler requires inspectorKind and createInspector together"
15146
+ );
15358
15147
  }
15148
+ Object.defineProperty(run, RUN_FUNCTION_CONFIG_SYMBOL, {
15149
+ configurable: false,
15150
+ enumerable: false,
15151
+ writable: false,
15152
+ value: {
15153
+ name: options.name,
15154
+ icon: options.icon,
15155
+ inspectorKind: options.inspectorKind,
15156
+ createInspector: options.createInspector
15157
+ }
15158
+ });
15159
+ return run;
15359
15160
  }
15360
- function readWorkflowEntry(bc) {
15361
- return {
15362
- id: readString(bc),
15363
- location: readWorkflowLocation(bc),
15364
- kind: readWorkflowEntryKind(bc)
15365
- };
15366
- }
15367
- function read3(bc) {
15368
- return readBool(bc) ? readU64(bc) : null;
15161
+ function getRunInspectorKind(run) {
15162
+ var _a2;
15163
+ if (!run || typeof run !== "function") return void 0;
15164
+ return (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.inspectorKind;
15369
15165
  }
15370
- function readWorkflowEntryMetadata(bc) {
15371
- return {
15372
- status: readWorkflowEntryStatus(bc),
15373
- error: read1(bc),
15374
- attempts: readU32(bc),
15375
- lastAttemptAt: readU64(bc),
15376
- createdAt: readU64(bc),
15377
- completedAt: read3(bc),
15378
- rollbackCompletedAt: read3(bc),
15379
- rollbackError: read1(bc)
15380
- };
15166
+ function createRunInspector(run, context2) {
15167
+ var _a2, _b;
15168
+ if (!run || typeof run !== "function") return void 0;
15169
+ return (_b = (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.createInspector) == null ? void 0 : _b.call(_a2, context2);
15381
15170
  }
15382
- function read4(bc) {
15383
- const len = readUintSafe(bc);
15384
- if (len === 0) {
15385
- return [];
15386
- }
15387
- const result = [readString(bc)];
15388
- for (let i = 1; i < len; i++) {
15389
- result[i] = readString(bc);
15390
- }
15391
- return result;
15171
+ var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
15172
+ function getRunFunction(run) {
15173
+ if (!run) return void 0;
15174
+ if (typeof run === "function") return run;
15175
+ return run.run;
15392
15176
  }
15393
- function read5(bc) {
15394
- const len = readUintSafe(bc);
15395
- if (len === 0) {
15396
- return [];
15397
- }
15398
- const result = [readWorkflowEntry(bc)];
15399
- for (let i = 1; i < len; i++) {
15400
- result[i] = readWorkflowEntry(bc);
15177
+ function getRunMetadata(run) {
15178
+ if (!run) return {};
15179
+ if (typeof run === "function") {
15180
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15181
+ if (!config3) return {};
15182
+ return { name: config3.name, icon: config3.icon };
15401
15183
  }
15402
- return result;
15184
+ return { name: run.name, icon: run.icon };
15403
15185
  }
15404
- function read6(bc) {
15405
- const len = readUintSafe(bc);
15406
- const result = /* @__PURE__ */ new Map();
15407
- for (let i = 0; i < len; i++) {
15408
- const offset = bc.offset;
15409
- const key = readString(bc);
15410
- if (result.has(key)) {
15411
- bc.offset = offset;
15412
- throw new BareError(offset, "duplicated key");
15413
- }
15414
- result.set(key, readWorkflowEntryMetadata(bc));
15186
+ function getRunInspectorConfig(run, actor2) {
15187
+ if (!run) return void 0;
15188
+ if (typeof run === "function") {
15189
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15190
+ return (config3 == null ? void 0 : config3.inspectorFactory) ? config3.inspectorFactory(actor2) : config3 == null ? void 0 : config3.inspector;
15415
15191
  }
15416
- return result;
15192
+ return run.inspector;
15417
15193
  }
15418
- function readWorkflowHistory(bc) {
15419
- return {
15420
- nameRegistry: read4(bc),
15421
- entries: read5(bc),
15422
- entryMetadata: read6(bc)
15423
- };
15194
+ function hasRunInspectorConfig(run) {
15195
+ if (!run) return false;
15196
+ if (typeof run !== "function") return run.inspector !== void 0;
15197
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15198
+ 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;
15424
15199
  }
15425
- function decodeWorkflowHistory(bytes) {
15426
- const bc = new ByteCursor(bytes, config2);
15427
- const result = readWorkflowHistory(bc);
15428
- if (bc.offset < bc.view.byteLength) {
15429
- throw new BareError(bc.offset, "remaining bytes");
15200
+ function disposeRunInspector(run, actorId) {
15201
+ var _a2;
15202
+ if (!run || typeof run !== "function") {
15203
+ return;
15430
15204
  }
15431
- return result;
15432
- }
15433
- function decodeWorkflowHistoryTransport(data) {
15434
- return decodeWorkflowHistory(toUint8Array(data));
15205
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15206
+ (_a2 = config3 == null ? void 0 : config3.disposeInspector) == null ? void 0 : _a2.call(config3, actorId);
15435
15207
  }
15208
+ var GlobalActorOptionsBaseSchema = external_exports.object({
15209
+ /** Display name for the actor in the Inspector UI. */
15210
+ name: external_exports.string().optional(),
15211
+ /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
15212
+ icon: external_exports.string().optional(),
15213
+ /** Enables the experimental Actor Runtime Socket for this actor. */
15214
+ enableActorRuntimeSocket: external_exports.boolean().default(false),
15215
+ /**
15216
+ * Can hibernate WebSockets for onWebSocket.
15217
+ *
15218
+ * WebSockets using actions/events are hibernatable by default.
15219
+ *
15220
+ * @experimental
15221
+ **/
15222
+ canHibernateWebSocket: external_exports.union([external_exports.boolean(), zFunction()]).default(false)
15223
+ }).strict();
15224
+ var GlobalActorOptionsSchema = GlobalActorOptionsBaseSchema.prefault(
15225
+ () => ({})
15226
+ );
15227
+ var InstanceActorOptionsBaseSchema = external_exports.object({
15228
+ createVarsTimeout: external_exports.number().positive().default(5e3),
15229
+ createConnStateTimeout: external_exports.number().positive().default(5e3),
15230
+ onBeforeConnectTimeout: external_exports.number().positive().default(5e3),
15231
+ onConnectTimeout: external_exports.number().positive().default(5e3),
15232
+ onMigrateTimeout: external_exports.number().positive().default(3e4),
15233
+ sleepGracePeriod: external_exports.number().positive().default(DEFAULT_SLEEP_GRACE_PERIOD),
15234
+ /** @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. */
15235
+ onDestroyTimeout: external_exports.number().positive().optional(),
15236
+ /** @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. */
15237
+ waitUntilTimeout: external_exports.number().positive().optional(),
15238
+ stateSaveInterval: external_exports.number().positive().default(1e3),
15239
+ actionTimeout: external_exports.number().positive().default(6e4),
15240
+ connectionLivenessTimeout: external_exports.number().positive().default(2500),
15241
+ connectionLivenessInterval: external_exports.number().positive().default(5e3),
15242
+ /** @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. */
15243
+ noSleep: external_exports.boolean().default(false),
15244
+ sleepTimeout: external_exports.number().positive().default(3e4),
15245
+ maxQueueSize: external_exports.number().positive().default(1e3),
15246
+ /** Maximum pending one-shot and recurring schedules. */
15247
+ maxSchedules: external_exports.number().int().nonnegative().default(1e3),
15248
+ maxQueueMessageSize: external_exports.number().positive().default(64 * 1024),
15249
+ /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
15250
+ preloadMaxWorkflowBytes: external_exports.number().nonnegative().optional(),
15251
+ /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
15252
+ preloadMaxConnectionsBytes: external_exports.number().nonnegative().optional()
15253
+ }).strict();
15254
+ var InstanceActorOptionsSchema = InstanceActorOptionsBaseSchema.prefault(() => ({}));
15255
+ var ActorOptionsSchema = GlobalActorOptionsBaseSchema.extend(
15256
+ InstanceActorOptionsBaseSchema.shape
15257
+ ).strict().prefault(() => ({}));
15258
+ var zSampleRate = external_exports.number().min(0).max(1);
15259
+ var zActionSampleRates = external_exports.lazy(
15260
+ () => external_exports.record(external_exports.string(), external_exports.union([zSampleRate, zActionSampleRates]))
15261
+ );
15262
+ var ActorConfigSchema = external_exports.object({
15263
+ onCreate: zFunction().optional(),
15264
+ onDestroy: zFunction().optional(),
15265
+ onMigrate: zFunction().optional(),
15266
+ onWake: zFunction().optional(),
15267
+ onSleep: zFunction().optional(),
15268
+ run: zRunHandler,
15269
+ onStateChange: zFunction().optional(),
15270
+ onBeforeConnect: zFunction().optional(),
15271
+ onConnect: zFunction().optional(),
15272
+ onDisconnect: zFunction().optional(),
15273
+ onBeforeActionResponse: zFunction().optional(),
15274
+ onRequest: zFunction().optional(),
15275
+ onWebSocket: zFunction().optional(),
15276
+ actions: zActionTree.default(() => ({})),
15277
+ actionInputSchemas: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15278
+ tracing: external_exports.object({
15279
+ sampler: zSampleRate.optional(),
15280
+ actions: zActionSampleRates.optional()
15281
+ }).strict().optional(),
15282
+ connParamsSchema: external_exports.any().optional(),
15283
+ events: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15284
+ queues: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15285
+ state: external_exports.any().optional(),
15286
+ createState: zFunction().optional(),
15287
+ connState: external_exports.any().optional(),
15288
+ createConnState: zFunction().optional(),
15289
+ vars: external_exports.any().optional(),
15290
+ db: external_exports.any().optional(),
15291
+ createVars: zFunction().optional(),
15292
+ options: ActorOptionsSchema,
15293
+ inspector: ActorInspectorConfigSchema.optional()
15294
+ }).strict().refine(
15295
+ (data) => !(data.state !== void 0 && data.createState !== void 0),
15296
+ {
15297
+ message: "Cannot define both 'state' and 'createState'",
15298
+ path: ["state"]
15299
+ }
15300
+ ).refine(
15301
+ (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
15302
+ {
15303
+ message: "Cannot define both 'connState' and 'createConnState'",
15304
+ path: ["connState"]
15305
+ }
15306
+ ).refine(
15307
+ (data) => !(data.vars !== void 0 && data.createVars !== void 0),
15308
+ {
15309
+ message: "Cannot define both 'vars' and 'createVars'",
15310
+ path: ["vars"]
15311
+ }
15312
+ );
15313
+ var DocActorOptionsSchema = external_exports.object({
15314
+ name: external_exports.string().optional().describe("Display name for the actor in the Inspector UI."),
15315
+ icon: external_exports.string().optional().describe(
15316
+ "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
15317
+ ),
15318
+ enableActorRuntimeSocket: external_exports.boolean().optional().describe(
15319
+ "Enables the experimental Actor Runtime Socket for this actor. Default: false"
15320
+ ),
15321
+ createVarsTimeout: external_exports.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
15322
+ createConnStateTimeout: external_exports.number().optional().describe(
15323
+ "Timeout in ms for createConnState handler. Default: 5000"
15324
+ ),
15325
+ onMigrateTimeout: external_exports.number().optional().describe("Timeout in ms for onMigrate handler. Default: 30000"),
15326
+ onBeforeConnectTimeout: external_exports.number().optional().describe(
15327
+ "Timeout in ms for onBeforeConnect handler. Default: 5000"
15328
+ ),
15329
+ onConnectTimeout: external_exports.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
15330
+ sleepGracePeriod: external_exports.number().optional().describe(
15331
+ `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}.`
15332
+ ),
15333
+ onDestroyTimeout: external_exports.number().optional().describe(
15334
+ "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
15335
+ ),
15336
+ waitUntilTimeout: external_exports.number().optional().describe(
15337
+ "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
15338
+ ),
15339
+ stateSaveInterval: external_exports.number().optional().describe(
15340
+ "Interval in ms between automatic state saves. Default: 1000"
15341
+ ),
15342
+ actionTimeout: external_exports.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
15343
+ connectionLivenessTimeout: external_exports.number().optional().describe(
15344
+ "Timeout in ms for connection liveness checks. Default: 2500"
15345
+ ),
15346
+ connectionLivenessInterval: external_exports.number().optional().describe(
15347
+ "Interval in ms between connection liveness checks. Default: 5000"
15348
+ ),
15349
+ noSleep: external_exports.boolean().optional().describe(
15350
+ "Deprecated. If true, the actor will never sleep. Use c.keepAwake(promise) to scope keep-awake to a specific operation instead. Default: false"
15351
+ ),
15352
+ sleepTimeout: external_exports.number().optional().describe(
15353
+ "Time in ms of inactivity before the actor sleeps. Default: 30000"
15354
+ ),
15355
+ maxQueueSize: external_exports.number().optional().describe(
15356
+ "Maximum number of queue messages before rejecting new messages. Default: 1000"
15357
+ ),
15358
+ maxSchedules: external_exports.number().int().nonnegative().optional().describe(
15359
+ "Maximum pending one-shot and recurring schedules before rejecting new schedules. Default: 1000"
15360
+ ),
15361
+ maxQueueMessageSize: external_exports.number().optional().describe(
15362
+ "Maximum size of each queue message in bytes. Default: 65536"
15363
+ ),
15364
+ canHibernateWebSocket: external_exports.boolean().optional().describe(
15365
+ "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
15366
+ )
15367
+ }).describe("Actor options for timeouts and behavior configuration.");
15368
+ var DocActorConfigSchema = external_exports.object({
15369
+ state: external_exports.unknown().optional().describe(
15370
+ "Initial state value for the actor. Cannot be used with createState."
15371
+ ),
15372
+ createState: external_exports.unknown().optional().describe(
15373
+ "Function to create initial state. Receives context and input. Cannot be used with state."
15374
+ ),
15375
+ connState: external_exports.unknown().optional().describe(
15376
+ "Initial connection state value. Cannot be used with createConnState."
15377
+ ),
15378
+ createConnState: external_exports.unknown().optional().describe(
15379
+ "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."
15380
+ ),
15381
+ vars: external_exports.unknown().optional().describe(
15382
+ "Initial ephemeral variables value. Cannot be used with createVars."
15383
+ ),
15384
+ createVars: external_exports.unknown().optional().describe(
15385
+ "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
15386
+ ),
15387
+ db: external_exports.unknown().optional().describe("Database provider instance for the actor."),
15388
+ onCreate: external_exports.unknown().optional().describe(
15389
+ "Called when the actor is first initialized. Use to initialize state."
15390
+ ),
15391
+ onDestroy: external_exports.unknown().optional().describe("Called when the actor is destroyed."),
15392
+ onMigrate: external_exports.unknown().optional().describe(
15393
+ "Called on every actor start after persisted state loads and before onWake. Use for repeatable schema migrations."
15394
+ ),
15395
+ onWake: external_exports.unknown().optional().describe(
15396
+ "Called when the actor wakes up and is ready to receive connections and actions."
15397
+ ),
15398
+ onSleep: external_exports.unknown().optional().describe(
15399
+ "Called when the actor is stopping or sleeping. Use to clean up resources."
15400
+ ),
15401
+ run: external_exports.unknown().optional().describe(
15402
+ "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."
15403
+ ),
15404
+ onStateChange: external_exports.unknown().optional().describe(
15405
+ "Called when the actor's state changes. State changes within this hook won't trigger recursion."
15406
+ ),
15407
+ onBeforeConnect: external_exports.unknown().optional().describe(
15408
+ "Called before a client connects. Throw an error to reject the connection. The pending connection is not visible in c.conns while this runs."
15409
+ ),
15410
+ onConnect: external_exports.unknown().optional().describe(
15411
+ "Called when a client successfully connects. The connection is visible in c.conns before this runs."
15412
+ ),
15413
+ onDisconnect: external_exports.unknown().optional().describe("Called when a client disconnects."),
15414
+ onBeforeActionResponse: external_exports.unknown().optional().describe(
15415
+ "Called before sending an action response. Use to transform output."
15416
+ ),
15417
+ onRequest: external_exports.unknown().optional().describe(
15418
+ "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
15419
+ ),
15420
+ onWebSocket: external_exports.unknown().optional().describe(
15421
+ "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
15422
+ ),
15423
+ actions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
15424
+ "Tree of action names or nested groups to handler functions. Nested paths use dot-separated low-level action names. Defaults to an empty object."
15425
+ ),
15426
+ actionInputSchemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
15427
+ "Optional schemas for validating action argument tuples in native runtimes. May mirror nested action groups or use dot-separated low-level action names."
15428
+ ),
15429
+ tracing: external_exports.unknown().optional().describe(
15430
+ "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."
15431
+ ),
15432
+ connParamsSchema: external_exports.unknown().optional().describe(
15433
+ "Optional schema for validating connection params in native runtimes."
15434
+ ),
15435
+ events: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of event names to schemas."),
15436
+ queues: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of queue names to schemas."),
15437
+ options: DocActorOptionsSchema.optional()
15438
+ }).describe("Actor configuration passed to the actor() function.");
15436
15439
 
15437
15440
  // ../rivetkit/dist/tsup/chunk-JI6GZ2C2.js
15438
15441
  var EMPTY_KEY = "/";
@@ -15551,7 +15554,7 @@ function removePrefixFromKey(prefixedKey) {
15551
15554
  return prefixedKey.slice(KEYS.KV.length);
15552
15555
  }
15553
15556
 
15554
- // ../rivetkit/dist/tsup/chunk-553CIQJY.js
15557
+ // ../rivetkit/dist/tsup/chunk-2CI2IEVN.js
15555
15558
  function logger() {
15556
15559
  return getLogger("actor-client");
15557
15560
  }
@@ -15672,7 +15675,7 @@ var AsyncMutex = class {
15672
15675
  }
15673
15676
  };
15674
15677
 
15675
- // ../rivetkit/dist/tsup/chunk-5G2J26VM.js
15678
+ // ../rivetkit/dist/tsup/chunk-PYRI75DL.js
15676
15679
  var import_invariant2 = __toESM(require_invariant(), 1);
15677
15680
 
15678
15681
  // ../../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
@@ -16887,7 +16890,7 @@ var TraceAPI = (
16887
16890
  // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js
16888
16891
  var trace = TraceAPI.getInstance();
16889
16892
 
16890
- // ../rivetkit/dist/tsup/chunk-5G2J26VM.js
16893
+ // ../rivetkit/dist/tsup/chunk-PYRI75DL.js
16891
16894
  var import_invariant3 = __toESM(require_invariant(), 1);
16892
16895
  var import_invariant4 = __toESM(require_invariant(), 1);
16893
16896
  var PATH_CONNECT = "/connect";
@@ -19361,7 +19364,8 @@ async function sendHttpRequest(opts) {
19361
19364
  {
19362
19365
  metadata: responseData.metadata,
19363
19366
  rayId: rayId ?? void 0,
19364
- actor: responseData.actor
19367
+ actor: responseData.actor,
19368
+ statusCode: response.status
19365
19369
  }
19366
19370
  );
19367
19371
  } catch (error46) {
@@ -20269,6 +20273,22 @@ var ActorHandleRaw = class {
20269
20273
  "dynamic actor resolution did not produce a direct actor id"
20270
20274
  );
20271
20275
  }
20276
+ /** Issue a token scoped to this actor. Defaults to actor gateway read access. */
20277
+ async issueToken(options = {}) {
20278
+ const actorId = await this.resolve();
20279
+ const permissions = options.permissions ?? {
20280
+ actor_gateway: ["read"]
20281
+ };
20282
+ const grants = Object.keys(permissions).flatMap((resource) => {
20283
+ const operations = permissions[resource];
20284
+ return operations ? [{ resource, target: { id: actorId }, operations }] : [];
20285
+ });
20286
+ return this.#driver.issueToken({
20287
+ subject: options.subject,
20288
+ expiresIn: options.expiresIn,
20289
+ grants
20290
+ });
20291
+ }
20272
20292
  /**
20273
20293
  * Returns the raw URL for routing traffic to the actor.
20274
20294
  */
@@ -20301,6 +20321,8 @@ var ACTOR_CONNS_SYMBOL = /* @__PURE__ */ Symbol("actorConns");
20301
20321
  var CREATE_ACTOR_CONN_PROXY = /* @__PURE__ */ Symbol("createActorConnProxy");
20302
20322
  var ClientRaw = class {
20303
20323
  #disposed = false;
20324
+ /** Issue namespace-scoped tokens with an explicit grant list. */
20325
+ auth;
20304
20326
  [ACTOR_CONNS_SYMBOL] = /* @__PURE__ */ new Set();
20305
20327
  #driver;
20306
20328
  #encodingKind;
@@ -20312,6 +20334,9 @@ var ClientRaw = class {
20312
20334
  */
20313
20335
  constructor(driver, options = {}) {
20314
20336
  this.#driver = driver;
20337
+ this.auth = {
20338
+ issueToken: (issueOptions) => this.#driver.issueToken(issueOptions)
20339
+ };
20315
20340
  this.#encodingKind = options.encoding ?? "bare";
20316
20341
  this.#gatewayOptions = options.gateway ?? {};
20317
20342
  this.#currentActorInvocation = options.currentActorInvocation;
@@ -20603,6 +20628,72 @@ function createActorProxy(handle) {
20603
20628
  }
20604
20629
  });
20605
20630
  }
20631
+ function isInvalidToken(group, code) {
20632
+ return group === "auth" && (code === "invalid_token" || code === "token_expired");
20633
+ }
20634
+ function isInvalidTokenResponse(response) {
20635
+ if (response.status !== 401) return false;
20636
+ const error46 = response.headers.get("x-rivet-error");
20637
+ if (!error46) return false;
20638
+ const separator = error46.indexOf(".");
20639
+ return separator > 0 && isInvalidToken(error46.slice(0, separator), error46.slice(separator + 1));
20640
+ }
20641
+ var TokenProvider = class {
20642
+ constructor(getToken) {
20643
+ this.getToken = getToken;
20644
+ }
20645
+ #cached;
20646
+ #pending;
20647
+ #pendingForce = false;
20648
+ async current() {
20649
+ if (this.#cached && (this.#cached.expiresAt === void 0 || Date.now() < this.#cached.expiresAt - 5e3)) {
20650
+ return this.#cached.token;
20651
+ }
20652
+ return this.#load(false);
20653
+ }
20654
+ /** A late rejection for an older token must never erase a newer credential. */
20655
+ async refreshIfCurrent(failedToken) {
20656
+ var _a2;
20657
+ if (this.#pending !== void 0) {
20658
+ const wasForced = this.#pendingForce;
20659
+ const refreshed = await this.#pending;
20660
+ if (wasForced || refreshed !== failedToken) return refreshed;
20661
+ }
20662
+ if (((_a2 = this.#cached) == null ? void 0 : _a2.token) !== failedToken) {
20663
+ return this.current();
20664
+ }
20665
+ return this.#load(true);
20666
+ }
20667
+ #load(forceRefresh) {
20668
+ if (this.#pending !== void 0) return this.#pending;
20669
+ const pending = Promise.resolve().then(() => this.getToken({ forceRefresh })).then((token) => {
20670
+ if (typeof token !== "string" || token.length === 0) {
20671
+ throw new Error(
20672
+ "getToken must resolve to a nonempty string"
20673
+ );
20674
+ }
20675
+ this.#cached = { token, expiresAt: jwtExpiration(token) };
20676
+ return token;
20677
+ }).finally(() => {
20678
+ if (this.#pending === pending) this.#pending = void 0;
20679
+ });
20680
+ this.#pending = pending;
20681
+ this.#pendingForce = forceRefresh;
20682
+ return pending;
20683
+ }
20684
+ };
20685
+ function jwtExpiration(token) {
20686
+ try {
20687
+ const payload = token.split(".")[1];
20688
+ if (!payload) return void 0;
20689
+ const claims = JSON.parse(
20690
+ atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
20691
+ );
20692
+ return typeof claims.exp === "number" && Number.isSafeInteger(claims.exp) ? claims.exp * 1e3 : void 0;
20693
+ } catch {
20694
+ return void 0;
20695
+ }
20696
+ }
20606
20697
  var CONNECT_SYMBOL = /* @__PURE__ */ Symbol("connect");
20607
20698
  var ActorConnRaw = class {
20608
20699
  #disposed = false;
@@ -20631,6 +20722,7 @@ var ActorConnRaw = class {
20631
20722
  /** Promise used to indicate the socket has connected successfully. This will be rejected if the connection fails. */
20632
20723
  #onOpenPromise;
20633
20724
  #websocket;
20725
+ #authRetryAvailable = true;
20634
20726
  #client;
20635
20727
  #driver;
20636
20728
  #currentActorInvocation;
@@ -20876,6 +20968,10 @@ var ActorConnRaw = class {
20876
20968
  if (error46 instanceof ActorConnDisposed) {
20877
20969
  return false;
20878
20970
  }
20971
+ if (error46 instanceof RivetError && isInvalidToken(error46.group, error46.code) && this.#driver.refreshAuthToken && this.#authRetryAvailable) {
20972
+ this.#authRetryAvailable = false;
20973
+ return true;
20974
+ }
20879
20975
  if (error46 instanceof RivetError && this.#shouldReconnectForStaleActor(error46.group, error46.code)) {
20880
20976
  return true;
20881
20977
  }
@@ -21000,6 +21096,7 @@ var ActorConnRaw = class {
21000
21096
  messageQueueLength: this.#messageQueue.length,
21001
21097
  connId: this.#connId
21002
21098
  });
21099
+ this.#authRetryAvailable = true;
21003
21100
  this.#setConnStatus("connected");
21004
21101
  if (this.#onOpenPromise) {
21005
21102
  this.#onOpenPromise.resolve(void 0);
@@ -21142,7 +21239,8 @@ var ActorConnRaw = class {
21142
21239
  }
21143
21240
  /** Called by the onclose event from drivers. */
21144
21241
  async #handleOnClose(event2) {
21145
- var _a2;
21242
+ var _a2, _b, _c;
21243
+ const failedSocket = this.#websocket;
21146
21244
  const closeEvent = event2;
21147
21245
  const wasClean = closeEvent.wasClean;
21148
21246
  const wasConnected = this.#connStatus === "connected";
@@ -21164,9 +21262,24 @@ var ActorConnRaw = class {
21164
21262
  const parsed = parseWebSocketCloseReason(reason);
21165
21263
  if (parsed) {
21166
21264
  const { group, code, rayId } = parsed;
21265
+ if (isInvalidToken(group, code) && closeEvent.code === 1008 && failedSocket) {
21266
+ try {
21267
+ if (!await ((_b = (_a2 = this.#driver).refreshAuthToken) == null ? void 0 : _b.call(
21268
+ _a2,
21269
+ failedSocket
21270
+ ))) {
21271
+ this.#authRetryAvailable = false;
21272
+ }
21273
+ } catch {
21274
+ logger().warn("token renewal failed");
21275
+ this.#authRetryAvailable = false;
21276
+ }
21277
+ } else if (isInvalidToken(group, code)) {
21278
+ this.#authRetryAvailable = false;
21279
+ }
21167
21280
  if (this.#shouldReconnectForStaleActor(group, code)) {
21168
21281
  this.#clearResolvedActorIdentity();
21169
- (_a2 = this.#onOpenPromise) == null ? void 0 : _a2.reject(
21282
+ (_c = this.#onOpenPromise) == null ? void 0 : _c.reject(
21170
21283
  new RivetError(
21171
21284
  group,
21172
21285
  code,
@@ -21213,7 +21326,7 @@ var ActorConnRaw = class {
21213
21326
  if (error46 instanceof RivetError) {
21214
21327
  this.#dispatchActorError(error46);
21215
21328
  }
21216
- if (wasConnected) {
21329
+ if (wasConnected && this.#authRetryAvailable) {
21217
21330
  logger().debug({
21218
21331
  msg: "triggering reconnect",
21219
21332
  connId: this.#connId
@@ -21682,6 +21795,23 @@ var ActorConnRaw = class {
21682
21795
  );
21683
21796
  }
21684
21797
  };
21798
+ var ENGINE_HOST = "127.0.0.1";
21799
+ var ENGINE_PORT = 6420;
21800
+ var ENGINE_ENDPOINT = buildEngineEndpoint(ENGINE_HOST, ENGINE_PORT);
21801
+ function buildEngineEndpoint(host, port) {
21802
+ const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
21803
+ return `http://${urlHost}:${port}`;
21804
+ }
21805
+ function isLocalEngineEndpoint(endpoint) {
21806
+ let url2;
21807
+ try {
21808
+ url2 = new URL(endpoint);
21809
+ } catch {
21810
+ return false;
21811
+ }
21812
+ const hostname3 = url2.hostname.toLowerCase();
21813
+ return hostname3 === "localhost" || hostname3 === "0.0.0.0" || hostname3 === "::" || hostname3 === "[::]" || hostname3 === "::1" || hostname3 === "[::1]" || /^127(?:\.\d{1,3}){0,3}$/.test(hostname3);
21814
+ }
21685
21815
  function tryParseEndpoint(ctx, options) {
21686
21816
  const {
21687
21817
  endpoint,
@@ -21776,6 +21906,8 @@ var ClientConfigSchemaBase = v4_default.object({
21776
21906
  }),
21777
21907
  /** Token to use to authenticate with the API. */
21778
21908
  token: v4_default.string().optional().transform((val) => val ?? getRivetToken()),
21909
+ /** Issue and renew a client token on demand. Overrides the static token when provided. */
21910
+ getToken: v4_default.custom().optional(),
21779
21911
  /** Namespace to connect to. */
21780
21912
  namespace: v4_default.string().optional().transform((val) => val ?? getRivetNamespace()),
21781
21913
  /** Name of the envoy pool. This is used to group together envoys in to different pools. */
@@ -21820,7 +21952,7 @@ function transformClientConfig(config3, ctx) {
21820
21952
  ...config3,
21821
21953
  endpoint: parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint,
21822
21954
  namespace: (parsedEndpoint == null ? void 0 : parsedEndpoint.namespace) ?? config3.namespace ?? "default",
21823
- token: (parsedEndpoint == null ? void 0 : parsedEndpoint.token) ?? config3.token
21955
+ token: (parsedEndpoint == null ? void 0 : parsedEndpoint.token) ?? config3.token ?? (config3.endpoint && isLocalEngineEndpoint(config3.endpoint) ? "default" : void 0)
21824
21956
  };
21825
21957
  }
21826
21958
  function convertRegistryConfigToClientConfig(config3) {
@@ -21828,6 +21960,7 @@ function convertRegistryConfigToClientConfig(config3) {
21828
21960
  return {
21829
21961
  endpoint: config3.endpoint,
21830
21962
  token: config3.token,
21963
+ getToken: void 0,
21831
21964
  namespace: config3.namespace,
21832
21965
  poolName: config3.envoy.poolName,
21833
21966
  headers: config3.headers,
@@ -22159,7 +22292,8 @@ async function openWebSocketToGateway(runConfig, gatewayUrl, encoding, params, o
22159
22292
  const ackHookToken = typeof process !== "undefined" && process.env.VITEST ? crypto.randomUUID() : void 0;
22160
22293
  logger2().debug({
22161
22294
  msg: "opening websocket to actor via guard",
22162
- gatewayUrl
22295
+ // Gateway URLs can embed credentials; never include the path or query in logs.
22296
+ origin: new URL(gatewayUrl).origin
22163
22297
  });
22164
22298
  const ws = new WebSocket2(
22165
22299
  gatewayUrl,
@@ -22249,6 +22383,14 @@ async function apiCall(config3, method2, path2, body) {
22249
22383
  responseFromBare: (value) => value
22250
22384
  });
22251
22385
  }
22386
+ async function issueToken(config3, options) {
22387
+ return apiCall(config3, "POST", "/auth/tokens", {
22388
+ namespace: config3.namespace,
22389
+ subject: options.subject,
22390
+ duration: options.expiresIn,
22391
+ grants: options.grants
22392
+ });
22393
+ }
22252
22394
  async function getActor(config3, _, actorId) {
22253
22395
  return apiCall(
22254
22396
  config3,
@@ -22490,6 +22632,8 @@ function closeWebSocketIfOpen(ws, code, reason) {
22490
22632
  var RemoteEngineControlClient = class {
22491
22633
  #config;
22492
22634
  #metadataPromise;
22635
+ #tokenProvider;
22636
+ #webSocketTokens = /* @__PURE__ */ new WeakMap();
22493
22637
  constructor(runConfig) {
22494
22638
  if (getNextPhase() === "phase-production-build") {
22495
22639
  logger2().info(
@@ -22498,6 +22642,8 @@ var RemoteEngineControlClient = class {
22498
22642
  runConfig.disableMetadataLookup = true;
22499
22643
  }
22500
22644
  this.#config = { ...runConfig };
22645
+ if (runConfig.getToken)
22646
+ this.#tokenProvider = new TokenProvider(runConfig.getToken);
22501
22647
  if (!runConfig.disableMetadataLookup) {
22502
22648
  this.#metadataPromise = lookupMetadataCached(this.#config).then(
22503
22649
  (metadataData) => {
@@ -22506,14 +22652,13 @@ var RemoteEngineControlClient = class {
22506
22652
  if (metadataData.clientNamespace) {
22507
22653
  this.#config.namespace = metadataData.clientNamespace;
22508
22654
  }
22509
- if (metadataData.clientToken) {
22655
+ if (metadataData.clientToken && !this.#tokenProvider) {
22510
22656
  this.#config.token = metadataData.clientToken;
22511
22657
  }
22512
22658
  logger2().info({
22513
22659
  msg: "overriding client endpoint",
22514
22660
  endpoint: metadataData.clientEndpoint,
22515
- namespace: metadataData.clientNamespace,
22516
- token: metadataData.clientToken
22661
+ namespace: metadataData.clientNamespace
22517
22662
  });
22518
22663
  }
22519
22664
  logger2().info({
@@ -22526,12 +22671,47 @@ var RemoteEngineControlClient = class {
22526
22671
  );
22527
22672
  }
22528
22673
  }
22674
+ async #authorizedConfig() {
22675
+ if (!this.#tokenProvider) return this.#config;
22676
+ return { ...this.#config, token: await this.#tokenProvider.current() };
22677
+ }
22678
+ async #withCredential(request, readOnly = false) {
22679
+ const config3 = await this.#authorizedConfig();
22680
+ try {
22681
+ return await request(config3);
22682
+ } catch (error46) {
22683
+ if (this.#tokenProvider && config3.token && error46 instanceof RivetError && error46.statusCode === 401 && isInvalidToken(error46.group, error46.code)) {
22684
+ if (readOnly) {
22685
+ const token = await this.#tokenProvider.refreshIfCurrent(
22686
+ config3.token
22687
+ );
22688
+ return request({ ...this.#config, token });
22689
+ }
22690
+ await this.#tokenProvider.refreshIfCurrent(config3.token);
22691
+ }
22692
+ throw error46;
22693
+ }
22694
+ }
22695
+ async issueToken(options) {
22696
+ await this.#metadataPromise;
22697
+ const response = await this.#withCredential(
22698
+ (config3) => issueToken(config3, options)
22699
+ );
22700
+ return {
22701
+ token: response.token,
22702
+ issuedAt: response.issued_ts,
22703
+ expiresAt: response.expires_ts
22704
+ };
22705
+ }
22529
22706
  async getForId({
22530
22707
  name,
22531
22708
  actorId
22532
22709
  }) {
22533
22710
  await this.#metadataPromise;
22534
- const response = await getActor(this.#config, name, actorId);
22711
+ const response = await this.#withCredential(
22712
+ (config3) => getActor(config3, name, actorId),
22713
+ true
22714
+ );
22535
22715
  const actor2 = response.actors[0];
22536
22716
  if (!actor2) return void 0;
22537
22717
  if (actor2.name !== name) {
@@ -22552,7 +22732,10 @@ var RemoteEngineControlClient = class {
22552
22732
  await this.#metadataPromise;
22553
22733
  logger2().debug({ msg: "getWithKey: searching for actor", name, key });
22554
22734
  try {
22555
- const response = await getActorByKey(this.#config, name, key);
22735
+ const response = await this.#withCredential(
22736
+ (config3) => getActorByKey(config3, name, key),
22737
+ true
22738
+ );
22556
22739
  const actor2 = response.actors[0];
22557
22740
  if (!actor2) return void 0;
22558
22741
  logger2().debug({
@@ -22585,16 +22768,18 @@ var RemoteEngineControlClient = class {
22585
22768
  key
22586
22769
  });
22587
22770
  try {
22588
- const { actor: actor2, created } = await getOrCreateActor(this.#config, {
22589
- datacenter: region,
22590
- name,
22591
- key: serializeActorKey(key),
22592
- runner_name_selector: poolName ?? this.#config.poolName,
22593
- input: actorInput ? uint8ArrayToBase642(
22594
- encodeCborCompat(actorInput)
22595
- ) : void 0,
22596
- crash_policy: crashPolicy ?? "sleep"
22597
- });
22771
+ const { actor: actor2, created } = await this.#withCredential(
22772
+ (config3) => getOrCreateActor(config3, {
22773
+ datacenter: region,
22774
+ name,
22775
+ key: serializeActorKey(key),
22776
+ runner_name_selector: poolName ?? this.#config.poolName,
22777
+ input: actorInput ? uint8ArrayToBase642(
22778
+ encodeCborCompat(actorInput)
22779
+ ) : void 0,
22780
+ crash_policy: crashPolicy ?? "sleep"
22781
+ })
22782
+ );
22598
22783
  logger2().info({
22599
22784
  msg: "getOrCreateWithKey: actor ready",
22600
22785
  actorId: actor2.actor_id,
@@ -22610,7 +22795,10 @@ var RemoteEngineControlClient = class {
22610
22795
  name,
22611
22796
  key
22612
22797
  });
22613
- const response = await getActorByKey(this.#config, name, key);
22798
+ const response = await this.#withCredential(
22799
+ (config3) => getActorByKey(config3, name, key),
22800
+ true
22801
+ );
22614
22802
  const existing = response.actors[0];
22615
22803
  if (!existing) throw error46;
22616
22804
  logger2().info({
@@ -22634,14 +22822,18 @@ var RemoteEngineControlClient = class {
22634
22822
  }) {
22635
22823
  await this.#metadataPromise;
22636
22824
  logger2().info({ msg: "creating actor via engine api", name, key });
22637
- const result = await createActor(this.#config, {
22638
- datacenter: region,
22639
- name,
22640
- runner_name_selector: poolName ?? this.#config.poolName,
22641
- key: serializeActorKey(key),
22642
- input: input ? uint8ArrayToBase642(encodeCborCompat(input)) : void 0,
22643
- crash_policy: crashPolicy ?? "sleep"
22644
- });
22825
+ const result = await this.#withCredential(
22826
+ (config3) => createActor(config3, {
22827
+ datacenter: region,
22828
+ name,
22829
+ runner_name_selector: poolName ?? this.#config.poolName,
22830
+ key: serializeActorKey(key),
22831
+ input: input ? uint8ArrayToBase642(
22832
+ encodeCborCompat(input)
22833
+ ) : void 0,
22834
+ crash_policy: crashPolicy ?? "sleep"
22835
+ })
22836
+ );
22645
22837
  logger2().info({
22646
22838
  msg: "actor created",
22647
22839
  actorId: result.actor.actor_id,
@@ -22653,43 +22845,61 @@ var RemoteEngineControlClient = class {
22653
22845
  async listActors({ name }) {
22654
22846
  await this.#metadataPromise;
22655
22847
  logger2().debug({ msg: "listing actors via engine api", name });
22656
- const response = await listActorsByName(this.#config, name);
22848
+ const response = await this.#withCredential(
22849
+ (config3) => listActorsByName(config3, name),
22850
+ true
22851
+ );
22657
22852
  return response.actors.map(apiActorToOutput);
22658
22853
  }
22659
22854
  async destroyActor(actorId) {
22660
22855
  await this.#metadataPromise;
22661
22856
  logger2().info({ msg: "destroying actor via engine api", actorId });
22662
- await destroyActor(this.#config, actorId);
22857
+ await this.#withCredential((config3) => destroyActor(config3, actorId));
22663
22858
  logger2().info({ msg: "actor destroyed", actorId });
22664
22859
  }
22665
22860
  async sendRequest(target, actorRequest, options = {}) {
22861
+ var _a2;
22666
22862
  await this.#metadataPromise;
22667
- const path2 = requestPath(actorRequest);
22668
- const gatewayUrl = this.#buildGatewayUrlForTarget(
22669
- target,
22670
- path2,
22671
- options
22672
- );
22863
+ const config3 = await this.#authorizedConfig();
22673
22864
  const httpOptions = {
22674
22865
  ...options,
22675
22866
  directActorId: shouldSkipReadyWait(options) ? directActorIdFromTarget(target) : void 0
22676
22867
  };
22677
- return sendHttpRequestToGateway(
22678
- this.#config,
22679
- gatewayUrl,
22868
+ const send = (current) => sendHttpRequestToGateway(
22869
+ current,
22870
+ this.#buildGatewayUrlForTarget(
22871
+ current,
22872
+ target,
22873
+ requestPath(actorRequest),
22874
+ options
22875
+ ),
22680
22876
  actorRequest,
22681
22877
  httpOptions
22682
22878
  );
22879
+ const response = await send(config3);
22880
+ if (!this.#tokenProvider || !config3.token || !isInvalidTokenResponse(response))
22881
+ return response;
22882
+ if ((actorRequest.method === "GET" || actorRequest.method === "HEAD") && !("getOrCreateForKey" in target)) {
22883
+ const token = await this.#tokenProvider.refreshIfCurrent(
22884
+ config3.token
22885
+ );
22886
+ await ((_a2 = response.body) == null ? void 0 : _a2.cancel());
22887
+ return send({ ...this.#config, token });
22888
+ }
22889
+ await this.#tokenProvider.refreshIfCurrent(config3.token);
22890
+ return response;
22683
22891
  }
22684
22892
  async openWebSocket(path2, target, encoding, params, options = {}) {
22685
22893
  await this.#metadataPromise;
22894
+ const config3 = await this.#authorizedConfig();
22686
22895
  const gatewayUrl = this.#buildGatewayUrlForTarget(
22896
+ config3,
22687
22897
  target,
22688
22898
  path2,
22689
22899
  options
22690
22900
  );
22691
- return openWebSocketToGateway(
22692
- this.#config,
22901
+ const ws = await openWebSocketToGateway(
22902
+ config3,
22693
22903
  gatewayUrl,
22694
22904
  encoding,
22695
22905
  params,
@@ -22698,25 +22908,59 @@ var RemoteEngineControlClient = class {
22698
22908
  directActorId: shouldSkipReadyWait(options) ? directActorIdFromTarget(target) : void 0
22699
22909
  }
22700
22910
  );
22911
+ this.#watchWebSocketAuth(ws, config3.token);
22912
+ return ws;
22913
+ }
22914
+ async refreshAuthToken(ws) {
22915
+ const context2 = this.#webSocketTokens.get(ws);
22916
+ if (!(context2 == null ? void 0 : context2.refresh)) return false;
22917
+ await context2.refresh;
22918
+ return true;
22919
+ }
22920
+ #watchWebSocketAuth(ws, token) {
22921
+ const tokenProvider = this.#tokenProvider;
22922
+ if (!tokenProvider || !token) return;
22923
+ const context2 = {};
22924
+ this.#webSocketTokens.set(ws, context2);
22925
+ ws.addEventListener(
22926
+ "close",
22927
+ (event2) => {
22928
+ if (event2.code !== 1008 || !event2.reason) return;
22929
+ const separator = event2.reason.indexOf(".");
22930
+ if (separator < 0) return;
22931
+ const code = event2.reason.slice(separator + 1).split(/[\s:#]/, 1)[0];
22932
+ if (isInvalidToken(event2.reason.slice(0, separator), code)) {
22933
+ context2.refresh = tokenProvider.refreshIfCurrent(token).catch((error46) => {
22934
+ logger2().warn(
22935
+ "failed to renew authentication token"
22936
+ );
22937
+ throw error46;
22938
+ });
22939
+ context2.refresh.catch(() => {
22940
+ });
22941
+ }
22942
+ }
22943
+ );
22701
22944
  }
22702
22945
  async buildGatewayUrl(target, options = {}) {
22703
22946
  await this.#metadataPromise;
22704
- return this.#buildGatewayUrlForTarget(target, "", options);
22947
+ return this.#buildGatewayUrlForTarget(
22948
+ await this.#authorizedConfig(),
22949
+ target,
22950
+ "",
22951
+ options
22952
+ );
22705
22953
  }
22706
22954
  async proxyRequest(_c, actorRequest, actorId) {
22707
- await this.#metadataPromise;
22708
- const gatewayUrl = this.#buildGatewayUrlForTarget(
22709
- { directId: actorId },
22710
- requestPath(actorRequest)
22711
- );
22712
- return sendHttpRequestToGateway(this.#config, gatewayUrl, actorRequest);
22955
+ return this.sendRequest({ directId: actorId }, actorRequest);
22713
22956
  }
22714
22957
  async proxyWebSocket(c, path2, actorId, encoding, params) {
22715
- var _a2, _b;
22958
+ var _a2;
22716
22959
  await this.#metadataPromise;
22717
- const upgradeWebSocket = (_b = (_a2 = this.#config).getUpgradeWebSocket) == null ? void 0 : _b.call(_a2);
22960
+ const config3 = await this.#authorizedConfig();
22961
+ const upgradeWebSocket = (_a2 = config3.getUpgradeWebSocket) == null ? void 0 : _a2.call(config3);
22718
22962
  (0, import_invariant4.default)(upgradeWebSocket, "missing getUpgradeWebSocket");
22719
- const endpoint = getEndpoint(this.#config);
22963
+ const endpoint = getEndpoint(config3);
22720
22964
  const guardUrl = combineUrlPath(endpoint, path2);
22721
22965
  const wsGuardUrl = guardUrl.replace("http://", "ws://");
22722
22966
  logger2().debug({
@@ -22726,7 +22970,7 @@ var RemoteEngineControlClient = class {
22726
22970
  guardUrl
22727
22971
  });
22728
22972
  const protocols = buildWebSocketProtocols(
22729
- this.#config,
22973
+ config3,
22730
22974
  encoding,
22731
22975
  params,
22732
22976
  void 0,
@@ -22744,8 +22988,8 @@ var RemoteEngineControlClient = class {
22744
22988
  setGetUpgradeWebSocket(getUpgradeWebSocket) {
22745
22989
  this.#config.getUpgradeWebSocket = getUpgradeWebSocket;
22746
22990
  }
22747
- #buildGatewayUrlForTarget(target, path2, options = {}) {
22748
- const endpoint = getEndpoint(this.#config);
22991
+ #buildGatewayUrlForTarget(config3, target, path2, options = {}) {
22992
+ const endpoint = getEndpoint(config3);
22749
22993
  if (shouldSkipReadyWait(options) && directActorIdFromTarget(target) && canUseDirectSkipReadyWaitPath(path2)) {
22750
22994
  return combineUrlPath(endpoint, path2);
22751
22995
  }
@@ -22753,7 +22997,7 @@ var RemoteEngineControlClient = class {
22753
22997
  return buildActorGatewayUrl(
22754
22998
  endpoint,
22755
22999
  target.directId,
22756
- this.#config.token,
23000
+ config3.token,
22757
23001
  path2
22758
23002
  );
22759
23003
  }
@@ -22761,20 +23005,20 @@ var RemoteEngineControlClient = class {
22761
23005
  return buildActorGatewayUrl(
22762
23006
  endpoint,
22763
23007
  target.getForId.actorId,
22764
- this.#config.token,
23008
+ config3.token,
22765
23009
  path2
22766
23010
  );
22767
23011
  }
22768
23012
  if ("getForKey" in target || "getOrCreateForKey" in target) {
22769
23013
  return buildActorQueryGatewayUrl(
22770
23014
  endpoint,
22771
- this.#config.namespace,
23015
+ config3.namespace,
22772
23016
  target,
22773
- this.#config.token,
23017
+ config3.token,
22774
23018
  path2,
22775
- this.#config.maxInputSize,
23019
+ config3.maxInputSize,
22776
23020
  void 0,
22777
- "getOrCreateForKey" in target ? target.getOrCreateForKey.poolName ?? this.#config.poolName : void 0,
23021
+ "getOrCreateForKey" in target ? target.getOrCreateForKey.poolName ?? config3.poolName : void 0,
22778
23022
  options
22779
23023
  );
22780
23024
  }
@@ -22823,7 +23067,7 @@ function apiActorToOutput(actor2) {
22823
23067
  };
22824
23068
  }
22825
23069
 
22826
- // ../rivetkit/dist/tsup/chunk-W2PXGWMR.js
23070
+ // ../rivetkit/dist/tsup/chunk-5EGLHQJJ.js
22827
23071
  var nativeStateTransactionOpeners = /* @__PURE__ */ new WeakMap();
22828
23072
  var nativeStateTransactionClientBinders = /* @__PURE__ */ new WeakMap();
22829
23073
  function registerNativeStateTransactionOpener(provider, opener) {
@@ -24565,23 +24809,6 @@ var InlineWebSocketAdapter = class {
24565
24809
  }
24566
24810
  }
24567
24811
  };
24568
- var ENGINE_HOST = "127.0.0.1";
24569
- var ENGINE_PORT = 6420;
24570
- var ENGINE_ENDPOINT = buildEngineEndpoint(ENGINE_HOST, ENGINE_PORT);
24571
- function buildEngineEndpoint(host, port) {
24572
- const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
24573
- return `http://${urlHost}:${port}`;
24574
- }
24575
- function isLocalEngineEndpoint(endpoint) {
24576
- let url2;
24577
- try {
24578
- url2 = new URL(endpoint);
24579
- } catch {
24580
- return false;
24581
- }
24582
- const hostname3 = url2.hostname.toLowerCase();
24583
- return hostname3 === "localhost" || hostname3 === "0.0.0.0" || hostname3 === "::" || hostname3 === "[::]" || hostname3 === "::1" || hostname3 === "[::1]" || /^127(?:\.\d{1,3}){0,3}$/.test(hostname3);
24584
- }
24585
24812
  function logger22() {
24586
24813
  return getLogger("registry");
24587
24814
  }
@@ -24679,20 +24906,9 @@ async function configureServerlessPool(config3) {
24679
24906
  });
24680
24907
  throw lastError;
24681
24908
  }
24682
- var warnedMissingVersion = false;
24683
24909
  var EnvoyConfigSchema = external_exports.object({
24684
24910
  poolName: external_exports.string().default(() => getRivetPool() ?? "default"),
24685
- version: external_exports.number().default(() => {
24686
- const version2 = getRivetEnvoyVersion();
24687
- if (version2 !== void 0) return version2;
24688
- if (getNodeEnv() === "production" && !warnedMissingVersion) {
24689
- warnedMissingVersion = true;
24690
- getLogger("rivetkit").error(
24691
- "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"
24692
- );
24693
- }
24694
- return 1;
24695
- }),
24911
+ version: external_exports.number().default(() => getRivetEnvoyVersion() ?? 1),
24696
24912
  // Deprecated.
24697
24913
  totalSlots: external_exports.number().default(() => getRivetTotalSlots() ?? 1e5),
24698
24914
  envoyKey: external_exports.string().optional()
@@ -24992,7 +25208,7 @@ var RegistryConfigSchema = external_exports.object({
24992
25208
  config3.startEngine || parsedEndpoint
24993
25209
  );
24994
25210
  const namespace = (parsedEndpoint == null ? void 0 : parsedEndpoint.namespace) ?? config3.namespace ?? "default";
24995
- const token = (parsedEndpoint == null ? void 0 : parsedEndpoint.token) ?? config3.token ?? "dev";
25211
+ const token = (parsedEndpoint == null ? void 0 : parsedEndpoint.token) ?? config3.token ?? (endpoint && isLocalEngineEndpoint(endpoint) ? "default" : void 0);
24996
25212
  const parsedPublicEndpoint = config3.serverless.publicEndpoint ? tryParseEndpoint(ctx, {
24997
25213
  endpoint: config3.serverless.publicEndpoint,
24998
25214
  path: ["serverless", "publicEndpoint"]
@@ -31957,7 +32173,23 @@ var Registry = class {
31957
32173
  * Starts an actor envoy for standalone server deployments.
31958
32174
  */
31959
32175
  #startEnvoy(config3, printWelcome) {
32176
+ var _a2;
31960
32177
  if (!this.#runtimeServePromise) {
32178
+ const configuredEnvoyVersion = (_a2 = this.#config.envoy) == null ? void 0 : _a2.version;
32179
+ const envoyVersionSource = configuredEnvoyVersion !== void 0 ? "config" : getRivetEnvoyVersion() !== void 0 ? "environment" : "default";
32180
+ logger22().info({
32181
+ msg: "starting rivetkit envoy",
32182
+ rivetkitVersion: VERSION,
32183
+ envoyVersion: config3.envoy.version,
32184
+ envoyVersionSource
32185
+ });
32186
+ if (envoyVersionSource === "default" && getNodeEnv() === "production") {
32187
+ logger22().error({
32188
+ 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",
32189
+ envoyVersion: config3.envoy.version,
32190
+ envoyVersionSource
32191
+ });
32192
+ }
31961
32193
  const configuredRegistryPromise = this.#buildConfiguredRegistry(config3);
31962
32194
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
31963
32195
  this.#runtimeServeLifecyclePromise = configuredRegistryPromise.then(