"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }

var _chunkMMUXNMJFcjs = require('./chunk-MMUXNMJF.cjs');







var _chunkL47L3ZWJcjs = require('./chunk-L47L3ZWJ.cjs');

// src/actor/config.ts
var _v4 = require('zod/v4');
var zFunction = () => _v4.z.custom((val) => typeof val === "function");
var WorkflowInspectorConfigSchema = _v4.z.object({
  getHistory: zFunction(),
  onHistoryUpdated: zFunction().optional()
});
var RunInspectorConfigSchema = _v4.z.object({
  workflow: WorkflowInspectorConfigSchema.optional()
}).optional();
var RunConfigSchema = _v4.z.object({
  /** Display name for the actor in the Inspector UI. */
  name: _v4.z.string().optional(),
  /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
  icon: _v4.z.string().optional(),
  /** The run handler function. */
  run: zFunction(),
  /** Inspector integration for long-running run handlers. */
  inspector: RunInspectorConfigSchema.optional()
});
var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for(
  "rivetkit.run_function_config"
);
var zRunHandler = _v4.z.union([zFunction(), RunConfigSchema]).optional();
function getRunFunction(run) {
  if (!run) return void 0;
  if (typeof run === "function") return run;
  return run.run;
}
function getRunMetadata(run) {
  if (!run) return {};
  if (typeof run === "function") {
    const config = run[RUN_FUNCTION_CONFIG_SYMBOL];
    if (!config) return {};
    return { name: config.name, icon: config.icon };
  }
  return { name: run.name, icon: run.icon };
}
function getRunInspectorConfig(run) {
  var _a;
  if (!run) return void 0;
  if (typeof run === "function") {
    return (_a = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a.inspector;
  }
  return run.inspector;
}
var ActorConfigSchema = _v4.z.object({
  onCreate: zFunction().optional(),
  onDestroy: zFunction().optional(),
  onWake: zFunction().optional(),
  onSleep: zFunction().optional(),
  run: zRunHandler,
  onStateChange: zFunction().optional(),
  onBeforeConnect: zFunction().optional(),
  onConnect: zFunction().optional(),
  onDisconnect: zFunction().optional(),
  onBeforeActionResponse: zFunction().optional(),
  onRequest: zFunction().optional(),
  onWebSocket: zFunction().optional(),
  actions: _v4.z.record(_v4.z.string(), zFunction()).default(() => ({})),
  events: _v4.z.record(_v4.z.string(), _v4.z.any()).optional(),
  queues: _v4.z.record(_v4.z.string(), _v4.z.any()).optional(),
  state: _v4.z.any().optional(),
  createState: zFunction().optional(),
  connState: _v4.z.any().optional(),
  createConnState: zFunction().optional(),
  vars: _v4.z.any().optional(),
  db: _v4.z.any().optional(),
  createVars: zFunction().optional(),
  options: _v4.z.object({
    /** Display name for the actor in the Inspector UI. */
    name: _v4.z.string().optional(),
    /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
    icon: _v4.z.string().optional(),
    createVarsTimeout: _v4.z.number().positive().default(5e3),
    createConnStateTimeout: _v4.z.number().positive().default(5e3),
    onConnectTimeout: _v4.z.number().positive().default(5e3),
    // This must be less than engine config > pegboard.actor_stop_threshold
    onSleepTimeout: _v4.z.number().positive().default(5e3),
    // This must be less than engine config > pegboard.actor_stop_threshold
    onDestroyTimeout: _v4.z.number().positive().default(5e3),
    stateSaveInterval: _v4.z.number().positive().default(1e4),
    actionTimeout: _v4.z.number().positive().default(6e4),
    // Max time to wait for waitUntil background promises during shutdown
    waitUntilTimeout: _v4.z.number().positive().default(15e3),
    // Max time to wait for run handler to stop during shutdown
    runStopTimeout: _v4.z.number().positive().default(15e3),
    connectionLivenessTimeout: _v4.z.number().positive().default(2500),
    connectionLivenessInterval: _v4.z.number().positive().default(5e3),
    noSleep: _v4.z.boolean().default(false),
    sleepTimeout: _v4.z.number().positive().default(3e4),
    maxQueueSize: _v4.z.number().positive().default(1e3),
    maxQueueMessageSize: _v4.z.number().positive().default(64 * 1024),
    /**
     * Can hibernate WebSockets for onWebSocket.
     *
     * WebSockets using actions/events are hibernatable by default.
     *
     * @experimental
     **/
    canHibernateWebSocket: _v4.z.union([
      _v4.z.boolean(),
      zFunction()
    ]).default(false)
  }).strict().prefault(() => ({}))
}).strict().refine(
  (data) => !(data.state !== void 0 && data.createState !== void 0),
  {
    message: "Cannot define both 'state' and 'createState'",
    path: ["state"]
  }
).refine(
  (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
  {
    message: "Cannot define both 'connState' and 'createConnState'",
    path: ["connState"]
  }
).refine(
  (data) => !(data.vars !== void 0 && data.createVars !== void 0),
  {
    message: "Cannot define both 'vars' and 'createVars'",
    path: ["vars"]
  }
);
var DocActorOptionsSchema = _v4.z.object({
  name: _v4.z.string().optional().describe("Display name for the actor in the Inspector UI."),
  icon: _v4.z.string().optional().describe(
    "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
  ),
  createVarsTimeout: _v4.z.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
  createConnStateTimeout: _v4.z.number().optional().describe(
    "Timeout in ms for createConnState handler. Default: 5000"
  ),
  onConnectTimeout: _v4.z.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
  onSleepTimeout: _v4.z.number().optional().describe(
    "Timeout in ms for onSleep handler. Must be less than ACTOR_STOP_THRESHOLD_MS. Default: 5000"
  ),
  onDestroyTimeout: _v4.z.number().optional().describe("Timeout in ms for onDestroy handler. Default: 5000"),
  stateSaveInterval: _v4.z.number().optional().describe(
    "Interval in ms between automatic state saves. Default: 10000"
  ),
  actionTimeout: _v4.z.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
  waitUntilTimeout: _v4.z.number().optional().describe(
    "Max time in ms to wait for waitUntil background promises during shutdown. Default: 15000"
  ),
  runStopTimeout: _v4.z.number().optional().describe(
    "Max time in ms to wait for run handler to stop during shutdown. Default: 15000"
  ),
  connectionLivenessTimeout: _v4.z.number().optional().describe(
    "Timeout in ms for connection liveness checks. Default: 2500"
  ),
  connectionLivenessInterval: _v4.z.number().optional().describe(
    "Interval in ms between connection liveness checks. Default: 5000"
  ),
  noSleep: _v4.z.boolean().optional().describe("If true, the actor will never sleep. Default: false"),
  sleepTimeout: _v4.z.number().optional().describe(
    "Time in ms of inactivity before the actor sleeps. Default: 30000"
  ),
  maxQueueSize: _v4.z.number().optional().describe(
    "Maximum number of queue messages before rejecting new messages. Default: 1000"
  ),
  maxQueueMessageSize: _v4.z.number().optional().describe(
    "Maximum size of each queue message in bytes. Default: 65536"
  ),
  canHibernateWebSocket: _v4.z.boolean().optional().describe(
    "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
  )
}).describe("Actor options for timeouts and behavior configuration.");
var DocActorConfigSchema = _v4.z.object({
  state: _v4.z.unknown().optional().describe(
    "Initial state value for the actor. Cannot be used with createState."
  ),
  createState: _v4.z.unknown().optional().describe(
    "Function to create initial state. Receives context and input. Cannot be used with state."
  ),
  connState: _v4.z.unknown().optional().describe(
    "Initial connection state value. Cannot be used with createConnState."
  ),
  createConnState: _v4.z.unknown().optional().describe(
    "Function to create connection state. Receives context and connection params. Cannot be used with connState."
  ),
  vars: _v4.z.unknown().optional().describe(
    "Initial ephemeral variables value. Cannot be used with createVars."
  ),
  createVars: _v4.z.unknown().optional().describe(
    "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
  ),
  db: _v4.z.unknown().optional().describe("Database provider instance for the actor."),
  onCreate: _v4.z.unknown().optional().describe(
    "Called when the actor is first initialized. Use to initialize state."
  ),
  onDestroy: _v4.z.unknown().optional().describe("Called when the actor is destroyed."),
  onWake: _v4.z.unknown().optional().describe(
    "Called when the actor wakes up and is ready to receive connections and actions."
  ),
  onSleep: _v4.z.unknown().optional().describe(
    "Called when the actor is stopping or sleeping. Use to clean up resources."
  ),
  run: _v4.z.unknown().optional().describe(
    "Called after actor starts. Does not block startup. Use for background tasks like queue processing or tick loops. If it exits or throws, the actor crashes."
  ),
  onStateChange: _v4.z.unknown().optional().describe(
    "Called when the actor's state changes. State changes within this hook won't trigger recursion."
  ),
  onBeforeConnect: _v4.z.unknown().optional().describe(
    "Called before a client connects. Throw an error to reject the connection."
  ),
  onConnect: _v4.z.unknown().optional().describe("Called when a client successfully connects."),
  onDisconnect: _v4.z.unknown().optional().describe("Called when a client disconnects."),
  onBeforeActionResponse: _v4.z.unknown().optional().describe(
    "Called before sending an action response. Use to transform output."
  ),
  onRequest: _v4.z.unknown().optional().describe(
    "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
  ),
  onWebSocket: _v4.z.unknown().optional().describe(
    "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
  ),
  actions: _v4.z.record(_v4.z.string(), _v4.z.unknown()).optional().describe(
    "Map of action name to handler function. Defaults to an empty object."
  ),
  events: _v4.z.record(_v4.z.string(), _v4.z.unknown()).optional().describe("Map of event names to schemas."),
  queues: _v4.z.record(_v4.z.string(), _v4.z.unknown()).optional().describe("Map of queue names to schemas."),
  options: DocActorOptionsSchema.optional()
}).describe("Actor configuration passed to the actor() function.");

// src/actor/instance/keys.ts
var KEYS = {
  PERSIST_DATA: Uint8Array.from([1]),
  CONN_PREFIX: Uint8Array.from([2]),
  // Prefix for connection keys
  INSPECTOR_TOKEN: Uint8Array.from([3]),
  // Inspector token key
  KV: Uint8Array.from([4]),
  // Prefix for user-facing KV storage
  QUEUE_PREFIX: Uint8Array.from([5]),
  // Prefix for queue storage
  WORKFLOW_PREFIX: Uint8Array.from([6]),
  // Prefix for workflow storage
  TRACES_PREFIX: Uint8Array.from([7]),
  // Prefix for traces storage
  SQLITE_PREFIX: Uint8Array.from([8])
  // Prefix for SQLite VFS data
};
var STORAGE_VERSION = {
  QUEUE: 1,
  WORKFLOW: 1,
  TRACES: 1,
  SQLITE: 1
};
var STORAGE_VERSION_BYTES = {
  QUEUE: Uint8Array.from([STORAGE_VERSION.QUEUE]),
  WORKFLOW: Uint8Array.from([STORAGE_VERSION.WORKFLOW]),
  TRACES: Uint8Array.from([STORAGE_VERSION.TRACES]),
  SQLITE: Uint8Array.from([STORAGE_VERSION.SQLITE])
};
var QUEUE_NAMESPACE = {
  METADATA: Uint8Array.from([1]),
  MESSAGES: Uint8Array.from([2])
};
var QUEUE_ID_BYTES = 8;
function concatPrefix(prefix, suffix) {
  const merged = new Uint8Array(prefix.length + suffix.length);
  merged.set(prefix, 0);
  merged.set(suffix, prefix.length);
  return merged;
}
var QUEUE_STORAGE_PREFIX = concatPrefix(
  KEYS.QUEUE_PREFIX,
  STORAGE_VERSION_BYTES.QUEUE
);
var QUEUE_METADATA_KEY = concatPrefix(
  QUEUE_STORAGE_PREFIX,
  QUEUE_NAMESPACE.METADATA
);
var QUEUE_MESSAGES_PREFIX = concatPrefix(
  QUEUE_STORAGE_PREFIX,
  QUEUE_NAMESPACE.MESSAGES
);
var WORKFLOW_STORAGE_PREFIX = concatPrefix(
  KEYS.WORKFLOW_PREFIX,
  STORAGE_VERSION_BYTES.WORKFLOW
);
var TRACES_STORAGE_PREFIX = concatPrefix(
  KEYS.TRACES_PREFIX,
  STORAGE_VERSION_BYTES.TRACES
);
var SQLITE_STORAGE_PREFIX = concatPrefix(
  KEYS.SQLITE_PREFIX,
  STORAGE_VERSION_BYTES.SQLITE
);
function makePrefixedKey(key) {
  const prefixed = new Uint8Array(KEYS.KV.length + key.length);
  prefixed.set(KEYS.KV, 0);
  prefixed.set(key, KEYS.KV.length);
  return prefixed;
}
function removePrefixFromKey(prefixedKey) {
  return prefixedKey.slice(KEYS.KV.length);
}
function makeWorkflowKey(key) {
  return concatPrefix(WORKFLOW_STORAGE_PREFIX, key);
}
function workflowStoragePrefix() {
  return Uint8Array.from(WORKFLOW_STORAGE_PREFIX);
}
function tracesStoragePrefix() {
  return Uint8Array.from(TRACES_STORAGE_PREFIX);
}
function queueMetadataKey() {
  return Uint8Array.from(QUEUE_METADATA_KEY);
}
function queueMessagesPrefix() {
  return Uint8Array.from(QUEUE_MESSAGES_PREFIX);
}
function makeConnKey(connId) {
  const encoder = new TextEncoder();
  const connIdBytes = encoder.encode(connId);
  const key = new Uint8Array(KEYS.CONN_PREFIX.length + connIdBytes.length);
  key.set(KEYS.CONN_PREFIX, 0);
  key.set(connIdBytes, KEYS.CONN_PREFIX.length);
  return key;
}
function makeQueueMessageKey(id) {
  const key = new Uint8Array(QUEUE_MESSAGES_PREFIX.length + QUEUE_ID_BYTES);
  key.set(QUEUE_MESSAGES_PREFIX, 0);
  const view = new DataView(key.buffer, key.byteOffset, key.byteLength);
  view.setBigUint64(QUEUE_MESSAGES_PREFIX.length, id, false);
  return key;
}
function decodeQueueMessageKey(key) {
  const offset = QUEUE_MESSAGES_PREFIX.length;
  if (key.length < offset + QUEUE_ID_BYTES) {
    throw new Error("Queue key is too short");
  }
  for (let i = 0; i < QUEUE_MESSAGES_PREFIX.length; i++) {
    if (key[i] !== QUEUE_MESSAGES_PREFIX[i]) {
      throw new Error("Queue key has invalid prefix");
    }
  }
  const view = new DataView(
    key.buffer,
    key.byteOffset + offset,
    QUEUE_ID_BYTES
  );
  return view.getBigUint64(0, false);
}

// src/actor/instance/kv.ts
var textEncoder = new TextEncoder();
var textDecoder = new TextDecoder();
function encodeKey(key, keyType) {
  if (key instanceof Uint8Array) {
    return key;
  }
  const resolvedKeyType = _nullishCoalesce(keyType, () => ( "text"));
  if (resolvedKeyType === "binary") {
    throw new TypeError("Expected a Uint8Array when keyType is binary");
  }
  return textEncoder.encode(key);
}
function decodeKey(key, keyType) {
  const resolvedKeyType = _nullishCoalesce(keyType, () => ( "text"));
  switch (resolvedKeyType) {
    case "text":
      return textDecoder.decode(key);
    case "binary":
      return key;
    default:
      throw new TypeError("Invalid kv key type");
  }
}
function resolveValueType(value) {
  if (typeof value === "string") {
    return "text";
  }
  if (value instanceof Uint8Array) {
    return "binary";
  }
  if (value instanceof ArrayBuffer) {
    return "arrayBuffer";
  }
  throw new TypeError("Invalid kv value");
}
function encodeValue(value, options) {
  const type = _nullishCoalesce((options == null ? void 0 : options.type), () => ( resolveValueType(value)));
  switch (type) {
    case "text":
      if (typeof value !== "string") {
        throw new TypeError("Expected a string when type is text");
      }
      return textEncoder.encode(value);
    case "arrayBuffer":
      if (!(value instanceof ArrayBuffer)) {
        throw new TypeError("Expected an ArrayBuffer when type is arrayBuffer");
      }
      return new Uint8Array(value);
    case "binary":
      if (!(value instanceof Uint8Array)) {
        throw new TypeError("Expected a Uint8Array when type is binary");
      }
      return value;
    default:
      throw new TypeError("Invalid kv value type");
  }
}
function decodeValue(value, options) {
  const type = _nullishCoalesce((options == null ? void 0 : options.type), () => ( "text"));
  switch (type) {
    case "text":
      return textDecoder.decode(value);
    case "arrayBuffer": {
      const copy = new Uint8Array(value.byteLength);
      copy.set(value);
      return copy.buffer;
    }
    case "binary":
      return value;
    default:
      throw new TypeError("Invalid kv value type");
  }
}
var ActorKv = class {
  #driver;
  #actorId;
  constructor(driver, actorId) {
    this.#driver = driver;
    this.#actorId = actorId;
  }
  /**
   * Get a single value by key.
   */
  async get(key, options) {
    const results = await this.#driver.kvBatchGet(this.#actorId, [
      makePrefixedKey(encodeKey(key))
    ]);
    const result = results[0];
    if (!result) {
      return null;
    }
    return decodeValue(result, options);
  }
  /**
   * Get multiple values by keys.
   */
  async getBatch(keys, options) {
    const prefixedKeys = keys.map(
      (key) => makePrefixedKey(encodeKey(key))
    );
    const results = await this.#driver.kvBatchGet(
      this.#actorId,
      prefixedKeys
    );
    return results.map(
      (result) => result ? decodeValue(result, options) : null
    );
  }
  /**
   * Put a single key-value pair.
   */
  async put(key, value, options) {
    await this.#driver.kvBatchPut(this.#actorId, [
      [makePrefixedKey(encodeKey(key)), encodeValue(value, options)]
    ]);
  }
  /**
   * Put multiple key-value pairs.
   */
  async putBatch(entries, options) {
    const prefixedEntries = entries.map(
      ([key, value]) => [
        makePrefixedKey(encodeKey(key)),
        encodeValue(value, options)
      ]
    );
    await this.#driver.kvBatchPut(this.#actorId, prefixedEntries);
  }
  /**
   * Delete a single key.
   */
  async delete(key) {
    await this.#driver.kvBatchDelete(this.#actorId, [
      makePrefixedKey(encodeKey(key))
    ]);
  }
  /**
   * Delete multiple keys.
   */
  async deleteBatch(keys) {
    const prefixedKeys = keys.map(
      (key) => makePrefixedKey(encodeKey(key))
    );
    await this.#driver.kvBatchDelete(this.#actorId, prefixedKeys);
  }
  /**
   * List all keys with a given prefix.
   * Returns key-value pairs where keys have the user prefix removed.
   */
  async list(prefix, options) {
    const prefixedPrefix = makePrefixedKey(
      encodeKey(prefix, options == null ? void 0 : options.keyType)
    );
    const results = await this.#driver.kvListPrefix(
      this.#actorId,
      prefixedPrefix
    );
    return results.map(([key, value]) => [
      decodeKey(removePrefixFromKey(key), options == null ? void 0 : options.keyType),
      decodeValue(value, options)
    ]);
  }
};

// src/actor/log.ts
function loggerWithoutContext() {
  return _chunkMMUXNMJFcjs.getLogger.call(void 0, "actor-runtime");
}

// src/actor/utils.ts
function assertUnreachable(x) {
  loggerWithoutContext().error({
    msg: "unreachable",
    value: `${x}`,
    stack: new Error().stack
  });
  throw new (0, _chunkL47L3ZWJcjs.Unreachable)(x);
}
var DeadlineError = class extends Error {
  constructor() {
    super("Promise did not complete before deadline.");
  }
};
function deadline(promise, timeout) {
  const controller = new AbortController();
  const signal = controller.signal;
  const timeoutId = setTimeout(() => controller.abort(), timeout);
  return Promise.race([
    promise,
    new Promise((_, reject) => {
      signal.addEventListener("abort", () => reject(new DeadlineError()));
    })
  ]).finally(() => {
    clearTimeout(timeoutId);
  });
}
function joinAbortSignals(...signals) {
  const activeSignals = signals.filter(
    (signal) => signal !== void 0
  );
  if (activeSignals.length === 0) {
    return { signal: void 0, cleanup: () => {
    } };
  }
  if (activeSignals.length === 1) {
    return { signal: activeSignals[0], cleanup: () => {
    } };
  }
  const controller = new AbortController();
  if (activeSignals.some((signal) => signal.aborted)) {
    controller.abort();
    return { signal: controller.signal, cleanup: () => {
    } };
  }
  const cleanup = () => {
    for (const signal of activeSignals) {
      signal.removeEventListener("abort", onAbort);
    }
  };
  const onAbort = () => {
    controller.abort();
    cleanup();
  };
  for (const signal of activeSignals) {
    signal.addEventListener("abort", onAbort, { once: true });
  }
  return { signal: controller.signal, cleanup };
}
function generateSecureToken(length = 32) {
  const array = new Uint8Array(length);
  crypto.getRandomValues(array);
  return btoa(String.fromCharCode(...array)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
function isStatePath(path) {
  return path === "state" || path.startsWith("state.");
}
function isConnStatePath(path) {
  if (!path.startsWith("connections.")) {
    return false;
  }
  const stateIndex = path.indexOf(".state", 12);
  if (stateIndex === -1) {
    return false;
  }
  const afterState = stateIndex + 6;
  return path.length === afterState || path[afterState] === ".";
}

// src/actor/instance/queue.ts
var ActorQueue = class {
  #queueManager;
  #abortSignal;
  #pendingCompletableMessageIds = /* @__PURE__ */ new Set();
  constructor(queueManager, abortSignal) {
    this.#queueManager = queueManager;
    this.#abortSignal = abortSignal;
  }
  async next(opts) {
    const resolvedOpts = _nullishCoalesce(opts, () => ( {}));
    const completable = resolvedOpts.completable === true;
    if (this.#pendingCompletableMessageIds.size > 0) {
      throw new (0, _chunkL47L3ZWJcjs.QueuePreviousMessageNotCompleted)();
    }
    const names = this.#normalizeNames(resolvedOpts.names);
    const count = Math.max(1, _nullishCoalesce(resolvedOpts.count, () => ( 1)));
    const { signal, cleanup } = joinAbortSignals(
      this.#abortSignal,
      resolvedOpts.signal
    );
    const messages = await this.#queueManager.receive(
      names,
      count,
      resolvedOpts.timeout,
      signal,
      completable
    ).finally(cleanup);
    if (!completable) {
      return messages;
    }
    return messages.map((message) => this.#makeCompletableMessage(message));
  }
  async tryNext(opts) {
    const resolvedOpts = _nullishCoalesce(opts, () => ( {}));
    if (resolvedOpts.completable === true) {
      return await this.next({
        names: resolvedOpts.names,
        count: resolvedOpts.count,
        timeout: 0,
        completable: true
      });
    }
    return await this.next({
      names: resolvedOpts.names,
      count: resolvedOpts.count,
      timeout: 0
    });
  }
  async *iter(opts) {
    const resolvedOpts = _nullishCoalesce(opts, () => ( {}));
    while (!this.#abortSignal.aborted) {
      try {
        const messages = resolvedOpts.completable === true ? await this.next({
          names: resolvedOpts.names,
          count: 1,
          signal: resolvedOpts.signal,
          completable: true
        }) : await this.next({
          names: resolvedOpts.names,
          count: 1,
          signal: resolvedOpts.signal
        });
        if (messages.length === 0) {
          continue;
        }
        yield messages[0];
      } catch (error) {
        if (error instanceof _chunkL47L3ZWJcjs.ActorAborted) {
          return;
        }
        throw error;
      }
    }
  }
  async send(name, body) {
    return await this.#queueManager.enqueue(name, body);
  }
  #normalizeNames(names) {
    if (!names || names.length === 0) {
      return void 0;
    }
    return [...new Set(names)];
  }
  #makeCompletableMessage(message) {
    const messageId = message.id.toString();
    this.#pendingCompletableMessageIds.add(messageId);
    let completed = false;
    const completableMessage = {
      ...message,
      complete: async (response) => {
        if (completed) {
          throw new (0, _chunkL47L3ZWJcjs.QueueAlreadyCompleted)();
        }
        completed = true;
        try {
          await this.#queueManager.completeMessage(message, response);
          this.#pendingCompletableMessageIds.delete(messageId);
        } catch (error) {
          completed = false;
          throw error;
        }
      }
    };
    return completableMessage;
  }
};

// src/actor/schema.ts
function event(options) {
  return _nullishCoalesce(options, () => ( {}));
}
function queue(options) {
  return _nullishCoalesce(options, () => ( {}));
}
function isStandardSchema(value) {
  return typeof value === "object" && value !== null && "~standard" in value;
}
function isQueueSchemaDefinition(value) {
  if (isEventSchemaDefinition(value)) {
    return false;
  }
  return typeof value === "object" && value !== null && "message" in value && value.message !== void 0;
}
function isEventSchemaDefinition(value) {
  return typeof value === "object" && value !== null && "schema" in value && value.schema !== void 0;
}
function hasSchemaConfigKey(schemas, key) {
  if (!schemas) {
    return false;
  }
  return Object.prototype.hasOwnProperty.call(schemas, key);
}
function getEventCanSubscribe(schemas, key) {
  const schema = schemas == null ? void 0 : schemas[key];
  if (!schema || isStandardSchema(schema)) {
    return void 0;
  }
  const maybeCanSubscribe = schema.canSubscribe;
  return typeof maybeCanSubscribe === "function" ? maybeCanSubscribe : void 0;
}
function getQueueCanPublish(schemas, key) {
  const schema = schemas == null ? void 0 : schemas[key];
  if (!schema || isStandardSchema(schema)) {
    return void 0;
  }
  const maybeCanPublish = schema.canPublish;
  return typeof maybeCanPublish === "function" ? maybeCanPublish : void 0;
}
function getValidationSchema(schema) {
  if (!schema) {
    return void 0;
  }
  if (isEventSchemaDefinition(schema)) {
    return schema.schema;
  }
  if (isQueueSchemaDefinition(schema)) {
    return schema.message;
  }
  if (typeof schema === "object" && schema !== null && "schema" in schema && schema.schema !== void 0) {
    return schema.schema;
  }
  if (typeof schema === "object" && schema !== null && "message" in schema && schema.message !== void 0) {
    return schema.message;
  }
  return schema;
}
function isPromiseLike(value) {
  return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
}
function validateSchemaSync(schemas, key, data) {
  const schema = getValidationSchema(schemas == null ? void 0 : schemas[key]);
  if (!schema) {
    return { success: true, data };
  }
  if (isStandardSchema(schema)) {
    const result = schema["~standard"].validate(data);
    if (isPromiseLike(result)) {
      throw new (0, _chunkL47L3ZWJcjs.Unsupported)("async schema validation");
    }
    if (result.issues) {
      return { success: false, issues: [...result.issues] };
    }
    return {
      success: true,
      data: result.value
    };
  }
  return { success: true, data };
}

// src/actor/contexts/base/actor.ts
var ACTOR_CONTEXT_INTERNAL_SYMBOL = /* @__PURE__ */ Symbol.for(
  "rivetkit.actorContextInternal"
);
var ActorContext = class {
  
  #actor;
  #kv;
  #queue;
  constructor(actor) {
    this.#actor = actor;
    this[ACTOR_CONTEXT_INTERNAL_SYMBOL] = actor;
  }
  /**
   * Gets the KV storage interface.
   */
  get kv() {
    if (!this.#kv) {
      this.#kv = new ActorKv(this.#actor.driver, this.#actor.id);
    }
    return this.#kv;
  }
  /**
   * Get the actor state
   *
   * @remarks
   * This property is not available in `createState` since the state hasn't been created yet.
   */
  get state() {
    return this.#actor.state;
  }
  /**
   * Get the actor variables
   *
   * @remarks
   * This property is not available in `createVars` since the variables haven't been created yet.
   * Variables are only available if you define `vars` or `createVars` in your actor config.
   */
  get vars() {
    return this.#actor.vars;
  }
  broadcast(name, ...args) {
    if (this.#actor.config.events !== void 0 && !hasSchemaConfigKey(this.#actor.config.events, name)) {
      this.#actor.rLog.warn({
        msg: "broadcasting event not defined in actor events config",
        eventName: name
      });
    }
    const payload = args.length === 1 ? args[0] : args;
    const result = validateSchemaSync(
      this.#actor.config.events,
      name,
      payload
    );
    if (!result.success) {
      throw new (0, _chunkL47L3ZWJcjs.EventPayloadInvalid)(name, result.issues);
    }
    if (args.length === 1) {
      this.#actor.eventManager.broadcast(name, result.data);
      return;
    }
    if (Array.isArray(result.data)) {
      this.#actor.eventManager.broadcast(
        name,
        ...result.data
      );
      return;
    }
    this.#actor.eventManager.broadcast(name, ...args);
  }
  /**
   * Gets the logger instance.
   */
  get log() {
    return this.#actor.log;
  }
  /**
   * Access to queue receive helpers.
   */
  get queue() {
    if (!this.#queue) {
      this.#queue = exports.queue = new ActorQueue(
        this.#actor.queueManager,
        this.#actor.abortSignal
      );
    }
    return this.#queue;
  }
  /**
   * Gets actor ID.
   */
  get actorId() {
    return this.#actor.id;
  }
  /**
   * Gets the actor name.
   */
  get name() {
    return this.#actor.name;
  }
  /**
   * Gets the actor key.
   */
  get key() {
    return this.#actor.key;
  }
  /**
   * Gets the region.
   */
  get region() {
    return this.#actor.region;
  }
  /**
   * Gets the scheduler.
   */
  get schedule() {
    return this.#actor.schedule;
  }
  /**
   * Gets the map of connections.
   */
  get conns() {
    return this.#actor.conns;
  }
  /**
   * Returns the client for the given registry.
   */
  client() {
    return this.#actor.inlineClient;
  }
  /**
   * Gets the database.
   *
   * @experimental
   * @remarks
   * This property is only available if you define a `db` provider in your actor config.
   * @throws {DatabaseNotEnabled} If the database is not enabled.
   */
  get db() {
    return this.#actor.db;
  }
  /**
   * Forces the state to get saved.
   *
   * @param opts - Options for saving the state.
   */
  async saveState(opts) {
    return this.#actor.stateManager.saveState(opts);
  }
  /**
   * Prevents the actor from sleeping until promise is complete.
   */
  waitUntil(promise) {
    this.#actor.waitUntil(promise);
  }
  /**
   * Prevents the actor from sleeping while the given promise is running.
   *
   * Use this when performing async operations in the `run` handler or other
   * background contexts where you need to ensure the actor stays awake.
   *
   * Returns the resolved value and resets the sleep timer on completion.
   * Errors are propagated to the caller.
   */
  keepAwake(promise) {
    return this.#actor.keepAwake(promise);
  }
  /**
   * AbortSignal that fires when the actor is stopping.
   */
  get abortSignal() {
    return this.#actor.abortSignal;
  }
  /**
   * True when the actor is stopping.
   *
   * Alias for `c.abortSignal.aborted`.
   */
  get aborted() {
    return this.#actor.abortSignal.aborted;
  }
  /**
   * Forces the actor to sleep.
   *
   * Not supported on all drivers.
   *
   * @experimental
   */
  sleep() {
    this.#actor.startSleep();
  }
  /**
   * Forces the actor to destroy.
   *
   * This will return immediately, then call `onStop` and `onDestroy`.
   *
   * @experimental
   */
  destroy() {
    this.#actor.startDestroy();
  }
};
































exports.RUN_FUNCTION_CONFIG_SYMBOL = RUN_FUNCTION_CONFIG_SYMBOL; exports.getRunFunction = getRunFunction; exports.getRunMetadata = getRunMetadata; exports.getRunInspectorConfig = getRunInspectorConfig; exports.ActorConfigSchema = ActorConfigSchema; exports.loggerWithoutContext = loggerWithoutContext; exports.assertUnreachable = assertUnreachable; exports.DeadlineError = DeadlineError; exports.deadline = deadline; exports.generateSecureToken = generateSecureToken; exports.isStatePath = isStatePath; exports.isConnStatePath = isConnStatePath; exports.event = event; exports.queue = queue; exports.hasSchemaConfigKey = hasSchemaConfigKey; exports.getEventCanSubscribe = getEventCanSubscribe; exports.getQueueCanPublish = getQueueCanPublish; exports.validateSchemaSync = validateSchemaSync; exports.KEYS = KEYS; exports.makeWorkflowKey = makeWorkflowKey; exports.workflowStoragePrefix = workflowStoragePrefix; exports.tracesStoragePrefix = tracesStoragePrefix; exports.queueMetadataKey = queueMetadataKey; exports.queueMessagesPrefix = queueMessagesPrefix; exports.makeConnKey = makeConnKey; exports.makeQueueMessageKey = makeQueueMessageKey; exports.decodeQueueMessageKey = decodeQueueMessageKey; exports.ActorKv = ActorKv; exports.ACTOR_CONTEXT_INTERNAL_SYMBOL = ACTOR_CONTEXT_INTERNAL_SYMBOL; exports.ActorContext = ActorContext;
//# sourceMappingURL=chunk-LNDVGTPQ.cjs.map