@rivetkit/supabase 2.3.19 → 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 +1252 -976
  2. package/dist/mod.mjs +1255 -979
  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,839 +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-EB77NZL4.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
- );
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}`);
13231
+ }
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);
12991
13275
  }
12992
- const schema = nestedSchema ?? flatSchema;
12993
- if (schema !== void 0) {
12994
- flattened[name] = schema;
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;
12995
13284
  }
13285
+ metadata = {
13286
+ //url: `https://dashboard.rivet.dev/projects/${actorMetadata.project.slug}/environments/${actorMetadata.environment.slug}/actors?actorId=${actorMetadata.actor.id}`,
13287
+ };
12996
13288
  }
12997
- return flattened;
12998
- }
12999
- function collectActionEntries(actions) {
13000
- const entries = [];
13001
- const names = /* @__PURE__ */ new Set();
13002
- visitActionGroup(actions ?? {}, [], entries, names);
13003
- return entries;
13289
+ return {
13290
+ __type: "ActorError",
13291
+ statusCode,
13292
+ public: public_,
13293
+ group,
13294
+ code,
13295
+ message,
13296
+ metadata,
13297
+ rayId,
13298
+ actor: actor2
13299
+ };
13004
13300
  }
13005
- function visitActionGroup(value, path2, entries, names) {
13006
- if (!isRecord(value)) {
13007
- throw new TypeError(
13008
- `${formatActionPath(path2)} must be an action handler or group`
13009
- );
13010
- }
13011
- for (const [segment, child] of Object.entries(value)) {
13012
- const childPath = [...path2, segment];
13013
- if (typeof child === "function") {
13014
- const name = childPath.join(".");
13015
- if (names.has(name)) {
13016
- throw new TypeError(
13017
- `Multiple action definitions flatten to \`${name}\``
13018
- );
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;
13019
13309
  }
13020
- names.add(name);
13021
- entries.push({
13022
- name,
13023
- path: childPath,
13024
- handler: child
13025
- });
13310
+ return `${error46.name}: ${error46.message}${stack ? `
13311
+ ${stack}` : ""}`;
13026
13312
  } else {
13027
- visitActionGroup(child, childPath, entries, names);
13313
+ return `${error46.name}: ${error46.message}`;
13028
13314
  }
13029
- }
13030
- }
13031
- function lookupNestedSchema(schemas, path2) {
13032
- let value = schemas;
13033
- for (const segment of path2) {
13034
- if (!isRecord(value) || !Object.hasOwn(value, segment)) {
13035
- 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]";
13036
13322
  }
13037
- value = value[segment];
13323
+ } else {
13324
+ return `Unknown error: ${getErrorMessage(error46)}`;
13038
13325
  }
13039
- return value;
13040
13326
  }
13041
- function isRecord(value) {
13042
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
13043
- 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);
13044
13332
  }
13045
- const prototype = Object.getPrototypeOf(value);
13046
- return prototype === Object.prototype || prototype === null;
13047
13333
  }
13048
- function formatActionPath(path2) {
13049
- return path2.length === 0 ? "actions" : `Action \`${path2.join(".")}\``;
13050
- }
13051
- var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
13052
- var ACTOR_CONTEXT_INTERNAL_SYMBOL = /* @__PURE__ */ Symbol(
13053
- "rivetkit.actor_context_internal"
13054
- );
13055
- var RAW_STATE_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.raw_state");
13056
- var CONN_STATE_MANAGER_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.conn_state_manager");
13057
- var zFunction = () => external_exports.custom((val) => typeof val === "function");
13058
- var zActionTree = external_exports.custom((value) => {
13059
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
13060
- return false;
13061
- }
13062
- const prototype = Object.getPrototypeOf(value);
13063
- return prototype === Object.prototype || prototype === null;
13064
- }).superRefine((actions, ctx) => {
13065
- try {
13066
- flattenActionHandlers(actions);
13067
- } catch (error46) {
13068
- ctx.addIssue({
13069
- code: "custom",
13070
- message: error46 instanceof Error ? error46.message : "Invalid action definition"
13071
- });
13072
- }
13073
- });
13074
- var WorkflowInspectorConfigSchema = external_exports.object({
13075
- getHistory: zFunction(),
13076
- getState: zFunction().optional(),
13077
- onHistoryUpdated: zFunction().optional(),
13078
- replayFromStep: zFunction().optional()
13079
- });
13080
- var RunInspectorConfigSchema = external_exports.object({
13081
- workflow: WorkflowInspectorConfigSchema.optional()
13082
- }).optional();
13083
- var BUILTIN_INSPECTOR_TAB_IDS = [
13084
- "workflow",
13085
- "database",
13086
- "state",
13087
- "queue",
13088
- "schedules",
13089
- "connections",
13090
- "console"
13091
- ];
13092
- var BuiltinInspectorTabIdSchema = external_exports.enum(BUILTIN_INSPECTOR_TAB_IDS);
13093
- var CUSTOM_INSPECTOR_TAB_ID_RE = /^[A-Za-z0-9_-]+$/;
13094
- var CustomInspectorTabEntrySchema = external_exports.object({
13095
- id: external_exports.string().regex(
13096
- CUSTOM_INSPECTOR_TAB_ID_RE,
13097
- "inspector.tabs[].id must contain only letters, digits, underscore, or dash"
13098
- ),
13099
- label: external_exports.string().min(1),
13100
- source: external_exports.string().min(1),
13101
- /**
13102
- * Optional icon id. The dashboard maps strings to glyphs (see its
13103
- * icon registry); unknown ids fall back to a generic icon.
13104
- */
13105
- icon: external_exports.string().min(1).optional(),
13106
- hidden: external_exports.literal(false).optional()
13107
- }).strict();
13108
- var HideInspectorTabEntrySchema = external_exports.object({
13109
- id: BuiltinInspectorTabIdSchema,
13110
- hidden: external_exports.literal(true)
13111
- }).strict();
13112
- var InspectorTabEntrySchema = external_exports.union([
13113
- CustomInspectorTabEntrySchema,
13114
- HideInspectorTabEntrySchema
13115
- ]);
13116
- var ActorInspectorConfigSchema = external_exports.object({
13117
- tabs: external_exports.array(InspectorTabEntrySchema).default(() => [])
13118
- }).strict().refine(
13119
- (data) => {
13120
- const ids = data.tabs.map((t) => t.id);
13121
- return new Set(ids).size === ids.length;
13122
- },
13123
- { message: "Duplicate id in inspector.tabs", path: ["tabs"] }
13124
- ).refine(
13125
- (data) => {
13126
- const builtinSet = new Set(BUILTIN_INSPECTOR_TAB_IDS);
13127
- return data.tabs.every(
13128
- (t) => t.hidden === true || !builtinSet.has(t.id)
13129
- );
13130
- },
13131
- {
13132
- message: "Custom inspector tab id collides with a built-in (use hidden: true to hide a built-in)",
13133
- path: ["tabs"]
13134
- }
13135
- );
13136
- var RunConfigSchema = external_exports.object({
13137
- /** Display name for the actor in the Inspector UI. */
13138
- name: external_exports.string().optional(),
13139
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
13140
- icon: external_exports.string().optional(),
13141
- /** The run handler function. */
13142
- run: zFunction(),
13143
- /** Inspector integration for long-running run handlers. */
13144
- inspector: RunInspectorConfigSchema.optional()
13145
- });
13146
- var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("rivetkit.run_function_config");
13147
- function defineRunHandler(run, options) {
13148
- if (options.inspectorKind === void 0 !== (options.createInspector === void 0)) {
13149
- throw new TypeError(
13150
- "defineRunHandler requires inspectorKind and createInspector together"
13151
- );
13152
- }
13153
- Object.defineProperty(run, RUN_FUNCTION_CONFIG_SYMBOL, {
13154
- configurable: false,
13155
- enumerable: false,
13156
- writable: false,
13157
- value: {
13158
- name: options.name,
13159
- icon: options.icon,
13160
- inspectorKind: options.inspectorKind,
13161
- createInspector: options.createInspector
13162
- }
13163
- });
13164
- return run;
13165
- }
13166
- function getRunInspectorKind(run) {
13167
- var _a2;
13168
- if (!run || typeof run !== "function") return void 0;
13169
- return (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.inspectorKind;
13170
- }
13171
- function createRunInspector(run, context2) {
13172
- var _a2, _b;
13173
- if (!run || typeof run !== "function") return void 0;
13174
- return (_b = (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.createInspector) == null ? void 0 : _b.call(_a2, context2);
13175
- }
13176
- var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
13177
- function getRunFunction(run) {
13178
- if (!run) return void 0;
13179
- if (typeof run === "function") return run;
13180
- return run.run;
13181
- }
13182
- function getRunMetadata(run) {
13183
- if (!run) return {};
13184
- if (typeof run === "function") {
13185
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13186
- if (!config3) return {};
13187
- return { name: config3.name, icon: config3.icon };
13188
- }
13189
- return { name: run.name, icon: run.icon };
13190
- }
13191
- function getRunInspectorConfig(run, actor2) {
13192
- if (!run) return void 0;
13193
- if (typeof run === "function") {
13194
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13195
- return (config3 == null ? void 0 : config3.inspectorFactory) ? config3.inspectorFactory(actor2) : config3 == null ? void 0 : config3.inspector;
13196
- }
13197
- return run.inspector;
13198
- }
13199
- function hasRunInspectorConfig(run) {
13200
- if (!run) return false;
13201
- if (typeof run !== "function") return run.inspector !== void 0;
13202
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13203
- 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;
13204
- }
13205
- function disposeRunInspector(run, actorId) {
13206
- var _a2;
13207
- if (!run || typeof run !== "function") {
13208
- return;
13209
- }
13210
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13211
- (_a2 = config3 == null ? void 0 : config3.disposeInspector) == null ? void 0 : _a2.call(config3, actorId);
13212
- }
13213
- var GlobalActorOptionsBaseSchema = external_exports.object({
13214
- /** Display name for the actor in the Inspector UI. */
13215
- name: external_exports.string().optional(),
13216
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
13217
- icon: external_exports.string().optional(),
13218
- /** Enables the experimental Actor Runtime Socket for this actor. */
13219
- enableActorRuntimeSocket: external_exports.boolean().default(false),
13220
- /**
13221
- * Can hibernate WebSockets for onWebSocket.
13222
- *
13223
- * WebSockets using actions/events are hibernatable by default.
13224
- *
13225
- * @experimental
13226
- **/
13227
- canHibernateWebSocket: external_exports.union([external_exports.boolean(), zFunction()]).default(false)
13228
- }).strict();
13229
- var GlobalActorOptionsSchema = GlobalActorOptionsBaseSchema.prefault(
13230
- () => ({})
13231
- );
13232
- var InstanceActorOptionsBaseSchema = external_exports.object({
13233
- createVarsTimeout: external_exports.number().positive().default(5e3),
13234
- createConnStateTimeout: external_exports.number().positive().default(5e3),
13235
- onBeforeConnectTimeout: external_exports.number().positive().default(5e3),
13236
- onConnectTimeout: external_exports.number().positive().default(5e3),
13237
- onMigrateTimeout: external_exports.number().positive().default(3e4),
13238
- sleepGracePeriod: external_exports.number().positive().default(DEFAULT_SLEEP_GRACE_PERIOD),
13239
- /** @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. */
13240
- onDestroyTimeout: external_exports.number().positive().optional(),
13241
- /** @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. */
13242
- waitUntilTimeout: external_exports.number().positive().optional(),
13243
- stateSaveInterval: external_exports.number().positive().default(1e3),
13244
- actionTimeout: external_exports.number().positive().default(6e4),
13245
- connectionLivenessTimeout: external_exports.number().positive().default(2500),
13246
- connectionLivenessInterval: external_exports.number().positive().default(5e3),
13247
- /** @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. */
13248
- noSleep: external_exports.boolean().default(false),
13249
- sleepTimeout: external_exports.number().positive().default(3e4),
13250
- maxQueueSize: external_exports.number().positive().default(1e3),
13251
- /** Maximum pending one-shot and recurring schedules. */
13252
- maxSchedules: external_exports.number().int().nonnegative().default(1e3),
13253
- maxQueueMessageSize: external_exports.number().positive().default(64 * 1024),
13254
- /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
13255
- preloadMaxWorkflowBytes: external_exports.number().nonnegative().optional(),
13256
- /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
13257
- preloadMaxConnectionsBytes: external_exports.number().nonnegative().optional()
13258
- }).strict();
13259
- var InstanceActorOptionsSchema = InstanceActorOptionsBaseSchema.prefault(() => ({}));
13260
- var ActorOptionsSchema = GlobalActorOptionsBaseSchema.extend(
13261
- InstanceActorOptionsBaseSchema.shape
13262
- ).strict().prefault(() => ({}));
13263
- var ActorConfigSchema = external_exports.object({
13264
- onCreate: zFunction().optional(),
13265
- onDestroy: zFunction().optional(),
13266
- onMigrate: zFunction().optional(),
13267
- onWake: zFunction().optional(),
13268
- onSleep: zFunction().optional(),
13269
- run: zRunHandler,
13270
- onStateChange: zFunction().optional(),
13271
- onBeforeConnect: zFunction().optional(),
13272
- onConnect: zFunction().optional(),
13273
- onDisconnect: zFunction().optional(),
13274
- onBeforeActionResponse: zFunction().optional(),
13275
- onRequest: zFunction().optional(),
13276
- onWebSocket: zFunction().optional(),
13277
- actions: zActionTree.default(() => ({})),
13278
- actionInputSchemas: external_exports.record(external_exports.string(), external_exports.any()).optional(),
13279
- connParamsSchema: external_exports.any().optional(),
13280
- events: external_exports.record(external_exports.string(), external_exports.any()).optional(),
13281
- queues: external_exports.record(external_exports.string(), external_exports.any()).optional(),
13282
- state: external_exports.any().optional(),
13283
- createState: zFunction().optional(),
13284
- connState: external_exports.any().optional(),
13285
- createConnState: zFunction().optional(),
13286
- vars: external_exports.any().optional(),
13287
- db: external_exports.any().optional(),
13288
- createVars: zFunction().optional(),
13289
- options: ActorOptionsSchema,
13290
- inspector: ActorInspectorConfigSchema.optional()
13291
- }).strict().refine(
13292
- (data) => !(data.state !== void 0 && data.createState !== void 0),
13293
- {
13294
- message: "Cannot define both 'state' and 'createState'",
13295
- path: ["state"]
13296
- }
13297
- ).refine(
13298
- (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
13299
- {
13300
- message: "Cannot define both 'connState' and 'createConnState'",
13301
- path: ["connState"]
13302
- }
13303
- ).refine(
13304
- (data) => !(data.vars !== void 0 && data.createVars !== void 0),
13305
- {
13306
- message: "Cannot define both 'vars' and 'createVars'",
13307
- path: ["vars"]
13308
- }
13309
- );
13310
- var DocActorOptionsSchema = external_exports.object({
13311
- name: external_exports.string().optional().describe("Display name for the actor in the Inspector UI."),
13312
- icon: external_exports.string().optional().describe(
13313
- "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
13314
- ),
13315
- enableActorRuntimeSocket: external_exports.boolean().optional().describe(
13316
- "Enables the experimental Actor Runtime Socket for this actor. Default: false"
13317
- ),
13318
- createVarsTimeout: external_exports.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
13319
- createConnStateTimeout: external_exports.number().optional().describe(
13320
- "Timeout in ms for createConnState handler. Default: 5000"
13321
- ),
13322
- onMigrateTimeout: external_exports.number().optional().describe("Timeout in ms for onMigrate handler. Default: 30000"),
13323
- onBeforeConnectTimeout: external_exports.number().optional().describe(
13324
- "Timeout in ms for onBeforeConnect handler. Default: 5000"
13325
- ),
13326
- onConnectTimeout: external_exports.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
13327
- sleepGracePeriod: external_exports.number().optional().describe(
13328
- `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}.`
13329
- ),
13330
- onDestroyTimeout: external_exports.number().optional().describe(
13331
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
13332
- ),
13333
- waitUntilTimeout: external_exports.number().optional().describe(
13334
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
13335
- ),
13336
- stateSaveInterval: external_exports.number().optional().describe(
13337
- "Interval in ms between automatic state saves. Default: 1000"
13338
- ),
13339
- actionTimeout: external_exports.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
13340
- connectionLivenessTimeout: external_exports.number().optional().describe(
13341
- "Timeout in ms for connection liveness checks. Default: 2500"
13342
- ),
13343
- connectionLivenessInterval: external_exports.number().optional().describe(
13344
- "Interval in ms between connection liveness checks. Default: 5000"
13345
- ),
13346
- noSleep: external_exports.boolean().optional().describe(
13347
- "Deprecated. If true, the actor will never sleep. Use c.keepAwake(promise) to scope keep-awake to a specific operation instead. Default: false"
13348
- ),
13349
- sleepTimeout: external_exports.number().optional().describe(
13350
- "Time in ms of inactivity before the actor sleeps. Default: 30000"
13351
- ),
13352
- maxQueueSize: external_exports.number().optional().describe(
13353
- "Maximum number of queue messages before rejecting new messages. Default: 1000"
13354
- ),
13355
- maxSchedules: external_exports.number().int().nonnegative().optional().describe(
13356
- "Maximum pending one-shot and recurring schedules before rejecting new schedules. Default: 1000"
13357
- ),
13358
- maxQueueMessageSize: external_exports.number().optional().describe(
13359
- "Maximum size of each queue message in bytes. Default: 65536"
13360
- ),
13361
- canHibernateWebSocket: external_exports.boolean().optional().describe(
13362
- "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
13363
- )
13364
- }).describe("Actor options for timeouts and behavior configuration.");
13365
- var DocActorConfigSchema = external_exports.object({
13366
- state: external_exports.unknown().optional().describe(
13367
- "Initial state value for the actor. Cannot be used with createState."
13368
- ),
13369
- createState: external_exports.unknown().optional().describe(
13370
- "Function to create initial state. Receives context and input. Cannot be used with state."
13371
- ),
13372
- connState: external_exports.unknown().optional().describe(
13373
- "Initial connection state value. Cannot be used with createConnState."
13374
- ),
13375
- createConnState: external_exports.unknown().optional().describe(
13376
- "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."
13377
- ),
13378
- vars: external_exports.unknown().optional().describe(
13379
- "Initial ephemeral variables value. Cannot be used with createVars."
13380
- ),
13381
- createVars: external_exports.unknown().optional().describe(
13382
- "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
13383
- ),
13384
- db: external_exports.unknown().optional().describe("Database provider instance for the actor."),
13385
- onCreate: external_exports.unknown().optional().describe(
13386
- "Called when the actor is first initialized. Use to initialize state."
13387
- ),
13388
- onDestroy: external_exports.unknown().optional().describe("Called when the actor is destroyed."),
13389
- onMigrate: external_exports.unknown().optional().describe(
13390
- "Called on every actor start after persisted state loads and before onWake. Use for repeatable schema migrations."
13391
- ),
13392
- onWake: external_exports.unknown().optional().describe(
13393
- "Called when the actor wakes up and is ready to receive connections and actions."
13394
- ),
13395
- onSleep: external_exports.unknown().optional().describe(
13396
- "Called when the actor is stopping or sleeping. Use to clean up resources."
13397
- ),
13398
- run: external_exports.unknown().optional().describe(
13399
- "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."
13400
- ),
13401
- onStateChange: external_exports.unknown().optional().describe(
13402
- "Called when the actor's state changes. State changes within this hook won't trigger recursion."
13403
- ),
13404
- onBeforeConnect: external_exports.unknown().optional().describe(
13405
- "Called before a client connects. Throw an error to reject the connection. The pending connection is not visible in c.conns while this runs."
13406
- ),
13407
- onConnect: external_exports.unknown().optional().describe(
13408
- "Called when a client successfully connects. The connection is visible in c.conns before this runs."
13409
- ),
13410
- onDisconnect: external_exports.unknown().optional().describe("Called when a client disconnects."),
13411
- onBeforeActionResponse: external_exports.unknown().optional().describe(
13412
- "Called before sending an action response. Use to transform output."
13413
- ),
13414
- onRequest: external_exports.unknown().optional().describe(
13415
- "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
13416
- ),
13417
- onWebSocket: external_exports.unknown().optional().describe(
13418
- "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
13419
- ),
13420
- actions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
13421
- "Tree of action names or nested groups to handler functions. Nested paths use dot-separated low-level action names. Defaults to an empty object."
13422
- ),
13423
- actionInputSchemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
13424
- "Optional schemas for validating action argument tuples in native runtimes. May mirror nested action groups or use dot-separated low-level action names."
13425
- ),
13426
- connParamsSchema: external_exports.unknown().optional().describe(
13427
- "Optional schema for validating connection params in native runtimes."
13428
- ),
13429
- events: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of event names to schemas."),
13430
- queues: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of queue names to schemas."),
13431
- options: DocActorOptionsSchema.optional()
13432
- }).describe("Actor configuration passed to the actor() function.");
13433
-
13434
- // ../rivetkit/dist/tsup/chunk-P2OFXH4G.js
13435
- var INTERNAL_ERROR_CODE = "internal_error";
13436
- var INTERNAL_ERROR_DESCRIPTION = "An internal error occurred";
13437
- var USER_ERROR_CODE = "user_error";
13438
- var BRIDGE_RIVET_ERROR_PREFIX = "__RIVET_ERROR_JSON__:";
13439
- function looksLikeRivetErrorOptions(value) {
13440
- return typeof value === "object" && value !== null && ("public" in value || "metadata" in value || "rayId" in value || "statusCode" in value || "actor" in value || "cause" in value);
13441
- }
13442
- function isTypedErrorTag(value) {
13443
- return value === "ActorError" || value === "RivetError";
13444
- }
13445
- function errorMessage(error46, fallback = String(error46)) {
13446
- if (error46 && typeof error46 === "object" && "message" in error46 && typeof error46.message === "string") {
13447
- return error46.message;
13448
- }
13449
- return fallback;
13450
- }
13451
- function isRivetErrorLike(error46) {
13452
- 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));
13453
- }
13454
- function isActorAbortedError(error46) {
13455
- return isRivetErrorLike(error46) && error46.group === "actor" && error46.code === "aborted";
13456
- }
13457
- function isActorSpecifier(value) {
13458
- 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");
13459
- }
13460
- var RivetError = class extends Error {
13461
- __type = "RivetError";
13462
- public;
13463
- metadata;
13464
- rayId;
13465
- statusCode;
13466
- actor;
13467
- group;
13468
- code;
13469
- static isRivetError(error46) {
13470
- return isRivetErrorLike(error46);
13471
- }
13472
- static isActorError(error46) {
13473
- return isRivetErrorLike(error46);
13474
- }
13475
- constructor(group, code, message, options) {
13476
- const normalized = looksLikeRivetErrorOptions(options) ? options : { metadata: options };
13477
- super(message, { cause: normalized.cause });
13478
- this.name = "RivetError";
13479
- this.group = group;
13480
- this.code = code;
13481
- this.public = normalized.public ?? false;
13482
- this.metadata = normalized.metadata;
13483
- this.rayId = normalized.rayId ?? void 0;
13484
- this.statusCode = normalized.statusCode ?? (this.public ? 400 : 500);
13485
- this.actor = normalized.actor;
13486
- }
13487
- toString() {
13488
- return this.message;
13489
- }
13490
- };
13491
- var UserError = class extends RivetError {
13492
- constructor(message, options) {
13493
- super("user", (options == null ? void 0 : options.code) ?? USER_ERROR_CODE, message, {
13494
- public: true,
13495
- metadata: options == null ? void 0 : options.metadata,
13496
- cause: options == null ? void 0 : options.cause
13497
- });
13498
- }
13499
- };
13500
- function toRivetError(error46, fallback) {
13501
- if (typeof error46 === "string") {
13502
- const bridged = decodeBridgeRivetError(error46);
13503
- if (bridged) {
13504
- return bridged;
13505
- }
13506
- }
13507
- if (error46 instanceof Error) {
13508
- const bridged = decodeBridgeRivetError(error46.message);
13509
- if (bridged) {
13510
- return bridged;
13511
- }
13512
- }
13513
- if (isRivetErrorLike(error46)) {
13514
- return new RivetError(error46.group, error46.code, error46.message, {
13515
- public: error46.public,
13516
- statusCode: error46.statusCode,
13517
- metadata: error46.metadata,
13518
- rayId: error46.rayId,
13519
- actor: error46.actor,
13520
- cause: error46 instanceof Error ? error46.cause : void 0
13521
- });
13522
- }
13523
- return new RivetError(
13524
- (fallback == null ? void 0 : fallback.group) ?? "actor",
13525
- (fallback == null ? void 0 : fallback.code) ?? INTERNAL_ERROR_CODE,
13526
- errorMessage(error46, (fallback == null ? void 0 : fallback.message) ?? "Unknown error"),
13527
- {
13528
- public: fallback == null ? void 0 : fallback.public,
13529
- statusCode: fallback == null ? void 0 : fallback.statusCode,
13530
- metadata: fallback == null ? void 0 : fallback.metadata,
13531
- rayId: fallback == null ? void 0 : fallback.rayId,
13532
- actor: fallback == null ? void 0 : fallback.actor,
13533
- cause: error46 instanceof Error ? error46 : void 0
13534
- }
13535
- );
13536
- }
13537
- function encodeBridgeRivetError(error46) {
13538
- return `${BRIDGE_RIVET_ERROR_PREFIX}${JSON.stringify({
13539
- group: error46.group,
13540
- code: error46.code,
13541
- message: error46.message,
13542
- metadata: error46.metadata,
13543
- rayId: error46.rayId,
13544
- public: error46.public,
13545
- statusCode: error46.statusCode,
13546
- actor: error46.actor
13547
- })}`;
13548
- }
13549
- function encodeErrorForBridge(error46) {
13550
- if (isCanonicalStructuredRivetError(error46)) {
13551
- return encodeBridgeRivetError(error46);
13552
- }
13553
- return String(error46);
13554
- }
13555
- function isCanonicalStructuredRivetError(error46) {
13556
- 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";
13557
- }
13558
- function decodeBridgeRivetErrorPayload(value) {
13559
- if (!value.startsWith(BRIDGE_RIVET_ERROR_PREFIX)) {
13560
- return void 0;
13561
- }
13562
- try {
13563
- const raw = JSON.parse(
13564
- value.slice(BRIDGE_RIVET_ERROR_PREFIX.length)
13565
- );
13566
- const payload = {
13567
- ...raw,
13568
- rayId: raw.rayId ?? void 0
13569
- };
13570
- if (!isRivetErrorLike(payload)) {
13571
- return void 0;
13572
- }
13573
- if (payload.actor !== void 0 && payload.actor !== null && !isActorSpecifier(payload.actor)) {
13574
- return void 0;
13575
- }
13576
- return payload;
13577
- } catch {
13578
- return void 0;
13579
- }
13580
- }
13581
- function decodeBridgeRivetError(value) {
13582
- const payload = decodeBridgeRivetErrorPayload(value);
13583
- if (!payload) {
13584
- return void 0;
13585
- }
13586
- return new RivetError(payload.group, payload.code, payload.message, {
13587
- metadata: payload.metadata,
13588
- rayId: payload.rayId,
13589
- public: payload.public,
13590
- statusCode: payload.statusCode,
13591
- actor: payload.actor ?? void 0
13592
- });
13593
- }
13594
- function invalidRequest(error46) {
13595
- return new RivetError(
13596
- "request",
13597
- "invalid",
13598
- `Invalid request: ${errorMessage(error46, String(error46))}`,
13599
- {
13600
- public: true,
13601
- cause: error46 instanceof Error ? error46 : void 0
13602
- }
13603
- );
13604
- }
13605
- function actorNotFound(identifier) {
13606
- return new RivetError(
13607
- "actor",
13608
- "not_found",
13609
- identifier ? `Actor not found: ${identifier} (https://www.rivet.dev/docs/clients/javascript)` : "Actor not found (https://www.rivet.dev/docs/clients/javascript)",
13610
- { public: true }
13611
- );
13612
- }
13613
- function forbiddenError() {
13614
- return new RivetError("auth", "forbidden", "Forbidden", {
13615
- public: true,
13616
- statusCode: 403
13617
- });
13618
- }
13619
- function unsupportedFeature(feature) {
13620
- return new RivetError(
13621
- "feature",
13622
- "unsupported",
13623
- `Unsupported feature: ${feature}`
13624
- );
13625
- }
13626
-
13627
- // ../rivetkit/dist/tsup/chunk-DN6MD3KK.js
13628
- import {
13629
- pino,
13630
- stdTimeFunctions
13631
- } from "pino";
13632
- var import_invariant = __toESM(require_invariant(), 1);
13633
- import * as cbor from "cbor-x";
13634
- var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
13635
- var getRivetEndpoint = () => getEnvUniversal("RIVET_ENDPOINT");
13636
- var getRivetToken = () => getEnvUniversal("RIVET_TOKEN");
13637
- var getRivetNamespace = () => getEnvUniversal("RIVET_NAMESPACE");
13638
- var getRivetPool = () => getEnvUniversal("RIVET_POOL");
13639
- var getRivetTotalSlots = () => {
13640
- const value = getEnvUniversal("RIVET_TOTAL_SLOTS");
13641
- return value !== void 0 ? parseInt(value, 10) : void 0;
13642
- };
13643
- var getRivetRunEngine = () => getEnvUniversal("RIVET_RUN_ENGINE") === "1";
13644
- var getRivetRunEngineHost = () => getEnvUniversal("RIVET_RUN_ENGINE_HOST");
13645
- var getRivetRunEnginePort = () => {
13646
- const value = getEnvUniversal("RIVET_RUN_ENGINE_PORT");
13647
- return value !== void 0 ? parseInt(value, 10) : void 0;
13648
- };
13649
- var getRivetRunEngineVersion = () => getEnvUniversal("RIVET_RUN_ENGINE_VERSION");
13650
- var getRivetRunServices = () => {
13651
- const value = getEnvUniversal("RIVET_RUN_SERVICES");
13652
- return value === void 0 ? void 0 : value === "1";
13653
- };
13654
- var getRivetEnvoyVersion = () => {
13655
- const value = getEnvUniversal("RIVET_ENVOY_VERSION");
13656
- return value !== void 0 ? parseInt(value, 10) : void 0;
13657
- };
13658
- var getRivetPublicEndpoint = () => getEnvUniversal("RIVET_PUBLIC_ENDPOINT");
13659
- var getRivetPublicToken = () => getEnvUniversal("RIVET_PUBLIC_TOKEN");
13660
- var getRivetkitRuntime = () => getEnvUniversal("RIVETKIT_RUNTIME");
13661
- var getRivetkitRuntimeMode = () => {
13662
- const value = getEnvUniversal("RIVETKIT_RUNTIME_MODE");
13663
- if (value === void 0) return "envoy";
13664
- if (value === "envoy" || value === "serverless") return value;
13665
- throw new Error(
13666
- `RIVETKIT_RUNTIME_MODE env var must be "envoy" or "serverless"; got "${value}"`
13667
- );
13668
- };
13669
- var getRivetkitPublicDir = () => {
13670
- const value = getEnvUniversal("RIVETKIT_PUBLIC_DIR");
13671
- return value === void 0 || value === "" ? void 0 : value;
13672
- };
13673
- function parsePortEnv(raw) {
13674
- if (raw === void 0 || raw === "") return void 0;
13675
- const parsed = Number.parseInt(raw, 10);
13676
- if (!Number.isFinite(parsed) || parsed < 1 || parsed > 65535 || String(parsed) !== raw.trim()) {
13677
- throw new Error(
13678
- `RIVET_PORT env var must be an integer between 1 and 65535; got "${raw}"`
13679
- );
13680
- }
13681
- return parsed;
13682
- }
13683
- var getLogLevel = () => getEnvUniversal("RIVET_LOG_LEVEL") ?? getEnvUniversal("LOG_LEVEL");
13684
- var getLogTarget = () => getEnvUniversal("RIVET_LOG_TARGET") === "1";
13685
- var getLogTimestamp = () => getEnvUniversal("RIVET_LOG_TIMESTAMP") === "1";
13686
- var getLogMessage = () => getEnvUniversal("RIVET_LOG_MESSAGE") === "1";
13687
- var getLogErrorStack = () => getEnvUniversal("RIVET_LOG_ERROR_STACK") === "1";
13688
- var getNodeEnv = () => getEnvUniversal("NODE_ENV");
13689
- var getNextPhase = () => getEnvUniversal("NEXT_PHASE");
13690
- var isDev = () => getNodeEnv() !== "production";
13691
- function assertUnreachable(x) {
13692
- throw new Error(`Unreachable case: ${x}`);
13693
- }
13694
- function deconstructError(error46, exposeInternalError = false) {
13695
- let statusCode;
13696
- let public_;
13697
- let group;
13698
- let code;
13699
- let message;
13700
- let metadata;
13701
- let rayId;
13702
- let actor2;
13703
- if (isCanonicalStructuredRivetError(error46)) {
13704
- statusCode = typeof error46.statusCode === "number" ? error46.statusCode : error46.public ? 400 : 500;
13705
- public_ = error46.public ?? false;
13706
- group = error46.group;
13707
- code = error46.code;
13708
- message = error46.message;
13709
- metadata = error46.metadata;
13710
- rayId = error46.rayId;
13711
- actor2 = error46.actor;
13712
- } else if (RivetError.isActorError(error46) && error46.public) {
13713
- statusCode = "statusCode" in error46 && error46.statusCode ? error46.statusCode : 400;
13714
- public_ = true;
13715
- group = error46.group;
13716
- code = error46.code;
13717
- message = getErrorMessage(error46);
13718
- metadata = error46.metadata;
13719
- rayId = error46.rayId;
13720
- actor2 = error46.actor;
13721
- } else if (exposeInternalError) {
13722
- if (RivetError.isActorError(error46)) {
13723
- statusCode = 500;
13724
- public_ = false;
13725
- group = error46.group;
13726
- code = error46.code;
13727
- message = getErrorMessage(error46);
13728
- metadata = error46.metadata;
13729
- rayId = error46.rayId;
13730
- actor2 = error46.actor;
13731
- } else {
13732
- statusCode = 500;
13733
- public_ = false;
13734
- group = "rivetkit";
13735
- code = INTERNAL_ERROR_CODE;
13736
- message = getErrorMessage(error46);
13737
- }
13738
- } else {
13739
- statusCode = 500;
13740
- public_ = false;
13741
- group = "rivetkit";
13742
- code = INTERNAL_ERROR_CODE;
13743
- message = INTERNAL_ERROR_DESCRIPTION;
13744
- if (RivetError.isActorError(error46)) {
13745
- actor2 = error46.actor;
13746
- }
13747
- metadata = {
13748
- //url: `https://dashboard.rivet.dev/projects/${actorMetadata.project.slug}/environments/${actorMetadata.environment.slug}/actors?actorId=${actorMetadata.actor.id}`,
13749
- };
13750
- }
13751
- return {
13752
- __type: "ActorError",
13753
- statusCode,
13754
- public: public_,
13755
- group,
13756
- code,
13757
- message,
13758
- metadata,
13759
- rayId,
13760
- actor: actor2
13761
- };
13762
- }
13763
- function stringifyError(error46) {
13764
- if (error46 instanceof Error) {
13765
- if (typeof process !== "undefined" && getLogErrorStack()) {
13766
- let stack;
13767
- try {
13768
- stack = error46.stack;
13769
- } catch {
13770
- stack = void 0;
13771
- }
13772
- return `${error46.name}: ${error46.message}${stack ? `
13773
- ${stack}` : ""}`;
13774
- } else {
13775
- return `${error46.name}: ${error46.message}`;
13776
- }
13777
- } else if (typeof error46 === "string") {
13778
- return error46;
13779
- } else if (typeof error46 === "object" && error46 !== null) {
13780
- try {
13781
- return `${JSON.stringify(error46)}`;
13782
- } catch {
13783
- return "[cannot stringify error]";
13784
- }
13785
- } else {
13786
- return `Unknown error: ${getErrorMessage(error46)}`;
13787
- }
13788
- }
13789
- function getErrorMessage(err) {
13790
- if (err && typeof err === "object" && "message" in err && typeof err.message === "string") {
13791
- return err.message;
13792
- } else {
13793
- return String(err);
13794
- }
13795
- }
13796
- function noopNext() {
13797
- return async () => {
13798
- };
13334
+ function noopNext() {
13335
+ return async () => {
13336
+ };
13799
13337
  }
13800
13338
  var package_default = {
13801
13339
  name: "rivetkit",
13802
- version: "2.3.19",
13340
+ version: "2.3.21",
13803
13341
  description: "Lightweight libraries for building stateful actors on edge platforms",
13804
13342
  license: "Apache-2.0",
13805
13343
  keywords: [
@@ -14012,6 +13550,7 @@ var package_default = {
14012
13550
  "@rivet-dev/agent-os-core": "^0.1.1",
14013
13551
  "@rivet-dev/services": "^0.1.5",
14014
13552
  "@rivetkit/bare-ts": "^0.6.2",
13553
+ "@rivetkit/engine-api-full": "workspace:*",
14015
13554
  "@rivetkit/engine-cli": "workspace:*",
14016
13555
  "@rivetkit/engine-envoy-protocol": "workspace:*",
14017
13556
  "@rivetkit/on-change": "6.0.1",
@@ -15105,7 +14644,7 @@ function Config({ initialBufferLength = 1024, maxBufferLength = 1024 * 1024 * 32
15105
14644
  };
15106
14645
  }
15107
14646
 
15108
- // ../rivetkit/dist/tsup/chunk-4SC2NSAV.js
14647
+ // ../rivetkit/dist/tsup/chunk-CJXBGTVT.js
15109
14648
  var config2 = /* @__PURE__ */ Config({});
15110
14649
  function readWorkflowCbor(bc) {
15111
14650
  return readData(bc);
@@ -15326,82 +14865,577 @@ function readWorkflowEntryKind(bc) {
15326
14865
  }
15327
14866
  }
15328
14867
  }
15329
- function readWorkflowEntry(bc) {
15330
- return {
15331
- id: readString(bc),
15332
- location: readWorkflowLocation(bc),
15333
- kind: readWorkflowEntryKind(bc)
15334
- };
15335
- }
15336
- function read3(bc) {
15337
- return readBool(bc) ? readU64(bc) : null;
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;
14985
+ }
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
+ );
14993
+ }
14994
+ function collectActionEntries(actions) {
14995
+ const entries = [];
14996
+ const names = /* @__PURE__ */ new Set();
14997
+ visitActionGroup(actions ?? {}, [], entries, names);
14998
+ return entries;
14999
+ }
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);
15023
+ }
15024
+ }
15025
+ }
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;
15035
+ }
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;
15042
+ }
15043
+ function formatActionPath(path2) {
15044
+ return path2.length === 0 ? "actions" : `Action \`${path2.join(".")}\``;
15045
+ }
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
+ );
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;
15160
+ }
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;
15338
15165
  }
15339
- function readWorkflowEntryMetadata(bc) {
15340
- return {
15341
- status: readWorkflowEntryStatus(bc),
15342
- error: read1(bc),
15343
- attempts: readU32(bc),
15344
- lastAttemptAt: readU64(bc),
15345
- createdAt: readU64(bc),
15346
- completedAt: read3(bc),
15347
- rollbackCompletedAt: read3(bc),
15348
- rollbackError: read1(bc)
15349
- };
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);
15350
15170
  }
15351
- function read4(bc) {
15352
- const len = readUintSafe(bc);
15353
- if (len === 0) {
15354
- return [];
15355
- }
15356
- const result = [readString(bc)];
15357
- for (let i = 1; i < len; i++) {
15358
- result[i] = readString(bc);
15359
- }
15360
- 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;
15361
15176
  }
15362
- function read5(bc) {
15363
- const len = readUintSafe(bc);
15364
- if (len === 0) {
15365
- return [];
15366
- }
15367
- const result = [readWorkflowEntry(bc)];
15368
- for (let i = 1; i < len; i++) {
15369
- 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 };
15370
15183
  }
15371
- return result;
15184
+ return { name: run.name, icon: run.icon };
15372
15185
  }
15373
- function read6(bc) {
15374
- const len = readUintSafe(bc);
15375
- const result = /* @__PURE__ */ new Map();
15376
- for (let i = 0; i < len; i++) {
15377
- const offset = bc.offset;
15378
- const key = readString(bc);
15379
- if (result.has(key)) {
15380
- bc.offset = offset;
15381
- throw new BareError(offset, "duplicated key");
15382
- }
15383
- 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;
15384
15191
  }
15385
- return result;
15192
+ return run.inspector;
15386
15193
  }
15387
- function readWorkflowHistory(bc) {
15388
- return {
15389
- nameRegistry: read4(bc),
15390
- entries: read5(bc),
15391
- entryMetadata: read6(bc)
15392
- };
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;
15393
15199
  }
15394
- function decodeWorkflowHistory(bytes) {
15395
- const bc = new ByteCursor(bytes, config2);
15396
- const result = readWorkflowHistory(bc);
15397
- if (bc.offset < bc.view.byteLength) {
15398
- throw new BareError(bc.offset, "remaining bytes");
15200
+ function disposeRunInspector(run, actorId) {
15201
+ var _a2;
15202
+ if (!run || typeof run !== "function") {
15203
+ return;
15399
15204
  }
15400
- return result;
15401
- }
15402
- function decodeWorkflowHistoryTransport(data) {
15403
- 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);
15404
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.");
15405
15439
 
15406
15440
  // ../rivetkit/dist/tsup/chunk-JI6GZ2C2.js
15407
15441
  var EMPTY_KEY = "/";
@@ -15520,7 +15554,7 @@ function removePrefixFromKey(prefixedKey) {
15520
15554
  return prefixedKey.slice(KEYS.KV.length);
15521
15555
  }
15522
15556
 
15523
- // ../rivetkit/dist/tsup/chunk-X7RMJQGY.js
15557
+ // ../rivetkit/dist/tsup/chunk-2CI2IEVN.js
15524
15558
  function logger() {
15525
15559
  return getLogger("actor-client");
15526
15560
  }
@@ -15641,7 +15675,7 @@ var AsyncMutex = class {
15641
15675
  }
15642
15676
  };
15643
15677
 
15644
- // ../rivetkit/dist/tsup/chunk-BKX7UDTA.js
15678
+ // ../rivetkit/dist/tsup/chunk-PYRI75DL.js
15645
15679
  var import_invariant2 = __toESM(require_invariant(), 1);
15646
15680
 
15647
15681
  // ../../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
@@ -16856,7 +16890,7 @@ var TraceAPI = (
16856
16890
  // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js
16857
16891
  var trace = TraceAPI.getInstance();
16858
16892
 
16859
- // ../rivetkit/dist/tsup/chunk-BKX7UDTA.js
16893
+ // ../rivetkit/dist/tsup/chunk-PYRI75DL.js
16860
16894
  var import_invariant3 = __toESM(require_invariant(), 1);
16861
16895
  var import_invariant4 = __toESM(require_invariant(), 1);
16862
16896
  var PATH_CONNECT = "/connect";
@@ -19330,7 +19364,8 @@ async function sendHttpRequest(opts) {
19330
19364
  {
19331
19365
  metadata: responseData.metadata,
19332
19366
  rayId: rayId ?? void 0,
19333
- actor: responseData.actor
19367
+ actor: responseData.actor,
19368
+ statusCode: response.status
19334
19369
  }
19335
19370
  );
19336
19371
  } catch (error46) {
@@ -20238,6 +20273,22 @@ var ActorHandleRaw = class {
20238
20273
  "dynamic actor resolution did not produce a direct actor id"
20239
20274
  );
20240
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
+ }
20241
20292
  /**
20242
20293
  * Returns the raw URL for routing traffic to the actor.
20243
20294
  */
@@ -20270,6 +20321,8 @@ var ACTOR_CONNS_SYMBOL = /* @__PURE__ */ Symbol("actorConns");
20270
20321
  var CREATE_ACTOR_CONN_PROXY = /* @__PURE__ */ Symbol("createActorConnProxy");
20271
20322
  var ClientRaw = class {
20272
20323
  #disposed = false;
20324
+ /** Issue namespace-scoped tokens with an explicit grant list. */
20325
+ auth;
20273
20326
  [ACTOR_CONNS_SYMBOL] = /* @__PURE__ */ new Set();
20274
20327
  #driver;
20275
20328
  #encodingKind;
@@ -20281,6 +20334,9 @@ var ClientRaw = class {
20281
20334
  */
20282
20335
  constructor(driver, options = {}) {
20283
20336
  this.#driver = driver;
20337
+ this.auth = {
20338
+ issueToken: (issueOptions) => this.#driver.issueToken(issueOptions)
20339
+ };
20284
20340
  this.#encodingKind = options.encoding ?? "bare";
20285
20341
  this.#gatewayOptions = options.gateway ?? {};
20286
20342
  this.#currentActorInvocation = options.currentActorInvocation;
@@ -20572,6 +20628,72 @@ function createActorProxy(handle) {
20572
20628
  }
20573
20629
  });
20574
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
+ }
20575
20697
  var CONNECT_SYMBOL = /* @__PURE__ */ Symbol("connect");
20576
20698
  var ActorConnRaw = class {
20577
20699
  #disposed = false;
@@ -20600,6 +20722,7 @@ var ActorConnRaw = class {
20600
20722
  /** Promise used to indicate the socket has connected successfully. This will be rejected if the connection fails. */
20601
20723
  #onOpenPromise;
20602
20724
  #websocket;
20725
+ #authRetryAvailable = true;
20603
20726
  #client;
20604
20727
  #driver;
20605
20728
  #currentActorInvocation;
@@ -20845,6 +20968,10 @@ var ActorConnRaw = class {
20845
20968
  if (error46 instanceof ActorConnDisposed) {
20846
20969
  return false;
20847
20970
  }
20971
+ if (error46 instanceof RivetError && isInvalidToken(error46.group, error46.code) && this.#driver.refreshAuthToken && this.#authRetryAvailable) {
20972
+ this.#authRetryAvailable = false;
20973
+ return true;
20974
+ }
20848
20975
  if (error46 instanceof RivetError && this.#shouldReconnectForStaleActor(error46.group, error46.code)) {
20849
20976
  return true;
20850
20977
  }
@@ -20969,6 +21096,7 @@ var ActorConnRaw = class {
20969
21096
  messageQueueLength: this.#messageQueue.length,
20970
21097
  connId: this.#connId
20971
21098
  });
21099
+ this.#authRetryAvailable = true;
20972
21100
  this.#setConnStatus("connected");
20973
21101
  if (this.#onOpenPromise) {
20974
21102
  this.#onOpenPromise.resolve(void 0);
@@ -21111,7 +21239,8 @@ var ActorConnRaw = class {
21111
21239
  }
21112
21240
  /** Called by the onclose event from drivers. */
21113
21241
  async #handleOnClose(event2) {
21114
- var _a2;
21242
+ var _a2, _b, _c;
21243
+ const failedSocket = this.#websocket;
21115
21244
  const closeEvent = event2;
21116
21245
  const wasClean = closeEvent.wasClean;
21117
21246
  const wasConnected = this.#connStatus === "connected";
@@ -21133,9 +21262,24 @@ var ActorConnRaw = class {
21133
21262
  const parsed = parseWebSocketCloseReason(reason);
21134
21263
  if (parsed) {
21135
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
+ }
21136
21280
  if (this.#shouldReconnectForStaleActor(group, code)) {
21137
21281
  this.#clearResolvedActorIdentity();
21138
- (_a2 = this.#onOpenPromise) == null ? void 0 : _a2.reject(
21282
+ (_c = this.#onOpenPromise) == null ? void 0 : _c.reject(
21139
21283
  new RivetError(
21140
21284
  group,
21141
21285
  code,
@@ -21182,7 +21326,7 @@ var ActorConnRaw = class {
21182
21326
  if (error46 instanceof RivetError) {
21183
21327
  this.#dispatchActorError(error46);
21184
21328
  }
21185
- if (wasConnected) {
21329
+ if (wasConnected && this.#authRetryAvailable) {
21186
21330
  logger().debug({
21187
21331
  msg: "triggering reconnect",
21188
21332
  connId: this.#connId
@@ -21651,6 +21795,23 @@ var ActorConnRaw = class {
21651
21795
  );
21652
21796
  }
21653
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
+ }
21654
21815
  function tryParseEndpoint(ctx, options) {
21655
21816
  const {
21656
21817
  endpoint,
@@ -21745,6 +21906,8 @@ var ClientConfigSchemaBase = v4_default.object({
21745
21906
  }),
21746
21907
  /** Token to use to authenticate with the API. */
21747
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(),
21748
21911
  /** Namespace to connect to. */
21749
21912
  namespace: v4_default.string().optional().transform((val) => val ?? getRivetNamespace()),
21750
21913
  /** Name of the envoy pool. This is used to group together envoys in to different pools. */
@@ -21789,7 +21952,7 @@ function transformClientConfig(config3, ctx) {
21789
21952
  ...config3,
21790
21953
  endpoint: parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint,
21791
21954
  namespace: (parsedEndpoint == null ? void 0 : parsedEndpoint.namespace) ?? config3.namespace ?? "default",
21792
- 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)
21793
21956
  };
21794
21957
  }
21795
21958
  function convertRegistryConfigToClientConfig(config3) {
@@ -21797,6 +21960,7 @@ function convertRegistryConfigToClientConfig(config3) {
21797
21960
  return {
21798
21961
  endpoint: config3.endpoint,
21799
21962
  token: config3.token,
21963
+ getToken: void 0,
21800
21964
  namespace: config3.namespace,
21801
21965
  poolName: config3.envoy.poolName,
21802
21966
  headers: config3.headers,
@@ -22128,7 +22292,8 @@ async function openWebSocketToGateway(runConfig, gatewayUrl, encoding, params, o
22128
22292
  const ackHookToken = typeof process !== "undefined" && process.env.VITEST ? crypto.randomUUID() : void 0;
22129
22293
  logger2().debug({
22130
22294
  msg: "opening websocket to actor via guard",
22131
- gatewayUrl
22295
+ // Gateway URLs can embed credentials; never include the path or query in logs.
22296
+ origin: new URL(gatewayUrl).origin
22132
22297
  });
22133
22298
  const ws = new WebSocket2(
22134
22299
  gatewayUrl,
@@ -22218,6 +22383,14 @@ async function apiCall(config3, method2, path2, body) {
22218
22383
  responseFromBare: (value) => value
22219
22384
  });
22220
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
+ }
22221
22394
  async function getActor(config3, _, actorId) {
22222
22395
  return apiCall(
22223
22396
  config3,
@@ -22459,6 +22632,8 @@ function closeWebSocketIfOpen(ws, code, reason) {
22459
22632
  var RemoteEngineControlClient = class {
22460
22633
  #config;
22461
22634
  #metadataPromise;
22635
+ #tokenProvider;
22636
+ #webSocketTokens = /* @__PURE__ */ new WeakMap();
22462
22637
  constructor(runConfig) {
22463
22638
  if (getNextPhase() === "phase-production-build") {
22464
22639
  logger2().info(
@@ -22467,6 +22642,8 @@ var RemoteEngineControlClient = class {
22467
22642
  runConfig.disableMetadataLookup = true;
22468
22643
  }
22469
22644
  this.#config = { ...runConfig };
22645
+ if (runConfig.getToken)
22646
+ this.#tokenProvider = new TokenProvider(runConfig.getToken);
22470
22647
  if (!runConfig.disableMetadataLookup) {
22471
22648
  this.#metadataPromise = lookupMetadataCached(this.#config).then(
22472
22649
  (metadataData) => {
@@ -22475,14 +22652,13 @@ var RemoteEngineControlClient = class {
22475
22652
  if (metadataData.clientNamespace) {
22476
22653
  this.#config.namespace = metadataData.clientNamespace;
22477
22654
  }
22478
- if (metadataData.clientToken) {
22655
+ if (metadataData.clientToken && !this.#tokenProvider) {
22479
22656
  this.#config.token = metadataData.clientToken;
22480
22657
  }
22481
22658
  logger2().info({
22482
22659
  msg: "overriding client endpoint",
22483
22660
  endpoint: metadataData.clientEndpoint,
22484
- namespace: metadataData.clientNamespace,
22485
- token: metadataData.clientToken
22661
+ namespace: metadataData.clientNamespace
22486
22662
  });
22487
22663
  }
22488
22664
  logger2().info({
@@ -22495,12 +22671,47 @@ var RemoteEngineControlClient = class {
22495
22671
  );
22496
22672
  }
22497
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
+ }
22498
22706
  async getForId({
22499
22707
  name,
22500
22708
  actorId
22501
22709
  }) {
22502
22710
  await this.#metadataPromise;
22503
- const response = await getActor(this.#config, name, actorId);
22711
+ const response = await this.#withCredential(
22712
+ (config3) => getActor(config3, name, actorId),
22713
+ true
22714
+ );
22504
22715
  const actor2 = response.actors[0];
22505
22716
  if (!actor2) return void 0;
22506
22717
  if (actor2.name !== name) {
@@ -22521,7 +22732,10 @@ var RemoteEngineControlClient = class {
22521
22732
  await this.#metadataPromise;
22522
22733
  logger2().debug({ msg: "getWithKey: searching for actor", name, key });
22523
22734
  try {
22524
- const response = await getActorByKey(this.#config, name, key);
22735
+ const response = await this.#withCredential(
22736
+ (config3) => getActorByKey(config3, name, key),
22737
+ true
22738
+ );
22525
22739
  const actor2 = response.actors[0];
22526
22740
  if (!actor2) return void 0;
22527
22741
  logger2().debug({
@@ -22554,16 +22768,18 @@ var RemoteEngineControlClient = class {
22554
22768
  key
22555
22769
  });
22556
22770
  try {
22557
- const { actor: actor2, created } = await getOrCreateActor(this.#config, {
22558
- datacenter: region,
22559
- name,
22560
- key: serializeActorKey(key),
22561
- runner_name_selector: poolName ?? this.#config.poolName,
22562
- input: actorInput ? uint8ArrayToBase642(
22563
- encodeCborCompat(actorInput)
22564
- ) : void 0,
22565
- crash_policy: crashPolicy ?? "sleep"
22566
- });
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
+ );
22567
22783
  logger2().info({
22568
22784
  msg: "getOrCreateWithKey: actor ready",
22569
22785
  actorId: actor2.actor_id,
@@ -22579,7 +22795,10 @@ var RemoteEngineControlClient = class {
22579
22795
  name,
22580
22796
  key
22581
22797
  });
22582
- const response = await getActorByKey(this.#config, name, key);
22798
+ const response = await this.#withCredential(
22799
+ (config3) => getActorByKey(config3, name, key),
22800
+ true
22801
+ );
22583
22802
  const existing = response.actors[0];
22584
22803
  if (!existing) throw error46;
22585
22804
  logger2().info({
@@ -22603,14 +22822,18 @@ var RemoteEngineControlClient = class {
22603
22822
  }) {
22604
22823
  await this.#metadataPromise;
22605
22824
  logger2().info({ msg: "creating actor via engine api", name, key });
22606
- const result = await createActor(this.#config, {
22607
- datacenter: region,
22608
- name,
22609
- runner_name_selector: poolName ?? this.#config.poolName,
22610
- key: serializeActorKey(key),
22611
- input: input ? uint8ArrayToBase642(encodeCborCompat(input)) : void 0,
22612
- crash_policy: crashPolicy ?? "sleep"
22613
- });
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
+ );
22614
22837
  logger2().info({
22615
22838
  msg: "actor created",
22616
22839
  actorId: result.actor.actor_id,
@@ -22622,43 +22845,61 @@ var RemoteEngineControlClient = class {
22622
22845
  async listActors({ name }) {
22623
22846
  await this.#metadataPromise;
22624
22847
  logger2().debug({ msg: "listing actors via engine api", name });
22625
- const response = await listActorsByName(this.#config, name);
22848
+ const response = await this.#withCredential(
22849
+ (config3) => listActorsByName(config3, name),
22850
+ true
22851
+ );
22626
22852
  return response.actors.map(apiActorToOutput);
22627
22853
  }
22628
22854
  async destroyActor(actorId) {
22629
22855
  await this.#metadataPromise;
22630
22856
  logger2().info({ msg: "destroying actor via engine api", actorId });
22631
- await destroyActor(this.#config, actorId);
22857
+ await this.#withCredential((config3) => destroyActor(config3, actorId));
22632
22858
  logger2().info({ msg: "actor destroyed", actorId });
22633
22859
  }
22634
22860
  async sendRequest(target, actorRequest, options = {}) {
22861
+ var _a2;
22635
22862
  await this.#metadataPromise;
22636
- const path2 = requestPath(actorRequest);
22637
- const gatewayUrl = this.#buildGatewayUrlForTarget(
22638
- target,
22639
- path2,
22640
- options
22641
- );
22863
+ const config3 = await this.#authorizedConfig();
22642
22864
  const httpOptions = {
22643
22865
  ...options,
22644
22866
  directActorId: shouldSkipReadyWait(options) ? directActorIdFromTarget(target) : void 0
22645
22867
  };
22646
- return sendHttpRequestToGateway(
22647
- this.#config,
22648
- gatewayUrl,
22868
+ const send = (current) => sendHttpRequestToGateway(
22869
+ current,
22870
+ this.#buildGatewayUrlForTarget(
22871
+ current,
22872
+ target,
22873
+ requestPath(actorRequest),
22874
+ options
22875
+ ),
22649
22876
  actorRequest,
22650
22877
  httpOptions
22651
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;
22652
22891
  }
22653
22892
  async openWebSocket(path2, target, encoding, params, options = {}) {
22654
22893
  await this.#metadataPromise;
22894
+ const config3 = await this.#authorizedConfig();
22655
22895
  const gatewayUrl = this.#buildGatewayUrlForTarget(
22896
+ config3,
22656
22897
  target,
22657
22898
  path2,
22658
22899
  options
22659
22900
  );
22660
- return openWebSocketToGateway(
22661
- this.#config,
22901
+ const ws = await openWebSocketToGateway(
22902
+ config3,
22662
22903
  gatewayUrl,
22663
22904
  encoding,
22664
22905
  params,
@@ -22667,25 +22908,59 @@ var RemoteEngineControlClient = class {
22667
22908
  directActorId: shouldSkipReadyWait(options) ? directActorIdFromTarget(target) : void 0
22668
22909
  }
22669
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
+ );
22670
22944
  }
22671
22945
  async buildGatewayUrl(target, options = {}) {
22672
22946
  await this.#metadataPromise;
22673
- return this.#buildGatewayUrlForTarget(target, "", options);
22947
+ return this.#buildGatewayUrlForTarget(
22948
+ await this.#authorizedConfig(),
22949
+ target,
22950
+ "",
22951
+ options
22952
+ );
22674
22953
  }
22675
22954
  async proxyRequest(_c, actorRequest, actorId) {
22676
- await this.#metadataPromise;
22677
- const gatewayUrl = this.#buildGatewayUrlForTarget(
22678
- { directId: actorId },
22679
- requestPath(actorRequest)
22680
- );
22681
- return sendHttpRequestToGateway(this.#config, gatewayUrl, actorRequest);
22955
+ return this.sendRequest({ directId: actorId }, actorRequest);
22682
22956
  }
22683
22957
  async proxyWebSocket(c, path2, actorId, encoding, params) {
22684
- var _a2, _b;
22958
+ var _a2;
22685
22959
  await this.#metadataPromise;
22686
- 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);
22687
22962
  (0, import_invariant4.default)(upgradeWebSocket, "missing getUpgradeWebSocket");
22688
- const endpoint = getEndpoint(this.#config);
22963
+ const endpoint = getEndpoint(config3);
22689
22964
  const guardUrl = combineUrlPath(endpoint, path2);
22690
22965
  const wsGuardUrl = guardUrl.replace("http://", "ws://");
22691
22966
  logger2().debug({
@@ -22695,7 +22970,7 @@ var RemoteEngineControlClient = class {
22695
22970
  guardUrl
22696
22971
  });
22697
22972
  const protocols = buildWebSocketProtocols(
22698
- this.#config,
22973
+ config3,
22699
22974
  encoding,
22700
22975
  params,
22701
22976
  void 0,
@@ -22713,8 +22988,8 @@ var RemoteEngineControlClient = class {
22713
22988
  setGetUpgradeWebSocket(getUpgradeWebSocket) {
22714
22989
  this.#config.getUpgradeWebSocket = getUpgradeWebSocket;
22715
22990
  }
22716
- #buildGatewayUrlForTarget(target, path2, options = {}) {
22717
- const endpoint = getEndpoint(this.#config);
22991
+ #buildGatewayUrlForTarget(config3, target, path2, options = {}) {
22992
+ const endpoint = getEndpoint(config3);
22718
22993
  if (shouldSkipReadyWait(options) && directActorIdFromTarget(target) && canUseDirectSkipReadyWaitPath(path2)) {
22719
22994
  return combineUrlPath(endpoint, path2);
22720
22995
  }
@@ -22722,7 +22997,7 @@ var RemoteEngineControlClient = class {
22722
22997
  return buildActorGatewayUrl(
22723
22998
  endpoint,
22724
22999
  target.directId,
22725
- this.#config.token,
23000
+ config3.token,
22726
23001
  path2
22727
23002
  );
22728
23003
  }
@@ -22730,20 +23005,20 @@ var RemoteEngineControlClient = class {
22730
23005
  return buildActorGatewayUrl(
22731
23006
  endpoint,
22732
23007
  target.getForId.actorId,
22733
- this.#config.token,
23008
+ config3.token,
22734
23009
  path2
22735
23010
  );
22736
23011
  }
22737
23012
  if ("getForKey" in target || "getOrCreateForKey" in target) {
22738
23013
  return buildActorQueryGatewayUrl(
22739
23014
  endpoint,
22740
- this.#config.namespace,
23015
+ config3.namespace,
22741
23016
  target,
22742
- this.#config.token,
23017
+ config3.token,
22743
23018
  path2,
22744
- this.#config.maxInputSize,
23019
+ config3.maxInputSize,
22745
23020
  void 0,
22746
- "getOrCreateForKey" in target ? target.getOrCreateForKey.poolName ?? this.#config.poolName : void 0,
23021
+ "getOrCreateForKey" in target ? target.getOrCreateForKey.poolName ?? config3.poolName : void 0,
22747
23022
  options
22748
23023
  );
22749
23024
  }
@@ -22792,7 +23067,7 @@ function apiActorToOutput(actor2) {
22792
23067
  };
22793
23068
  }
22794
23069
 
22795
- // ../rivetkit/dist/tsup/chunk-WME6KOXW.js
23070
+ // ../rivetkit/dist/tsup/chunk-5EGLHQJJ.js
22796
23071
  var nativeStateTransactionOpeners = /* @__PURE__ */ new WeakMap();
22797
23072
  var nativeStateTransactionClientBinders = /* @__PURE__ */ new WeakMap();
22798
23073
  function registerNativeStateTransactionOpener(provider, opener) {
@@ -24285,12 +24560,14 @@ function isStaticActorInstance(_actor) {
24285
24560
  return true;
24286
24561
  }
24287
24562
  function actor(input) {
24563
+ var _a2;
24288
24564
  warnDeprecatedOptionKeys(
24289
24565
  input == null ? void 0 : input.options
24290
24566
  );
24291
24567
  const config3 = ActorConfigSchema.parse(input);
24292
24568
  flattenActionHandlers(config3.actions);
24293
24569
  flattenActionInputSchemas(config3.actions, config3.actionInputSchemas);
24570
+ flattenActionTraceSamplers(config3.actions, (_a2 = config3.tracing) == null ? void 0 : _a2.actions);
24294
24571
  return new ActorDefinition(config3);
24295
24572
  }
24296
24573
  function isStaticActorDefinition(definition) {
@@ -24532,23 +24809,6 @@ var InlineWebSocketAdapter = class {
24532
24809
  }
24533
24810
  }
24534
24811
  };
24535
- var ENGINE_HOST = "127.0.0.1";
24536
- var ENGINE_PORT = 6420;
24537
- var ENGINE_ENDPOINT = buildEngineEndpoint(ENGINE_HOST, ENGINE_PORT);
24538
- function buildEngineEndpoint(host, port) {
24539
- const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
24540
- return `http://${urlHost}:${port}`;
24541
- }
24542
- function isLocalEngineEndpoint(endpoint) {
24543
- let url2;
24544
- try {
24545
- url2 = new URL(endpoint);
24546
- } catch {
24547
- return false;
24548
- }
24549
- const hostname3 = url2.hostname.toLowerCase();
24550
- return hostname3 === "localhost" || hostname3 === "0.0.0.0" || hostname3 === "::" || hostname3 === "[::]" || hostname3 === "::1" || hostname3 === "[::1]" || /^127(?:\.\d{1,3}){0,3}$/.test(hostname3);
24551
- }
24552
24812
  function logger22() {
24553
24813
  return getLogger("registry");
24554
24814
  }
@@ -24646,20 +24906,9 @@ async function configureServerlessPool(config3) {
24646
24906
  });
24647
24907
  throw lastError;
24648
24908
  }
24649
- var warnedMissingVersion = false;
24650
24909
  var EnvoyConfigSchema = external_exports.object({
24651
24910
  poolName: external_exports.string().default(() => getRivetPool() ?? "default"),
24652
- version: external_exports.number().default(() => {
24653
- const version2 = getRivetEnvoyVersion();
24654
- if (version2 !== void 0) return version2;
24655
- if (getNodeEnv() === "production" && !warnedMissingVersion) {
24656
- warnedMissingVersion = true;
24657
- getLogger("rivetkit").error(
24658
- "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"
24659
- );
24660
- }
24661
- return 1;
24662
- }),
24911
+ version: external_exports.number().default(() => getRivetEnvoyVersion() ?? 1),
24663
24912
  // Deprecated.
24664
24913
  totalSlots: external_exports.number().default(() => getRivetTotalSlots() ?? 1e5),
24665
24914
  envoyKey: external_exports.string().optional()
@@ -24959,7 +25208,7 @@ var RegistryConfigSchema = external_exports.object({
24959
25208
  config3.startEngine || parsedEndpoint
24960
25209
  );
24961
25210
  const namespace = (parsedEndpoint == null ? void 0 : parsedEndpoint.namespace) ?? config3.namespace ?? "default";
24962
- 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);
24963
25212
  const parsedPublicEndpoint = config3.serverless.publicEndpoint ? tryParseEndpoint(ctx, {
24964
25213
  endpoint: config3.serverless.publicEndpoint,
24965
25214
  path: ["serverless", "publicEndpoint"]
@@ -30163,6 +30412,13 @@ function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databa
30163
30412
  )
30164
30413
  });
30165
30414
  }
30415
+ function buildActorTracingConfig(actions, tracing) {
30416
+ if (tracing === void 0) return void 0;
30417
+ return {
30418
+ sampler: tracing.sampler,
30419
+ actions: flattenActionTraceSamplers(actions, tracing.actions)
30420
+ };
30421
+ }
30166
30422
  function buildActorConfig(definition, registryConfig, runtimeKind) {
30167
30423
  var _a2;
30168
30424
  const config3 = definition.config;
@@ -30176,6 +30432,10 @@ function buildActorConfig(definition, registryConfig, runtimeKind) {
30176
30432
  hasDatabase: true,
30177
30433
  remoteSqlite: usesRemoteSqlite,
30178
30434
  sqliteProfiling,
30435
+ tracing: buildActorTracingConfig(
30436
+ definition.config.actions,
30437
+ definition.config.tracing
30438
+ ),
30179
30439
  enableActorRuntimeSocket: options.enableActorRuntimeSocket === true,
30180
30440
  hasState: config3.state !== void 0 || typeof config3.createState === "function",
30181
30441
  canHibernateWebsocket: typeof canHibernate === "boolean" ? canHibernate : void 0,
@@ -31913,7 +32173,23 @@ var Registry = class {
31913
32173
  * Starts an actor envoy for standalone server deployments.
31914
32174
  */
31915
32175
  #startEnvoy(config3, printWelcome) {
32176
+ var _a2;
31916
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
+ }
31917
32193
  const configuredRegistryPromise = this.#buildConfiguredRegistry(config3);
31918
32194
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
31919
32195
  this.#runtimeServeLifecyclePromise = configuredRegistryPromise.then(