@rivetkit/supabase 2.3.11-rc.8 → 2.3.11

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 +1088 -181
  2. package/dist/mod.mjs +1085 -178
  3. package/package.json +3 -3
package/dist/mod.mjs CHANGED
@@ -471,7 +471,7 @@ function unsupportedFeature(feature) {
471
471
  );
472
472
  }
473
473
 
474
- // ../rivetkit/dist/tsup/chunk-AGNBLCNJ.js
474
+ // ../rivetkit/dist/tsup/chunk-OUENKQHB.js
475
475
  import {
476
476
  pino,
477
477
  stdTimeFunctions
@@ -13147,7 +13147,7 @@ var classic_default = external_exports;
13147
13147
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/index.js
13148
13148
  var v4_default = classic_default;
13149
13149
 
13150
- // ../rivetkit/dist/tsup/chunk-AGNBLCNJ.js
13150
+ // ../rivetkit/dist/tsup/chunk-OUENKQHB.js
13151
13151
  var import_invariant = __toESM(require_invariant(), 1);
13152
13152
  import * as cbor from "cbor-x";
13153
13153
  var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
@@ -13312,7 +13312,7 @@ function noopNext() {
13312
13312
  }
13313
13313
  var package_default = {
13314
13314
  name: "rivetkit",
13315
- version: "2.3.11-rc.8",
13315
+ version: "2.3.11",
13316
13316
  description: "Lightweight libraries for building stateful actors on edge platforms",
13317
13317
  license: "Apache-2.0",
13318
13318
  keywords: [
@@ -13448,6 +13448,16 @@ var package_default = {
13448
13448
  default: "./dist/tsup/inspector/mod.cjs"
13449
13449
  }
13450
13450
  },
13451
+ "./experimental/inspector/workflow": {
13452
+ import: {
13453
+ types: "./dist/tsup/inspector/workflow.d.ts",
13454
+ default: "./dist/tsup/inspector/workflow.js"
13455
+ },
13456
+ require: {
13457
+ types: "./dist/tsup/inspector/workflow.d.cts",
13458
+ default: "./dist/tsup/inspector/workflow.cjs"
13459
+ }
13460
+ },
13451
13461
  "./inspector-tab": {
13452
13462
  import: {
13453
13463
  types: "./dist/tsup/inspector-tab/mod.d.ts",
@@ -13493,7 +13503,7 @@ var package_default = {
13493
13503
  "./dist/tsup/chunk-*.cjs"
13494
13504
  ],
13495
13505
  scripts: {
13496
- build: "tsup src/mod.ts src/client/mod.ts src/common/log.ts src/common/websocket.ts src/actor/errors.ts src/utils.ts src/workflow/mod.ts src/test/mod.ts src/inspector/mod.ts src/inspector-tab/mod.ts src/db/mod.ts src/db/drizzle.ts src/dynamic/mod.ts src/unstable/migrations.ts && tsup src/agent-os/index.ts --no-clean --out-dir dist/tsup/agent-os",
13506
+ build: "tsup src/mod.ts src/client/mod.ts src/common/log.ts src/common/websocket.ts src/actor/errors.ts src/utils.ts src/workflow/mod.ts src/test/mod.ts src/inspector/mod.ts src/inspector/workflow.ts src/inspector-tab/mod.ts src/db/mod.ts src/db/drizzle.ts src/dynamic/mod.ts src/unstable/migrations.ts && tsup src/agent-os/index.ts --no-clean --out-dir dist/tsup/agent-os && node scripts/check-built-commonjs.mjs",
13497
13507
  "build:browser": "tsup --config tsup.browser.config.ts",
13498
13508
  "check-types": "tsc --noEmit",
13499
13509
  lint: "biome check . && pnpm run check:test-skips && pnpm run check:wait-for-comments",
@@ -14605,7 +14615,7 @@ function Config({ initialBufferLength = 1024, maxBufferLength = 1024 * 1024 * 32
14605
14615
  };
14606
14616
  }
14607
14617
 
14608
- // ../rivetkit/dist/tsup/chunk-4EDGOGCB.js
14618
+ // ../rivetkit/dist/tsup/chunk-QFJ24MBU.js
14609
14619
  var config2 = /* @__PURE__ */ Config({});
14610
14620
  function readWorkflowCbor(bc) {
14611
14621
  return readData(bc);
@@ -14903,7 +14913,7 @@ function decodeWorkflowHistoryTransport(data) {
14903
14913
  return decodeWorkflowHistory(toUint8Array(data));
14904
14914
  }
14905
14915
 
14906
- // ../rivetkit/dist/tsup/chunk-QWLJCP3X.js
14916
+ // ../rivetkit/dist/tsup/chunk-6W5VGLFT.js
14907
14917
  function flattenActionHandlers(actions) {
14908
14918
  const flattened = /* @__PURE__ */ Object.create(null);
14909
14919
  for (const { name, handler } of collectActionEntries(actions)) {
@@ -15009,6 +15019,7 @@ var zActionTree = external_exports.custom((value) => {
15009
15019
  });
15010
15020
  var WorkflowInspectorConfigSchema = external_exports.object({
15011
15021
  getHistory: zFunction(),
15022
+ getState: zFunction().optional(),
15012
15023
  onHistoryUpdated: zFunction().optional(),
15013
15024
  replayFromStep: zFunction().optional()
15014
15025
  });
@@ -15078,9 +15089,36 @@ var RunConfigSchema = external_exports.object({
15078
15089
  /** Inspector integration for long-running run handlers. */
15079
15090
  inspector: RunInspectorConfigSchema.optional()
15080
15091
  });
15081
- var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for(
15082
- "rivetkit.run_function_config"
15083
- );
15092
+ var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("rivetkit.run_function_config");
15093
+ function defineRunHandler(run, options) {
15094
+ if (options.inspectorKind === void 0 !== (options.createInspector === void 0)) {
15095
+ throw new TypeError(
15096
+ "defineRunHandler requires inspectorKind and createInspector together"
15097
+ );
15098
+ }
15099
+ Object.defineProperty(run, RUN_FUNCTION_CONFIG_SYMBOL, {
15100
+ configurable: false,
15101
+ enumerable: false,
15102
+ writable: false,
15103
+ value: {
15104
+ name: options.name,
15105
+ icon: options.icon,
15106
+ inspectorKind: options.inspectorKind,
15107
+ createInspector: options.createInspector
15108
+ }
15109
+ });
15110
+ return run;
15111
+ }
15112
+ function getRunInspectorKind(run) {
15113
+ var _a2;
15114
+ if (!run || typeof run !== "function") return void 0;
15115
+ return (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.inspectorKind;
15116
+ }
15117
+ function createRunInspector(run, context) {
15118
+ var _a2, _b;
15119
+ if (!run || typeof run !== "function") return void 0;
15120
+ return (_b = (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.createInspector) == null ? void 0 : _b.call(_a2, context);
15121
+ }
15084
15122
  var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
15085
15123
  function getRunFunction(run) {
15086
15124
  if (!run) return void 0;
@@ -15104,6 +15142,12 @@ function getRunInspectorConfig(run, actor2) {
15104
15142
  }
15105
15143
  return run.inspector;
15106
15144
  }
15145
+ function hasRunInspectorConfig(run) {
15146
+ if (!run) return false;
15147
+ if (typeof run !== "function") return run.inspector !== void 0;
15148
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15149
+ 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;
15150
+ }
15107
15151
  function disposeRunInspector(run, actorId) {
15108
15152
  var _a2;
15109
15153
  if (!run || typeof run !== "function") {
@@ -15450,8 +15494,63 @@ function removePrefixFromKey(prefixedKey) {
15450
15494
  return prefixedKey.slice(KEYS.KV.length);
15451
15495
  }
15452
15496
 
15453
- // ../rivetkit/dist/tsup/chunk-7AFZMFPQ.js
15497
+ // ../rivetkit/dist/tsup/chunk-JTHHCZCZ.js
15454
15498
  var MIGRATION_TRANSACTION_TIMEOUT_MS = 5 * 6e4;
15499
+ function isManualTransactionControl(query) {
15500
+ return /^\s*(?:BEGIN|SAVEPOINT|COMMIT|END|ROLLBACK)\b/i.test(query);
15501
+ }
15502
+ function validateTransactionTimeout(timeout) {
15503
+ if (timeout !== void 0 && (!Number.isFinite(timeout) || timeout <= 0)) {
15504
+ throw new Error(
15505
+ "db.transaction() timeout must be a positive finite number of milliseconds"
15506
+ );
15507
+ }
15508
+ }
15509
+ function validateTransactionName(name) {
15510
+ if (name === void 0) {
15511
+ return;
15512
+ }
15513
+ if (name.length === 0) {
15514
+ throw new Error("db.transaction() name must not be empty");
15515
+ }
15516
+ }
15517
+ function isSqliteBindingValue(value) {
15518
+ if (value === null || typeof value === "number" || typeof value === "string" || typeof value === "bigint" || value instanceof Uint8Array) {
15519
+ return true;
15520
+ }
15521
+ if (Array.isArray(value)) {
15522
+ return value.every((item) => typeof item === "number");
15523
+ }
15524
+ return false;
15525
+ }
15526
+ function isPlainObject3(value) {
15527
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
15528
+ return false;
15529
+ }
15530
+ return Object.getPrototypeOf(value) === Object.prototype;
15531
+ }
15532
+ function isSqliteBindingObject(value) {
15533
+ if (!isPlainObject3(value)) {
15534
+ return false;
15535
+ }
15536
+ return Object.values(value).every((entry) => isSqliteBindingValue(entry));
15537
+ }
15538
+ function toSqliteBindings(input) {
15539
+ if (Array.isArray(input)) {
15540
+ for (const value of input) {
15541
+ if (!isSqliteBindingValue(value)) {
15542
+ throw new Error(
15543
+ `unsupported sqlite binding type: ${typeof value}`
15544
+ );
15545
+ }
15546
+ }
15547
+ return input;
15548
+ }
15549
+ if (isSqliteBindingObject(input)) {
15550
+ return input;
15551
+ }
15552
+ throw new Error("unsupported sqlite binding collection");
15553
+ }
15455
15554
  var AsyncMutex = class {
15456
15555
  #locked = false;
15457
15556
  #waiting = [];
@@ -15478,7 +15577,7 @@ var AsyncMutex = class {
15478
15577
  }
15479
15578
  };
15480
15579
 
15481
- // ../rivetkit/dist/tsup/chunk-V6ANE6JM.js
15580
+ // ../rivetkit/dist/tsup/chunk-FWROC5LA.js
15482
15581
  function logger() {
15483
15582
  return getLogger("actor-client");
15484
15583
  }
@@ -15516,7 +15615,7 @@ async function importWebSocket() {
15516
15615
  return webSocketPromise;
15517
15616
  }
15518
15617
 
15519
- // ../rivetkit/dist/tsup/chunk-JBQ63WSM.js
15618
+ // ../rivetkit/dist/tsup/chunk-3ZR542SK.js
15520
15619
  var import_invariant2 = __toESM(require_invariant(), 1);
15521
15620
 
15522
15621
  // ../../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
@@ -15694,7 +15793,7 @@ function createVersionedDataHandler(config3) {
15694
15793
  return new VersionedDataHandler(config3);
15695
15794
  }
15696
15795
 
15697
- // ../rivetkit/dist/tsup/chunk-JBQ63WSM.js
15796
+ // ../rivetkit/dist/tsup/chunk-3ZR542SK.js
15698
15797
  var import_invariant3 = __toESM(require_invariant(), 1);
15699
15798
  var import_invariant4 = __toESM(require_invariant(), 1);
15700
15799
  var PATH_CONNECT = "/connect";
@@ -21410,6 +21509,231 @@ function apiActorToOutput(actor2) {
21410
21509
  };
21411
21510
  }
21412
21511
 
21512
+ // ../rivetkit/dist/tsup/chunk-6WYATRS4.js
21513
+ var nativeStateTransactionOpeners = /* @__PURE__ */ new WeakMap();
21514
+ var nativeStateTransactionClientBinders = /* @__PURE__ */ new WeakMap();
21515
+ function registerNativeStateTransactionOpener(provider, opener) {
21516
+ nativeStateTransactionOpeners.set(provider, opener);
21517
+ return provider;
21518
+ }
21519
+ function bindNativeStateTransactionContext(client, context) {
21520
+ if ((typeof client !== "object" || client === null) && typeof client !== "function") {
21521
+ return client;
21522
+ }
21523
+ const bind = nativeStateTransactionClientBinders.get(client);
21524
+ return (bind == null ? void 0 : bind(context)) ?? client;
21525
+ }
21526
+ function hasMultipleStatements(query) {
21527
+ const trimmed = query.trim().replace(/;+$/, "").trimEnd();
21528
+ return trimmed.includes(";");
21529
+ }
21530
+ function db({
21531
+ onMigrate,
21532
+ warnOnManualTransactions = true,
21533
+ profiling
21534
+ } = {}) {
21535
+ const provider = {
21536
+ sqliteProfiling: profiling,
21537
+ createClient: async (ctx) => {
21538
+ const nativeDatabaseProvider = ctx.nativeDatabaseProvider;
21539
+ if (!nativeDatabaseProvider) {
21540
+ throw new Error(
21541
+ "native SQLite is required, but the current runtime did not provide a native database provider"
21542
+ );
21543
+ }
21544
+ const db2 = await nativeDatabaseProvider.open(ctx.actorId);
21545
+ let closed = false;
21546
+ let manualTransactionWarned = false;
21547
+ const ensureOpen = () => {
21548
+ if (closed) {
21549
+ throw new Error(
21550
+ "Database is closed. This usually means a background timer (setInterval, setTimeout) or a stray promise is still running after the actor stopped. Use c.abortSignal to clean up timers before the actor shuts down."
21551
+ );
21552
+ }
21553
+ };
21554
+ const createClient = (target, transactionScoped = false, stateTransactionContext) => {
21555
+ const client2 = {
21556
+ execute: async (query, ...args) => {
21557
+ var _a2, _b, _c, _d;
21558
+ ensureOpen();
21559
+ if (!transactionScoped && warnOnManualTransactions && !manualTransactionWarned && !hasMultipleStatements(query) && isManualTransactionControl(query)) {
21560
+ manualTransactionWarned = true;
21561
+ getLogger("database").warn(
21562
+ { actorId: ctx.actorId },
21563
+ "Manual cross-call SQLite transactions can interleave with other actor work. Use db.transaction() for coordinated transactions. Set warnOnManualTransactions: false in your db(...) configuration to disable this warning."
21564
+ );
21565
+ }
21566
+ const kvReadsBefore = ((_a2 = ctx.metrics) == null ? void 0 : _a2.totalKvReads) ?? 0;
21567
+ const kvWritesBefore = ((_b = ctx.metrics) == null ? void 0 : _b.totalKvWrites) ?? 0;
21568
+ const start = performance.now();
21569
+ try {
21570
+ if (args.length > 0) {
21571
+ const bindings = args.length === 1 && isSqliteBindingObject(args[0]) ? toSqliteBindings(args[0]) : toSqliteBindings(args);
21572
+ const { rows, columns } = await target.execute(
21573
+ query,
21574
+ bindings
21575
+ );
21576
+ return rows.map(
21577
+ (row) => rowToObject(row, columns)
21578
+ );
21579
+ }
21580
+ if (!hasMultipleStatements(query)) {
21581
+ const { rows, columns } = await target.execute(
21582
+ query,
21583
+ void 0
21584
+ );
21585
+ return rows.map(
21586
+ (row) => rowToObject(row, columns)
21587
+ );
21588
+ }
21589
+ return await execMultiStatement(
21590
+ target,
21591
+ query
21592
+ );
21593
+ } finally {
21594
+ const durationMs = performance.now() - start;
21595
+ (_c = ctx.metrics) == null ? void 0 : _c.trackSql(query, durationMs);
21596
+ if (ctx.metrics) {
21597
+ const kvReads = ctx.metrics.totalKvReads - kvReadsBefore;
21598
+ const kvWrites = ctx.metrics.totalKvWrites - kvWritesBefore;
21599
+ (_d = ctx.log) == null ? void 0 : _d.debug({
21600
+ msg: "sql query",
21601
+ query: query.slice(0, 120),
21602
+ durationMs,
21603
+ kvReads,
21604
+ kvWrites
21605
+ });
21606
+ }
21607
+ }
21608
+ },
21609
+ transaction: async (callback, options) => {
21610
+ var _a2, _b;
21611
+ validateTransactionTimeout(options == null ? void 0 : options.timeout);
21612
+ validateTransactionName(options == null ? void 0 : options.name);
21613
+ if (transactionScoped && ((_a2 = options == null ? void 0 : options.experimental) == null ? void 0 : _a2.includeState)) {
21614
+ throw new Error(
21615
+ "experimental.includeState is not supported for nested transactions"
21616
+ );
21617
+ }
21618
+ const includeState = ((_b = options == null ? void 0 : options.experimental) == null ? void 0 : _b.includeState) === true;
21619
+ const stateScope = includeState && stateTransactionContext ? await stateTransactionContext.enter() : void 0;
21620
+ try {
21621
+ const transaction = includeState ? await (() => {
21622
+ const beginStateTransaction = ctx.nativeDatabaseProvider && nativeStateTransactionOpeners.get(
21623
+ ctx.nativeDatabaseProvider
21624
+ );
21625
+ if (!beginStateTransaction) {
21626
+ throw new Error(
21627
+ "experimental.includeState is only supported by RivetKit's embedded database provider"
21628
+ );
21629
+ }
21630
+ return beginStateTransaction(
21631
+ options == null ? void 0 : options.timeout,
21632
+ stateScope
21633
+ );
21634
+ })() : await db2.beginTransaction(
21635
+ options == null ? void 0 : options.timeout,
21636
+ options == null ? void 0 : options.name
21637
+ );
21638
+ const tx = createClient(transaction, true);
21639
+ try {
21640
+ const result = await callback(tx);
21641
+ await transaction.commit();
21642
+ return result;
21643
+ } catch (error46) {
21644
+ try {
21645
+ await transaction.rollback();
21646
+ } catch {
21647
+ }
21648
+ throw error46;
21649
+ }
21650
+ } finally {
21651
+ if (stateScope !== void 0) {
21652
+ stateTransactionContext == null ? void 0 : stateTransactionContext.exit(stateScope);
21653
+ }
21654
+ }
21655
+ },
21656
+ close: async () => {
21657
+ if (!closed) {
21658
+ closed = true;
21659
+ await db2.close();
21660
+ }
21661
+ },
21662
+ nativeMetrics: () => {
21663
+ var _a2;
21664
+ return ((_a2 = db2.nativeMetrics) == null ? void 0 : _a2.call(db2)) ?? null;
21665
+ }
21666
+ };
21667
+ if (!transactionScoped) {
21668
+ nativeStateTransactionClientBinders.set(
21669
+ client2,
21670
+ (context) => createClient(target, false, context)
21671
+ );
21672
+ }
21673
+ return client2;
21674
+ };
21675
+ const client = createClient(db2);
21676
+ return client;
21677
+ },
21678
+ onMigrate: async (client) => {
21679
+ if (onMigrate) {
21680
+ await withMigrationSavepoint(
21681
+ client,
21682
+ (leased) => onMigrate(leased)
21683
+ );
21684
+ }
21685
+ }
21686
+ };
21687
+ return provider;
21688
+ }
21689
+ function rowToObject(row, columns) {
21690
+ const rowObj = {};
21691
+ for (let i = 0; i < columns.length; i++) {
21692
+ rowObj[columns[i]] = row[i];
21693
+ }
21694
+ return rowObj;
21695
+ }
21696
+ async function execMultiStatement(db2, query) {
21697
+ const results = [];
21698
+ let columnNames = null;
21699
+ await db2.exec(query, (row, columns) => {
21700
+ if (!columnNames) {
21701
+ columnNames = columns;
21702
+ }
21703
+ results.push(rowToObject(row, columnNames));
21704
+ });
21705
+ return results;
21706
+ }
21707
+ async function withMigrationSavepoint(client, callback) {
21708
+ return await client.transaction(
21709
+ async (transaction) => {
21710
+ await transaction.execute("SAVEPOINT __rivet_on_migrate");
21711
+ try {
21712
+ const result = await callback(transaction);
21713
+ await transaction.execute(
21714
+ "RELEASE SAVEPOINT __rivet_on_migrate"
21715
+ );
21716
+ return result;
21717
+ } catch (error46) {
21718
+ try {
21719
+ await transaction.execute(
21720
+ "ROLLBACK TO SAVEPOINT __rivet_on_migrate"
21721
+ );
21722
+ } finally {
21723
+ await transaction.execute(
21724
+ "RELEASE SAVEPOINT __rivet_on_migrate"
21725
+ );
21726
+ }
21727
+ throw error46;
21728
+ }
21729
+ },
21730
+ {
21731
+ name: "rivetkit-migration",
21732
+ timeout: MIGRATION_TRANSACTION_TIMEOUT_MS
21733
+ }
21734
+ );
21735
+ }
21736
+
21413
21737
  // ../../../shared/typescript/virtual-websocket/dist/mod.js
21414
21738
  var VirtualWebSocket = class {
21415
21739
  static CONNECTING = 0;
@@ -23729,11 +24053,33 @@ function wrapJsNativeDatabase(database) {
23729
24053
  release();
23730
24054
  }
23731
24055
  },
23732
- async beginTransaction(timeoutMs) {
24056
+ async beginTransaction(timeoutMs, name) {
23733
24057
  const release = gate.enter();
23734
24058
  let transaction;
23735
24059
  try {
23736
- transaction = await database.beginTransaction(timeoutMs);
24060
+ transaction = await database.beginTransaction(timeoutMs, name);
24061
+ } catch (error46) {
24062
+ enrichNativeDatabaseError(database, error46);
24063
+ } finally {
24064
+ release();
24065
+ }
24066
+ return wrapTransaction(database, transaction, gate, (result) => {
24067
+ if (result.lastInsertRowId !== void 0) {
24068
+ lastInsertRowId = result.lastInsertRowId;
24069
+ }
24070
+ });
24071
+ },
24072
+ async beginStateTransaction(timeoutMs, context) {
24073
+ if (!database.beginStateTransaction) {
24074
+ throw new Error("actor state transactions are not configured");
24075
+ }
24076
+ const release = gate.enter();
24077
+ let transaction;
24078
+ try {
24079
+ transaction = await database.beginStateTransaction(
24080
+ timeoutMs,
24081
+ context
24082
+ );
23737
24083
  } catch (error46) {
23738
24084
  enrichNativeDatabaseError(database, error46);
23739
24085
  } finally {
@@ -23840,45 +24186,37 @@ var nodeChildProcess;
23840
24186
  var nodeStream;
23841
24187
  var nodeUrl;
23842
24188
  var hasImportedDependencies = false;
23843
- function getRequireFn() {
23844
- return createRequire(import.meta.url);
24189
+ var fallbackRequire;
24190
+ function loadNodeBuiltin(id) {
24191
+ var _a2;
24192
+ const nodeProcess = globalThis.process;
24193
+ const builtin = (_a2 = nodeProcess == null ? void 0 : nodeProcess.getBuiltinModule) == null ? void 0 : _a2.call(nodeProcess, id);
24194
+ if (builtin !== void 0) {
24195
+ return builtin;
24196
+ }
24197
+ if (!(nodeProcess == null ? void 0 : nodeProcess.execPath)) {
24198
+ throw new Error("Node.js built-ins are not available");
24199
+ }
24200
+ fallbackRequire ??= createRequire(nodeProcess.execPath);
24201
+ return fallbackRequire(id);
23845
24202
  }
23846
24203
  function importNodeDependencies() {
23847
24204
  if (hasImportedDependencies) return;
23848
24205
  try {
23849
- const requireFn = getRequireFn();
23850
- nodeCrypto = requireFn(
23851
- /* webpackIgnore: true */
23852
- "node:crypto"
23853
- );
23854
- nodeFsSync = requireFn(
23855
- /* webpackIgnore: true */
23856
- "node:fs"
23857
- );
23858
- nodeFs = requireFn(
23859
- /* webpackIgnore: true */
24206
+ nodeCrypto = loadNodeBuiltin("node:crypto");
24207
+ nodeFsSync = loadNodeBuiltin("node:fs");
24208
+ nodeFs = loadNodeBuiltin(
23860
24209
  "node:fs/promises"
23861
24210
  );
23862
- nodePath = requireFn(
23863
- /* webpackIgnore: true */
23864
- "node:path"
23865
- );
23866
- nodeOs = requireFn(
23867
- /* webpackIgnore: true */
23868
- "node:os"
23869
- );
23870
- nodeChildProcess = requireFn(
23871
- /* webpackIgnore: true */
24211
+ nodePath = loadNodeBuiltin("node:path");
24212
+ nodeOs = loadNodeBuiltin("node:os");
24213
+ nodeChildProcess = loadNodeBuiltin(
23872
24214
  "node:child_process"
23873
24215
  );
23874
- nodeStream = requireFn(
23875
- /* webpackIgnore: true */
24216
+ nodeStream = loadNodeBuiltin(
23876
24217
  "node:stream/promises"
23877
24218
  );
23878
- nodeUrl = requireFn(
23879
- /* webpackIgnore: true */
23880
- "node:url"
23881
- );
24219
+ nodeUrl = loadNodeBuiltin("node:url");
23882
24220
  hasImportedDependencies = true;
23883
24221
  } catch (err) {
23884
24222
  console.warn(
@@ -23925,6 +24263,9 @@ function asNativeWebSocket(handle) {
23925
24263
  function asNativeSqlTransaction(handle) {
23926
24264
  return handle;
23927
24265
  }
24266
+ function asNativeActorStateTransaction(handle) {
24267
+ return handle;
24268
+ }
23928
24269
  function asNativeCancellationToken(handle) {
23929
24270
  return handle;
23930
24271
  }
@@ -24148,6 +24489,9 @@ var NapiCoreRuntime = class {
24148
24489
  actorSetAlarm(ctx, timestampMs) {
24149
24490
  asNativeActorContext(ctx).setAlarm(timestampMs);
24150
24491
  }
24492
+ async actorSetRunWakeAt(ctx, timestampMs) {
24493
+ await asNativeActorContext(ctx).setRunWakeAt(timestampMs);
24494
+ }
24151
24495
  actorRequestSave(ctx, opts) {
24152
24496
  asNativeActorContext(ctx).requestSave(opts);
24153
24497
  }
@@ -24308,9 +24652,10 @@ var NapiCoreRuntime = class {
24308
24652
  );
24309
24653
  return results.map(normalizeRuntimeSqlExecuteResult);
24310
24654
  }
24311
- async actorSqlBeginTransaction(ctx, timeoutMs) {
24655
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
24312
24656
  return await this.#actorSql(ctx).beginTransaction(
24313
- timeoutMs
24657
+ timeoutMs,
24658
+ name
24314
24659
  );
24315
24660
  }
24316
24661
  async actorSqlTransactionExec(transaction, sql) {
@@ -24329,6 +24674,26 @@ var NapiCoreRuntime = class {
24329
24674
  async actorSqlTransactionRollback(transaction) {
24330
24675
  await asNativeSqlTransaction(transaction).rollback();
24331
24676
  }
24677
+ async actorBeginStateTransaction(ctx, timeoutMs) {
24678
+ return await asNativeActorContext(ctx).beginStateTransaction(
24679
+ timeoutMs
24680
+ );
24681
+ }
24682
+ async actorStateTransactionExecute(transaction, sql, params) {
24683
+ const result = await asNativeActorStateTransaction(transaction).execute(
24684
+ sql,
24685
+ toNapiSqlBindParams(params)
24686
+ );
24687
+ return normalizeRuntimeSqlExecuteResult(result);
24688
+ }
24689
+ async actorStateTransactionCommit(transaction, payload) {
24690
+ await asNativeActorStateTransaction(transaction).commit(
24691
+ toNapiStateDeltaPayload(payload)
24692
+ );
24693
+ }
24694
+ async actorStateTransactionRollback(transaction) {
24695
+ await asNativeActorStateTransaction(transaction).rollback();
24696
+ }
24332
24697
  async actorSqlQuery(ctx, sql, params) {
24333
24698
  return await this.#actorSql(ctx).query(
24334
24699
  sql,
@@ -24386,6 +24751,13 @@ var NapiCoreRuntime = class {
24386
24751
  signal ? asNativeCancellationToken(signal) : signal
24387
24752
  );
24388
24753
  }
24754
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
24755
+ return await asNativeActorContext(ctx).queue().completePersisted(
24756
+ messageId,
24757
+ expectedName,
24758
+ response == null ? response : toNapiBuffer(response)
24759
+ );
24760
+ }
24389
24761
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
24390
24762
  return await asNativeActorContext(ctx).queue().enqueueAndWait(
24391
24763
  name,
@@ -24572,6 +24944,164 @@ function validationError(target, issues) {
24572
24944
  metadata: { issues }
24573
24945
  });
24574
24946
  }
24947
+ function runUnavailable(actorId, reason) {
24948
+ return new RivetError(
24949
+ "actor",
24950
+ "run_handler_unavailable",
24951
+ `Run handler control is unavailable for actor ${actorId}: ${reason}.`,
24952
+ {
24953
+ public: true,
24954
+ statusCode: 409,
24955
+ metadata: { actorId, reason }
24956
+ }
24957
+ );
24958
+ }
24959
+ function notifyStateChanged(state) {
24960
+ const waiters = [...state.waiters];
24961
+ state.waiters.clear();
24962
+ for (const waiter of waiters) {
24963
+ waiter();
24964
+ }
24965
+ }
24966
+ function waitForStateChange(state) {
24967
+ return new Promise((resolve) => {
24968
+ state.waiters.add(resolve);
24969
+ });
24970
+ }
24971
+ var RunHandlerCoordinator = class {
24972
+ #run;
24973
+ #states = /* @__PURE__ */ new Map();
24974
+ constructor(run) {
24975
+ this.#run = run;
24976
+ }
24977
+ get inspectorKind() {
24978
+ return getRunInspectorKind(this.#run);
24979
+ }
24980
+ async run(actorId, restart, callback) {
24981
+ const state = this.#getOrCreate(actorId);
24982
+ state.restart = restart;
24983
+ this.#initializeInspector(actorId, state);
24984
+ state.queued += 1;
24985
+ const blockedGeneration = state.exclusive ? state.exclusiveGeneration : void 0;
24986
+ try {
24987
+ while (!state.closed && (state.exclusive || state.active)) {
24988
+ await waitForStateChange(state);
24989
+ }
24990
+ } finally {
24991
+ state.queued -= 1;
24992
+ }
24993
+ if (state.closed) {
24994
+ return "closed";
24995
+ }
24996
+ if (blockedGeneration !== void 0 && state.exclusiveGeneration === blockedGeneration && state.exclusiveOutcome === "failure") {
24997
+ return "suppressed";
24998
+ }
24999
+ state.active = true;
25000
+ try {
25001
+ await callback();
25002
+ return "ran";
25003
+ } finally {
25004
+ state.active = false;
25005
+ notifyStateChanged(state);
25006
+ }
25007
+ }
25008
+ getInspector(actorId, restart) {
25009
+ var _a2;
25010
+ const state = this.#getOrCreate(actorId);
25011
+ state.restart = restart;
25012
+ this.#initializeInspector(actorId, state);
25013
+ return (_a2 = state.inspector) == null ? void 0 : _a2.inspector;
25014
+ }
25015
+ destroy(actorId) {
25016
+ var _a2, _b;
25017
+ const state = this.#states.get(actorId);
25018
+ if (!state) return;
25019
+ state.closed = true;
25020
+ (_b = (_a2 = state.inspector) == null ? void 0 : _a2.dispose) == null ? void 0 : _b.call(_a2);
25021
+ state.inspector = void 0;
25022
+ notifyStateChanged(state);
25023
+ this.#states.delete(actorId);
25024
+ }
25025
+ #control(actorId, state) {
25026
+ return {
25027
+ run: {
25028
+ withInactive: async (options, callback) => {
25029
+ if (state.closed) {
25030
+ throw runUnavailable(actorId, "actor is destroyed");
25031
+ }
25032
+ if (state.active || state.queued > 0 || state.exclusive) {
25033
+ throw runUnavailable(
25034
+ actorId,
25035
+ "the run handler is active or waiting to start"
25036
+ );
25037
+ }
25038
+ state.exclusive = true;
25039
+ state.exclusiveGeneration += 1;
25040
+ state.exclusiveOutcome = void 0;
25041
+ try {
25042
+ const result = await callback();
25043
+ if (state.closed) {
25044
+ throw runUnavailable(actorId, "actor is destroyed");
25045
+ }
25046
+ state.exclusiveOutcome = "success";
25047
+ if (options.restartOnSuccess && state.queued === 0) {
25048
+ if (!state.restart) {
25049
+ throw runUnavailable(
25050
+ actorId,
25051
+ "the runtime restart callback is not available"
25052
+ );
25053
+ }
25054
+ await state.restart();
25055
+ }
25056
+ return result;
25057
+ } catch (error46) {
25058
+ state.exclusiveOutcome = "failure";
25059
+ throw error46;
25060
+ } finally {
25061
+ state.exclusive = false;
25062
+ notifyStateChanged(state);
25063
+ }
25064
+ }
25065
+ }
25066
+ };
25067
+ }
25068
+ #getOrCreate(actorId) {
25069
+ let state = this.#states.get(actorId);
25070
+ if (!state) {
25071
+ state = {
25072
+ active: false,
25073
+ closed: false,
25074
+ exclusive: false,
25075
+ exclusiveGeneration: 0,
25076
+ inspectorInitialized: false,
25077
+ queued: 0,
25078
+ waiters: /* @__PURE__ */ new Set()
25079
+ };
25080
+ this.#states.set(actorId, state);
25081
+ }
25082
+ return state;
25083
+ }
25084
+ #initializeInspector(actorId, state) {
25085
+ if (state.inspectorInitialized) return;
25086
+ const inspector = createRunInspector(this.#run, {
25087
+ actorId,
25088
+ control: this.#control(actorId, state)
25089
+ });
25090
+ if (this.inspectorKind === "workflow") {
25091
+ const workflow = inspector === void 0 ? void 0 : inspector.inspector.workflow;
25092
+ if (!workflow || typeof workflow.getHistory !== "function" || typeof workflow.getState !== "function" || typeof workflow.onHistoryUpdated !== "function" || typeof workflow.replayFromStep !== "function") {
25093
+ throw new TypeError(
25094
+ `defineRunHandler createInspector returned an invalid workflow adapter for actor ${actorId}`
25095
+ );
25096
+ }
25097
+ }
25098
+ state.inspector = inspector;
25099
+ state.inspectorInitialized = true;
25100
+ }
25101
+ };
25102
+ function asWasmConstructors(bindings) {
25103
+ return bindings;
25104
+ }
24575
25105
  function asWasmRegistry(handle) {
24576
25106
  return handle;
24577
25107
  }
@@ -24696,10 +25226,10 @@ function childHandle(handle, name) {
24696
25226
  }
24697
25227
  var WasmCoreRuntime = class {
24698
25228
  kind = "wasm";
24699
- #bindings;
25229
+ #constructors;
24700
25230
  #sql = /* @__PURE__ */ new WeakMap();
24701
25231
  constructor(bindings) {
24702
- this.#bindings = bindings;
25232
+ this.#constructors = asWasmConstructors(bindings);
24703
25233
  }
24704
25234
  #actorSql(ctx) {
24705
25235
  const wasmCtx = asWasmActorContext(ctx);
@@ -24712,7 +25242,7 @@ var WasmCoreRuntime = class {
24712
25242
  }
24713
25243
  createRegistry() {
24714
25244
  return callWasmSync(
24715
- () => asRegistryHandle2(new this.#bindings.CoreRegistry())
25245
+ () => asRegistryHandle2(new this.#constructors.CoreRegistry())
24716
25246
  );
24717
25247
  }
24718
25248
  registerActor(registry2, name, factory) {
@@ -24767,13 +25297,13 @@ var WasmCoreRuntime = class {
24767
25297
  createActorFactory(callbacks, config3) {
24768
25298
  return callWasmSync(
24769
25299
  () => asActorFactoryHandle2(
24770
- new this.#bindings.ActorFactory(callbacks, config3)
25300
+ new this.#constructors.ActorFactory(callbacks, config3)
24771
25301
  )
24772
25302
  );
24773
25303
  }
24774
25304
  createCancellationToken() {
24775
25305
  return callWasmSync(
24776
- () => new this.#bindings.CancellationToken()
25306
+ () => new this.#constructors.CancellationToken()
24777
25307
  );
24778
25308
  }
24779
25309
  cancellationTokenAborted(token) {
@@ -24808,6 +25338,13 @@ var WasmCoreRuntime = class {
24808
25338
  optionalWasmNumber(timestampMs)
24809
25339
  );
24810
25340
  }
25341
+ async actorSetRunWakeAt(ctx, timestampMs) {
25342
+ await callHandleAsync(
25343
+ asWasmActorContext(ctx),
25344
+ "setRunWakeAt",
25345
+ optionalWasmNumber(timestampMs)
25346
+ );
25347
+ }
24811
25348
  actorRequestSave(ctx, opts) {
24812
25349
  callHandle(asWasmActorContext(ctx), "requestSave", opts);
24813
25350
  }
@@ -25022,9 +25559,9 @@ var WasmCoreRuntime = class {
25022
25559
  );
25023
25560
  return results.map(normalizeRuntimeSqlExecuteResult);
25024
25561
  }
25025
- async actorSqlBeginTransaction(ctx, timeoutMs) {
25562
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
25026
25563
  return await callWasm(
25027
- () => this.#actorSql(ctx).beginTransaction(timeoutMs)
25564
+ () => this.#actorSql(ctx).beginTransaction(timeoutMs, name)
25028
25565
  );
25029
25566
  }
25030
25567
  async actorSqlTransactionExec(transaction, sql) {
@@ -25048,6 +25585,27 @@ var WasmCoreRuntime = class {
25048
25585
  () => transaction.rollback()
25049
25586
  );
25050
25587
  }
25588
+ async actorBeginStateTransaction(ctx, timeoutMs) {
25589
+ return await callWasm(
25590
+ () => asWasmActorContext(ctx).beginStateTransaction(timeoutMs)
25591
+ );
25592
+ }
25593
+ async actorStateTransactionExecute(transaction, sql, params) {
25594
+ const result = await callWasm(
25595
+ () => transaction.execute(sql, params)
25596
+ );
25597
+ return normalizeRuntimeSqlExecuteResult(result);
25598
+ }
25599
+ async actorStateTransactionCommit(transaction, payload) {
25600
+ await callWasm(
25601
+ () => transaction.commit(payload)
25602
+ );
25603
+ }
25604
+ async actorStateTransactionRollback(transaction) {
25605
+ await callWasm(
25606
+ () => transaction.rollback()
25607
+ );
25608
+ }
25051
25609
  async actorSqlQuery(ctx, sql, params) {
25052
25610
  return await callWasm(() => this.#actorSql(ctx).query(sql, params));
25053
25611
  }
@@ -25120,6 +25678,16 @@ var WasmCoreRuntime = class {
25120
25678
  signal
25121
25679
  );
25122
25680
  }
25681
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
25682
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
25683
+ return await callHandleAsync(
25684
+ queue2,
25685
+ "completePersisted",
25686
+ messageId,
25687
+ expectedName,
25688
+ response
25689
+ );
25690
+ }
25123
25691
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
25124
25692
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
25125
25693
  return optionalBytes(
@@ -25317,6 +25885,83 @@ function createWriteThroughProxy(value, commit, beforeChange) {
25317
25885
  }
25318
25886
  );
25319
25887
  }
25888
+ function unwrapProxy(value) {
25889
+ let current = value;
25890
+ while (current !== null && typeof current === "object") {
25891
+ const target = source_default.target(current);
25892
+ if (target === current) {
25893
+ break;
25894
+ }
25895
+ current = target;
25896
+ }
25897
+ return current;
25898
+ }
25899
+ function isPlainObject4(value) {
25900
+ const proto = Object.getPrototypeOf(value);
25901
+ return proto === Object.prototype || proto === null;
25902
+ }
25903
+ function unwrapDeep(value, seen) {
25904
+ const unwrapped = unwrapProxy(value);
25905
+ if (!unwrapped || typeof unwrapped !== "object") {
25906
+ return unwrapped;
25907
+ }
25908
+ if (seen.has(unwrapped)) {
25909
+ return unwrapped;
25910
+ }
25911
+ seen.add(unwrapped);
25912
+ if (Array.isArray(unwrapped)) {
25913
+ for (let i = 0; i < unwrapped.length; i++) {
25914
+ const child = unwrapDeep(unwrapped[i], seen);
25915
+ if (child !== unwrapped[i]) {
25916
+ unwrapped[i] = child;
25917
+ }
25918
+ }
25919
+ return unwrapped;
25920
+ }
25921
+ if (unwrapped instanceof Map) {
25922
+ const replacements = [];
25923
+ for (const [key, child] of unwrapped.entries()) {
25924
+ const nextKey = unwrapDeep(key, seen);
25925
+ const nextChild = unwrapDeep(child, seen);
25926
+ if (nextKey !== key || nextChild !== child) {
25927
+ replacements.push([key, nextKey, nextChild]);
25928
+ }
25929
+ }
25930
+ for (const [key, nextKey, nextChild] of replacements) {
25931
+ if (nextKey !== key) {
25932
+ unwrapped.delete(key);
25933
+ }
25934
+ unwrapped.set(nextKey, nextChild);
25935
+ }
25936
+ return unwrapped;
25937
+ }
25938
+ if (unwrapped instanceof Set) {
25939
+ const replacements = [];
25940
+ for (const child of unwrapped.values()) {
25941
+ const next = unwrapDeep(child, seen);
25942
+ if (next !== child) {
25943
+ replacements.push([child, next]);
25944
+ }
25945
+ }
25946
+ for (const [child, next] of replacements) {
25947
+ unwrapped.delete(child);
25948
+ unwrapped.add(next);
25949
+ }
25950
+ return unwrapped;
25951
+ }
25952
+ if (isPlainObject4(unwrapped)) {
25953
+ for (const key of Object.keys(unwrapped)) {
25954
+ const child = unwrapDeep(unwrapped[key], seen);
25955
+ if (child !== unwrapped[key]) {
25956
+ unwrapped[key] = child;
25957
+ }
25958
+ }
25959
+ }
25960
+ return unwrapped;
25961
+ }
25962
+ function unwrapWriteThroughProxy(value) {
25963
+ return unwrapDeep(value, /* @__PURE__ */ new Set());
25964
+ }
25320
25965
  var textEncoder = new TextEncoder();
25321
25966
  var textDecoder = new TextDecoder();
25322
25967
  var defaultRuntimeLoaders = {
@@ -25461,6 +26106,14 @@ function stateMutationReentrantError() {
25461
26106
  "State mutations are not allowed inside onStateChange."
25462
26107
  );
25463
26108
  }
26109
+ function stateTransactionConflictError() {
26110
+ return new RivetError(
26111
+ "actor",
26112
+ "state_transaction_conflict",
26113
+ "State cannot be mutated by another action while an experimental state-aware database transaction is active.",
26114
+ { public: true, statusCode: 409 }
26115
+ );
26116
+ }
25464
26117
  function databaseNotConfiguredError() {
25465
26118
  return new RivetError(
25466
26119
  "actor",
@@ -25477,6 +26130,14 @@ function databaseClientNotReadyError() {
25477
26130
  { public: true }
25478
26131
  );
25479
26132
  }
26133
+ function runHandlerNotConfiguredError() {
26134
+ return new RivetError(
26135
+ "actor",
26136
+ "run_handler_unavailable",
26137
+ "Cannot schedule a run wake because this actor does not define a run handler.",
26138
+ { public: true, statusCode: 409 }
26139
+ );
26140
+ }
25480
26141
  function stateNotEnabledError() {
25481
26142
  return new RivetError(
25482
26143
  "actor",
@@ -25579,10 +26240,11 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
25579
26240
  exec: (sql) => runtime.actorSqlExec(ctx, sql),
25580
26241
  execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
25581
26242
  executeBatch: (statements) => runtime.actorSqlExecuteBatch(ctx, statements),
25582
- beginTransaction: async (timeoutMs) => {
26243
+ beginTransaction: async (timeoutMs, name) => {
25583
26244
  const transaction = await runtime.actorSqlBeginTransaction(
25584
26245
  ctx,
25585
- timeoutMs
26246
+ timeoutMs,
26247
+ name
25586
26248
  );
25587
26249
  return {
25588
26250
  exec: (sql) => runtime.actorSqlTransactionExec(transaction, sql),
@@ -25595,6 +26257,38 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
25595
26257
  rollback: () => runtime.actorSqlTransactionRollback(transaction)
25596
26258
  };
25597
26259
  },
26260
+ beginStateTransaction: async (timeoutMs, context) => {
26261
+ const scope = context;
26262
+ if (!scope) {
26263
+ throw new Error(
26264
+ "actor state transaction context is not configured"
26265
+ );
26266
+ }
26267
+ const transaction = await runtime.actorBeginStateTransaction(
26268
+ ctx,
26269
+ timeoutMs
26270
+ );
26271
+ return {
26272
+ exec: async () => {
26273
+ throw new Error(
26274
+ "actor state transactions only support single-statement execute calls"
26275
+ );
26276
+ },
26277
+ execute: (sql, params) => runtime.actorStateTransactionExecute(
26278
+ transaction,
26279
+ sql,
26280
+ params
26281
+ ),
26282
+ commit: async () => {
26283
+ await runtime.actorStateTransactionCommit(
26284
+ transaction,
26285
+ scope.actorContext.serializeForTick("save")
26286
+ );
26287
+ scope.committed = true;
26288
+ },
26289
+ rollback: () => runtime.actorStateTransactionRollback(transaction)
26290
+ };
26291
+ },
25598
26292
  query: (sql, params) => runtime.actorSqlQuery(ctx, sql, params),
25599
26293
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
25600
26294
  metrics: () => runtime.actorSqlMetrics(ctx),
@@ -25975,12 +26669,16 @@ var NativeConnAdapter = class {
25975
26669
  #schemas;
25976
26670
  #ctx;
25977
26671
  #queueHibernationRemoval;
25978
- constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval) {
26672
+ #assertCanMutateState;
26673
+ #stateProxy;
26674
+ #stateProxyTarget;
26675
+ constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval, assertCanMutateState) {
25979
26676
  this.#runtime = runtime;
25980
26677
  this.#conn = conn;
25981
26678
  this.#schemas = schemas;
25982
26679
  this.#ctx = ctx;
25983
26680
  this.#queueHibernationRemoval = queueHibernationRemoval;
26681
+ this.#assertCanMutateState = assertCanMutateState;
25984
26682
  this[CONN_STATE_MANAGER_SYMBOL] = {
25985
26683
  stateEnabled: true,
25986
26684
  get state() {
@@ -26003,22 +26701,46 @@ var NativeConnAdapter = class {
26003
26701
  }
26004
26702
  get state() {
26005
26703
  const nextState = this.#readState();
26704
+ if (!this.#ctx) {
26705
+ return this.#createStateProxy(nextState);
26706
+ }
26707
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
26708
+ this.#stateProxyTarget = nextState;
26709
+ this.#stateProxy = this.#createStateProxy(nextState);
26710
+ }
26711
+ return this.#stateProxy;
26712
+ }
26713
+ #createStateProxy(state) {
26714
+ const assertCurrentState = () => {
26715
+ var _a2;
26716
+ (_a2 = this.#assertCanMutateState) == null ? void 0 : _a2.call(this);
26717
+ if (this.#ctx && this.#readState() !== state) {
26718
+ throw stateTransactionConflictError();
26719
+ }
26720
+ };
26006
26721
  return createWriteThroughProxy(
26007
- nextState,
26722
+ state,
26008
26723
  (nextValue) => {
26724
+ assertCurrentState();
26009
26725
  this.#writeState(nextValue, { writeNative: true });
26010
26726
  },
26011
26727
  (newValue) => {
26728
+ assertCurrentState();
26012
26729
  assertJsonCompatValue(newValue);
26013
26730
  }
26014
26731
  );
26015
26732
  }
26016
26733
  set state(value) {
26017
- assertJsonCompatValue(value);
26018
- this.#writeState(value, { writeNative: true });
26734
+ var _a2;
26735
+ (_a2 = this.#assertCanMutateState) == null ? void 0 : _a2.call(this);
26736
+ const nextValue = unwrapWriteThroughProxy(value);
26737
+ assertJsonCompatValue(nextValue);
26738
+ this.#writeState(nextValue, { writeNative: true });
26019
26739
  }
26020
26740
  initializeState(value) {
26021
- this.#writeState(value, { writeNative: false });
26741
+ this.#writeState(unwrapWriteThroughProxy(value), {
26742
+ writeNative: false
26743
+ });
26022
26744
  }
26023
26745
  get isHibernatable() {
26024
26746
  return callNativeSync(
@@ -26336,8 +27058,9 @@ var NativeKvAdapter = class {
26336
27058
  };
26337
27059
  function wrapQueueMessage(message, schemas) {
26338
27060
  const name = callNativeSync(() => message.name());
27061
+ const id = callNativeSync(() => message.id());
26339
27062
  return {
26340
- id: Number(callNativeSync(() => message.id())),
27063
+ id: id <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(id) : id,
26341
27064
  name,
26342
27065
  body: validateQueueBody(
26343
27066
  schemas,
@@ -26475,6 +27198,25 @@ var NativeQueueAdapter = class {
26475
27198
  cleanup == null ? void 0 : cleanup();
26476
27199
  }
26477
27200
  }
27201
+ async waitForAvailable(names, options) {
27202
+ await this.waitForNamesAvailable(names ?? [], options);
27203
+ }
27204
+ async complete(message, response) {
27205
+ const validatedResponse = validateQueueComplete(
27206
+ this.#schemas,
27207
+ message.name,
27208
+ response
27209
+ );
27210
+ await callNative(
27211
+ () => this.#runtime.actorQueueCompletePersisted(
27212
+ this.#ctx,
27213
+ BigInt(message.id),
27214
+ message.name,
27215
+ encodeValue(validatedResponse)
27216
+ )
27217
+ );
27218
+ this.#pendingCompletableMessageIds.delete(message.id.toString());
27219
+ }
26478
27220
  async enqueueAndWait(name, body, options) {
26479
27221
  const validatedBody = validateQueueBody(this.#schemas, name, body);
26480
27222
  const { token, cleanup } = await createCancellationTokenHandle(
@@ -26911,10 +27653,12 @@ var NativeConnectionMap = class {
26911
27653
  #runtime;
26912
27654
  #ctx;
26913
27655
  #schemas;
26914
- constructor(runtime, ctx, schemas) {
27656
+ #assertCanMutateState;
27657
+ constructor(runtime, ctx, schemas, assertCanMutateState) {
26915
27658
  this.#runtime = runtime;
26916
27659
  this.#ctx = ctx;
26917
27660
  this.#schemas = schemas;
27661
+ this.#assertCanMutateState = assertCanMutateState;
26918
27662
  }
26919
27663
  #connToAdapter(conn) {
26920
27664
  return new NativeConnAdapter(
@@ -26927,7 +27671,8 @@ var NativeConnectionMap = class {
26927
27671
  this.#ctx,
26928
27672
  connId
26929
27673
  )
26930
- )
27674
+ ),
27675
+ this.#assertCanMutateState
26931
27676
  );
26932
27677
  }
26933
27678
  get size() {
@@ -26986,17 +27731,20 @@ var ActorContextHandleAdapter = class {
26986
27731
  #queue;
26987
27732
  #request;
26988
27733
  #schedule;
26989
- #sql;
26990
- #runHandlerActiveProvider;
27734
+ #run;
27735
+ #runHandlerConfigured;
26991
27736
  #onStateChange;
26992
27737
  #stateEnabled;
26993
- constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, runHandlerActiveProvider, onStateChange, dispatchCancelToken) {
27738
+ #stateProxy;
27739
+ #stateProxyTarget;
27740
+ #stateTransactionOwner = /* @__PURE__ */ Symbol("actor-state-transaction-owner");
27741
+ constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
26994
27742
  this.#runtime = runtime;
26995
27743
  this.#ctx = ctx;
26996
27744
  this.#clientFactory = clientFactory;
26997
27745
  this.#schemas = schemas;
26998
27746
  this.#dispatchCancelToken = dispatchCancelToken;
26999
- this.#runHandlerActiveProvider = runHandlerActiveProvider;
27747
+ this.#runHandlerConfigured = runHandlerConfigured;
27000
27748
  this.#onStateChange = onStateChange;
27001
27749
  this.#stateEnabled = stateEnabled;
27002
27750
  if (databaseProvider) {
@@ -27013,12 +27761,6 @@ var ActorContextHandleAdapter = class {
27013
27761
  }
27014
27762
  return this.#kv;
27015
27763
  }
27016
- get sql() {
27017
- if (!this.#sql) {
27018
- this.#sql = getOrCreateNativeSqlDatabase(this.#runtime, this.#ctx);
27019
- }
27020
- return this.#sql;
27021
- }
27022
27764
  async actorRuntimeSocket() {
27023
27765
  return await callNative(
27024
27766
  () => this.#runtime.actorRuntimeSocketProvision(this.#ctx)
@@ -27034,7 +27776,7 @@ var ActorContextHandleAdapter = class {
27034
27776
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
27035
27777
  const cachedClient = runtimeState.databaseClient;
27036
27778
  if (cachedClient) {
27037
- this.#db = cachedClient.client;
27779
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
27038
27780
  return this.#db;
27039
27781
  }
27040
27782
  throw databaseClientNotReadyError();
@@ -27049,36 +27791,45 @@ var ActorContextHandleAdapter = class {
27049
27791
  if (!this.#stateEnabled) {
27050
27792
  throw stateNotEnabledError();
27051
27793
  }
27052
- const actorState = getNativePersistState(this.#runtime, this.#ctx);
27053
27794
  const nextState = this.#readState();
27054
- if (actorState.stateProxy === void 0 || actorState.stateProxyTarget !== nextState) {
27055
- actorState.stateProxyTarget = nextState;
27056
- actorState.stateProxy = createWriteThroughProxy(
27795
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
27796
+ const assertCurrentState = () => {
27797
+ this.#assertCanMutateState();
27798
+ if (this.#readState() !== nextState) {
27799
+ throw stateTransactionConflictError();
27800
+ }
27801
+ };
27802
+ this.#stateProxyTarget = nextState;
27803
+ this.#stateProxy = createWriteThroughProxy(
27057
27804
  nextState,
27058
27805
  (nextValue) => {
27806
+ assertCurrentState();
27059
27807
  this.#writeState(nextValue, { scheduleSave: true });
27060
27808
  },
27061
27809
  (newValue) => {
27062
- this.#assertCanMutateState();
27810
+ assertCurrentState();
27063
27811
  assertJsonCompatValue(newValue);
27064
27812
  }
27065
27813
  );
27066
27814
  }
27067
- return actorState.stateProxy;
27815
+ return this.#stateProxy;
27068
27816
  }
27069
27817
  set state(value) {
27070
27818
  if (!this.#stateEnabled) {
27071
27819
  throw stateNotEnabledError();
27072
27820
  }
27073
27821
  this.#assertCanMutateState();
27074
- assertJsonCompatValue(value);
27075
- this.#writeState(value, { scheduleSave: true });
27822
+ const nextValue = unwrapWriteThroughProxy(value);
27823
+ assertJsonCompatValue(nextValue);
27824
+ this.#writeState(nextValue, { scheduleSave: true });
27076
27825
  }
27077
27826
  initializeState(value) {
27078
27827
  if (!this.#stateEnabled) {
27079
27828
  return;
27080
27829
  }
27081
- this.#writeState(value, { scheduleSave: false });
27830
+ this.#writeState(unwrapWriteThroughProxy(value), {
27831
+ scheduleSave: false
27832
+ });
27082
27833
  }
27083
27834
  get vars() {
27084
27835
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
@@ -27104,6 +27855,26 @@ var ActorContextHandleAdapter = class {
27104
27855
  }
27105
27856
  return this.#queue;
27106
27857
  }
27858
+ get run() {
27859
+ if (!this.#run) {
27860
+ this.#run = {
27861
+ setWakeAt: async (timestamp) => {
27862
+ if (timestamp !== null && !this.#runHandlerConfigured) {
27863
+ throw runHandlerNotConfiguredError();
27864
+ }
27865
+ if (timestamp !== null && (!Number.isSafeInteger(timestamp) || timestamp < 0)) {
27866
+ throw new TypeError(
27867
+ "Run wake timestamp must be a non-negative safe integer or null"
27868
+ );
27869
+ }
27870
+ await callNative(
27871
+ () => this.#runtime.actorSetRunWakeAt(this.#ctx, timestamp)
27872
+ );
27873
+ }
27874
+ };
27875
+ }
27876
+ return this.#run;
27877
+ }
27107
27878
  get schedule() {
27108
27879
  if (!this.#schedule) {
27109
27880
  this.#schedule = new NativeScheduleAdapter(
@@ -27138,7 +27909,8 @@ var ActorContextHandleAdapter = class {
27138
27909
  this.#connMap = new NativeConnectionMap(
27139
27910
  this.#runtime,
27140
27911
  this.#ctx,
27141
- this.#schemas
27912
+ this.#schemas,
27913
+ () => this.#assertCanMutateState()
27142
27914
  );
27143
27915
  }
27144
27916
  return this.#connMap;
@@ -27207,11 +27979,11 @@ var ActorContextHandleAdapter = class {
27207
27979
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
27208
27980
  const cachedClient = runtimeState.databaseClient;
27209
27981
  if (cachedClient) {
27210
- this.#db = cachedClient.client;
27982
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
27211
27983
  return this.#db;
27212
27984
  }
27213
27985
  const actorId = this.actorId;
27214
- const client = await this.#databaseProvider.createClient({
27986
+ const createdClient = await this.#databaseProvider.createClient({
27215
27987
  actorId,
27216
27988
  kv: {
27217
27989
  batchPut: async (entries) => {
@@ -27232,21 +28004,126 @@ var ActorContextHandleAdapter = class {
27232
28004
  log: {
27233
28005
  debug: (obj) => logger22().debug(obj)
27234
28006
  },
27235
- nativeDatabaseProvider: {
27236
- open: async (requestedActorId) => {
27237
- void requestedActorId;
27238
- return getOrCreateNativeSqlDatabase(
27239
- this.#runtime,
27240
- this.#ctx
27241
- );
27242
- }
27243
- }
28007
+ nativeDatabaseProvider: registerNativeStateTransactionOpener(
28008
+ {
28009
+ open: async (requestedActorId) => {
28010
+ void requestedActorId;
28011
+ return getOrCreateNativeSqlDatabase(
28012
+ this.#runtime,
28013
+ this.#ctx
28014
+ );
28015
+ }
28016
+ },
28017
+ async (timeoutMs, context) => await getOrCreateNativeSqlDatabase(
28018
+ this.#runtime,
28019
+ this.#ctx
28020
+ ).beginStateTransaction(timeoutMs, context)
28021
+ )
27244
28022
  });
27245
28023
  runtimeState.databaseClient = {
27246
- client
28024
+ client: createdClient
27247
28025
  };
27248
- this.#db = client;
27249
- return client;
28026
+ this.#db = this.#bindDatabaseClient(createdClient);
28027
+ return this.#db;
28028
+ }
28029
+ #bindDatabaseClient(client) {
28030
+ return bindNativeStateTransactionContext(client, {
28031
+ enter: async () => await this.#enterStateTransaction(),
28032
+ exit: (scope) => this.#exitStateTransaction(
28033
+ scope
28034
+ )
28035
+ });
28036
+ }
28037
+ async #enterStateTransaction() {
28038
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
28039
+ let pendingOwners = actorState.pendingStateTransactionOwners;
28040
+ if (!pendingOwners) {
28041
+ pendingOwners = /* @__PURE__ */ new Set();
28042
+ actorState.pendingStateTransactionOwners = pendingOwners;
28043
+ }
28044
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner || pendingOwners.has(this.#stateTransactionOwner)) {
28045
+ throw stateTransactionConflictError();
28046
+ }
28047
+ pendingOwners.add(this.#stateTransactionOwner);
28048
+ const predecessor = actorState.stateTransactionTail ?? Promise.resolve();
28049
+ let release;
28050
+ const hold = new Promise((resolve) => {
28051
+ release = resolve;
28052
+ });
28053
+ actorState.stateTransactionTail = predecessor.then(
28054
+ async () => await hold
28055
+ );
28056
+ try {
28057
+ await predecessor;
28058
+ pendingOwners.delete(this.#stateTransactionOwner);
28059
+ actorState.activeStateTransactionOwner = this.#stateTransactionOwner;
28060
+ return {
28061
+ actorContext: this,
28062
+ actorStateBaseline: this.#stateEnabled ? structuredClone(this.#readState()) : void 0,
28063
+ connectionStateBaselines: new Map(
28064
+ callNativeSync(
28065
+ () => this.#runtime.actorConns(this.#ctx)
28066
+ ).map((conn) => [
28067
+ callNativeSync(() => this.#runtime.connId(conn)),
28068
+ new Uint8Array(
28069
+ callNativeSync(() => this.#runtime.connState(conn))
28070
+ )
28071
+ ])
28072
+ ),
28073
+ committed: false,
28074
+ release
28075
+ };
28076
+ } catch (error46) {
28077
+ pendingOwners.delete(this.#stateTransactionOwner);
28078
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
28079
+ actorState.activeStateTransactionOwner = void 0;
28080
+ }
28081
+ release();
28082
+ throw error46;
28083
+ }
28084
+ }
28085
+ #exitStateTransaction(scope) {
28086
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
28087
+ try {
28088
+ if (!scope.committed) {
28089
+ this.#restoreStateTransactionBaseline(scope);
28090
+ }
28091
+ } finally {
28092
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
28093
+ actorState.activeStateTransactionOwner = void 0;
28094
+ }
28095
+ if (actorState.stateTransactionSaveDeferred) {
28096
+ actorState.stateTransactionSaveDeferred = false;
28097
+ this.#scheduleSave();
28098
+ }
28099
+ scope.release();
28100
+ }
28101
+ }
28102
+ #restoreStateTransactionBaseline(scope) {
28103
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
28104
+ if (actorState.pendingSaveHandle !== void 0) {
28105
+ clearImmediate(actorState.pendingSaveHandle);
28106
+ }
28107
+ actorState.pendingSaveHandle = void 0;
28108
+ actorState.saveScheduled = false;
28109
+ if (this.#stateEnabled) {
28110
+ actorState.state = structuredClone(scope.actorStateBaseline);
28111
+ }
28112
+ for (const conn of callNativeSync(
28113
+ () => this.#runtime.actorConns(this.#ctx)
28114
+ )) {
28115
+ const connId = callNativeSync(() => this.#runtime.connId(conn));
28116
+ const baseline = scope.connectionStateBaselines.get(connId);
28117
+ if (baseline === void 0) {
28118
+ continue;
28119
+ }
28120
+ callNativeSync(() => this.#runtime.connSetState(conn, baseline));
28121
+ const cached2 = actorState.connStates.get(connId);
28122
+ if (cached2) {
28123
+ cached2.state = decodeValue(baseline);
28124
+ }
28125
+ }
28126
+ this.#scheduleSave();
27250
28127
  }
27251
28128
  async prepare() {
27252
28129
  if (!this.#databaseProvider) {
@@ -27264,7 +28141,6 @@ var ActorContextHandleAdapter = class {
27264
28141
  }
27265
28142
  async closeDatabase() {
27266
28143
  this.#db = void 0;
27267
- this.#sql = void 0;
27268
28144
  await closeNativeDatabaseClient(this.#runtime, this.#ctx);
27269
28145
  await closeNativeSqlDatabase(this.#runtime, this.#ctx);
27270
28146
  }
@@ -27284,6 +28160,7 @@ var ActorContextHandleAdapter = class {
27284
28160
  }
27285
28161
  async saveState(opts) {
27286
28162
  if (opts == null ? void 0 : opts.immediate) {
28163
+ this.#assertCanAwaitStateSave();
27287
28164
  await callNative(
27288
28165
  () => this.#runtime.actorRequestSaveAndWait(this.#ctx, {
27289
28166
  immediate: true
@@ -27304,10 +28181,17 @@ var ActorContextHandleAdapter = class {
27304
28181
  );
27305
28182
  }
27306
28183
  async saveStateAndWorkflowBatch(writes) {
28184
+ this.#assertCanAwaitStateSave();
27307
28185
  await callNative(
27308
28186
  () => this.#runtime.actorSaveStateAndWorkflowBatch(this.#ctx, writes)
27309
28187
  );
27310
28188
  }
28189
+ #assertCanAwaitStateSave() {
28190
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
28191
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
28192
+ throw stateTransactionConflictError();
28193
+ }
28194
+ }
27311
28195
  serializeForTick(reason) {
27312
28196
  void reason;
27313
28197
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -27361,10 +28245,6 @@ var ActorContextHandleAdapter = class {
27361
28245
  }
27362
28246
  return promise2;
27363
28247
  }
27364
- runHandlerActive() {
27365
- var _a2;
27366
- return ((_a2 = this.#runHandlerActiveProvider) == null ? void 0 : _a2.call(this)) ?? false;
27367
- }
27368
28248
  internalKeepAwake(run) {
27369
28249
  const promise2 = typeof run === "function" ? run() : run;
27370
28250
  const trackedPromise = promise2.then(
@@ -27446,7 +28326,6 @@ var ActorContextHandleAdapter = class {
27446
28326
  var _a2;
27447
28327
  this.#flushStateChange();
27448
28328
  (_a2 = this.#abortSignalCleanup) == null ? void 0 : _a2.call(this);
27449
- this.#sql = void 0;
27450
28329
  }
27451
28330
  #createActorAbortSignal() {
27452
28331
  const nativeSignal = callNativeSync(
@@ -27480,10 +28359,18 @@ var ActorContextHandleAdapter = class {
27480
28359
  this.#scheduleSave();
27481
28360
  }
27482
28361
  #assertCanMutateState() {
28362
+ var _a2;
27483
28363
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
27484
28364
  if (actorState.isInOnStateChange) {
27485
28365
  throw stateMutationReentrantError();
27486
28366
  }
28367
+ if (actorState.activeStateTransactionOwner !== this.#stateTransactionOwner && (actorState.activeStateTransactionOwner !== void 0 || (((_a2 = actorState.pendingStateTransactionOwners) == null ? void 0 : _a2.size) ?? 0) > 0)) {
28368
+ throw stateTransactionConflictError();
28369
+ }
28370
+ }
28371
+ /** @internal */
28372
+ assertCanMutateState() {
28373
+ this.#assertCanMutateState();
27487
28374
  }
27488
28375
  // Coalesce the request-save and onStateChange work to once per event loop
27489
28376
  // tick. A synchronous burst of mutations (for example
@@ -27505,6 +28392,15 @@ var ActorContextHandleAdapter = class {
27505
28392
  if (!actorState.saveScheduled) {
27506
28393
  return;
27507
28394
  }
28395
+ if (actorState.activeStateTransactionOwner !== void 0) {
28396
+ actorState.saveScheduled = false;
28397
+ if (actorState.pendingSaveHandle !== void 0) {
28398
+ clearImmediate(actorState.pendingSaveHandle);
28399
+ actorState.pendingSaveHandle = void 0;
28400
+ }
28401
+ actorState.stateTransactionSaveDeferred = true;
28402
+ return;
28403
+ }
27508
28404
  actorState.saveScheduled = false;
27509
28405
  if (actorState.pendingSaveHandle !== void 0) {
27510
28406
  clearImmediate(actorState.pendingSaveHandle);
@@ -27628,9 +28524,6 @@ var NativeWorkflowRuntimeAdapter = class {
27628
28524
  }
27629
28525
  };
27630
28526
  }
27631
- isRunHandlerActive() {
27632
- return this.#ctx.runHandlerActive();
27633
- }
27634
28527
  async restartRunHandler() {
27635
28528
  await this.#ctx.restartRunHandler();
27636
28529
  }
@@ -27663,43 +28556,45 @@ var NativeWorkflowRuntimeAdapter = class {
27663
28556
  };
27664
28557
  }
27665
28558
  };
27666
- function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken) {
27667
- return Object.assign(
27668
- new ActorContextHandleAdapter(
28559
+ function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
28560
+ const actorContext = new ActorContextHandleAdapter(
28561
+ runtime,
28562
+ ctx,
28563
+ clientFactory,
28564
+ schemas,
28565
+ databaseProvider,
28566
+ request,
28567
+ stateEnabled,
28568
+ onStateChange,
28569
+ dispatchCancelToken,
28570
+ runHandlerConfigured
28571
+ );
28572
+ return Object.assign(actorContext, {
28573
+ conn: new NativeConnAdapter(
27669
28574
  runtime,
27670
- ctx,
27671
- clientFactory,
28575
+ conn,
27672
28576
  schemas,
27673
- databaseProvider,
27674
- request,
27675
- stateEnabled,
27676
- void 0,
27677
- onStateChange,
27678
- dispatchCancelToken
27679
- ),
27680
- {
27681
- conn: new NativeConnAdapter(
27682
- runtime,
27683
- conn,
27684
- schemas,
27685
- ctx,
27686
- (connId) => callNativeSync(
27687
- () => runtime.actorQueueHibernationRemoval(ctx, connId)
27688
- )
27689
- )
27690
- }
27691
- );
28577
+ ctx,
28578
+ (connId) => callNativeSync(
28579
+ () => runtime.actorQueueHibernationRemoval(ctx, connId)
28580
+ ),
28581
+ () => actorContext.assertCanMutateState()
28582
+ )
28583
+ });
27692
28584
  }
27693
28585
  function buildActorConfig(definition, registryConfig, runtimeKind) {
28586
+ var _a2;
27694
28587
  const config3 = definition.config;
27695
28588
  const options = config3.options ?? {};
27696
28589
  const canHibernate = options.canHibernateWebSocket;
27697
28590
  const usesRemoteSqlite = sqliteBackendForConfig(registryConfig) === "remote";
28591
+ const sqliteProfiling = (_a2 = config3.db) == null ? void 0 : _a2.sqliteProfiling;
27698
28592
  return {
27699
28593
  name: options.name,
27700
28594
  icon: options.icon,
27701
- hasDatabase: config3.db !== void 0 || usesRemoteSqlite,
28595
+ hasDatabase: true,
27702
28596
  remoteSqlite: usesRemoteSqlite,
28597
+ sqliteProfiling,
27703
28598
  enableActorRuntimeSocket: options.enableActorRuntimeSocket === true,
27704
28599
  hasState: config3.state !== void 0 || typeof config3.createState === "function",
27705
28600
  canHibernateWebsocket: typeof canHibernate === "boolean" ? canHibernate : void 0,
@@ -27798,7 +28693,7 @@ function validateInspectorTabSource(tabId, resolved) {
27798
28693
  function buildNativeFactory(runtime, registryConfig, definition) {
27799
28694
  var _a2;
27800
28695
  const config3 = definition.config;
27801
- const databaseProvider = config3.db;
28696
+ const databaseProvider = config3.db ?? db();
27802
28697
  const actionHandlers = flattenActionHandlers(config3.actions);
27803
28698
  const schemaConfig = {
27804
28699
  actionInputSchemas: flattenActionInputSchemas(
@@ -27815,16 +28710,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27815
28710
  ),
27816
28711
  { encoding: "bare" }
27817
28712
  );
27818
- const nativeRunHandlerActiveByActorId = /* @__PURE__ */ new Map();
27819
- const isNativeRunHandlerActive = (ctx) => nativeRunHandlerActiveByActorId.get(
27820
- callNativeSync(() => runtime.actorId(ctx))
27821
- ) ?? false;
28713
+ const run = getRunFunction(config3.run);
28714
+ const runHandlerCoordinator = getRunInspectorKind(config3.run) === "workflow" ? new RunHandlerCoordinator(config3.run) : void 0;
27822
28715
  const getNativeWorkflowInspector = (ctx) => {
27823
- var _a22;
27824
- return (_a22 = getRunInspectorConfig(
27825
- config3.run,
27826
- callNativeSync(() => runtime.actorId(ctx))
27827
- )) == null ? void 0 : _a22.workflow;
28716
+ var _a22, _b;
28717
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
28718
+ const restart = () => callNativeSync(() => runtime.actorRestartRunHandler(ctx));
28719
+ return ((_a22 = runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.getInspector(actorId, restart)) == null ? void 0 : _a22.workflow) ?? ((_b = getRunInspectorConfig(config3.run, actorId)) == null ? void 0 : _b.workflow);
27828
28720
  };
27829
28721
  const onStateChange = typeof config3.onStateChange === "function" ? (actorCtx, nextState) => {
27830
28722
  config3.onStateChange(actorCtx, nextState);
@@ -27844,9 +28736,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27844
28736
  databaseProvider,
27845
28737
  request,
27846
28738
  stateEnabled,
27847
- () => isNativeRunHandlerActive(ctx),
27848
28739
  onStateChange,
27849
- cancelToken
28740
+ cancelToken,
28741
+ run !== void 0
27850
28742
  );
27851
28743
  const makeConnCtx = (ctx, conn, request, cancelToken) => withConnContext(
27852
28744
  runtime,
@@ -27858,7 +28750,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27858
28750
  request,
27859
28751
  stateEnabled,
27860
28752
  onStateChange,
27861
- cancelToken
28753
+ cancelToken,
28754
+ run !== void 0
27862
28755
  );
27863
28756
  const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
27864
28757
  var _a22, _b, _c, _d;
@@ -27909,6 +28802,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27909
28802
  return await ((_b2 = (_a3 = getNativeWorkflowInspector(ctx)) == null ? void 0 : _a3.getState) == null ? void 0 : _b2.call(_a3)) ?? null;
27910
28803
  };
27911
28804
  const actorCtx = makeActorCtx(ctx, jsRequest);
28805
+ const sql = getOrCreateNativeSqlDatabase(runtime, ctx);
27912
28806
  try {
27913
28807
  if (url2.pathname === "/inspector/state" && jsRequest.method === "GET") {
27914
28808
  return jsonResponse({
@@ -28036,9 +28930,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28036
28930
  }
28037
28931
  }
28038
28932
  if (url2.pathname === "/inspector/database/schema" && jsRequest.method === "GET") {
28039
- const db = actorCtx.sql;
28933
+ const db2 = sql;
28040
28934
  const tables = queryRows(
28041
- await db.query(
28935
+ await db2.query(
28042
28936
  "SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '__drizzle_%' ORDER BY name"
28043
28937
  )
28044
28938
  );
@@ -28046,13 +28940,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28046
28940
  for (const table of tables) {
28047
28941
  const quoted = `"${table.name.replace(/"/g, '""')}"`;
28048
28942
  const columns = queryRows(
28049
- await db.query(`PRAGMA table_info(${quoted})`)
28943
+ await db2.query(`PRAGMA table_info(${quoted})`)
28050
28944
  );
28051
28945
  const foreignKeys = queryRows(
28052
- await db.query(`PRAGMA foreign_key_list(${quoted})`)
28946
+ await db2.query(`PRAGMA foreign_key_list(${quoted})`)
28053
28947
  );
28054
28948
  const countResult = queryRows(
28055
- await db.query(
28949
+ await db2.query(
28056
28950
  `SELECT COUNT(*) as count FROM ${quoted}`
28057
28951
  )
28058
28952
  );
@@ -28087,7 +28981,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28087
28981
  );
28088
28982
  const quoted = `"${table.replace(/"/g, '""')}"`;
28089
28983
  const rows = queryRows(
28090
- await actorCtx.sql.query(
28984
+ await sql.query(
28091
28985
  `SELECT * FROM ${quoted} LIMIT ? OFFSET ?`,
28092
28986
  [
28093
28987
  Math.max(0, Math.min(limit, 500)),
@@ -28115,15 +29009,11 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28115
29009
  const bindings = normalizeSqlitePropertyBindings(
28116
29010
  body.properties
28117
29011
  );
28118
- const rows2 = queryRows(
28119
- await actorCtx.sql.query(body.sql, bindings)
28120
- );
29012
+ const rows2 = queryRows(await sql.query(body.sql, bindings));
28121
29013
  return jsonResponse({ rows: jsonSafe(rows2) });
28122
29014
  }
28123
29015
  const args = Array.isArray(body.args) ? body.args : [];
28124
- const rows = queryRows(
28125
- await actorCtx.sql.query(body.sql, args)
28126
- );
29016
+ const rows = queryRows(await sql.query(body.sql, args));
28127
29017
  return jsonResponse({ rows: jsonSafe(rows) });
28128
29018
  }
28129
29019
  if (url2.pathname === "/inspector/summary" && jsRequest.method === "GET") {
@@ -28149,7 +29039,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28149
29039
  rpcs: Object.keys(actionHandlers).sort(),
28150
29040
  queueSize: inspectorSnapshot.queueSize,
28151
29041
  isStateEnabled: stateEnabled,
28152
- isDatabaseEnabled: databaseProvider !== void 0,
29042
+ isDatabaseEnabled: true,
28153
29043
  isWorkflowEnabled: getNativeWorkflowInspector(ctx) !== void 0,
28154
29044
  workflowState: await workflowState(),
28155
29045
  workflowHistory: workflowHistory()
@@ -28339,6 +29229,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28339
29229
  async (error46, payload) => {
28340
29230
  const { ctx } = unwrapTsfnPayload(error46, payload);
28341
29231
  const actorCtx = makeActorCtx(ctx);
29232
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
28342
29233
  const saveActorState = async () => {
28343
29234
  if (runtime.kind === "wasm") {
28344
29235
  await runtime.actorSaveState(
@@ -28364,6 +29255,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28364
29255
  saveActorState
28365
29256
  );
28366
29257
  } finally {
29258
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
29259
+ disposeRunInspector(config3.run, actorId);
28367
29260
  await actorCtx.dispose();
28368
29261
  }
28369
29262
  }
@@ -28373,14 +29266,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28373
29266
  async (error46, payload) => {
28374
29267
  const { ctx } = unwrapTsfnPayload(error46, payload);
28375
29268
  const actorCtx = makeActorCtx(ctx);
29269
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
29270
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
29271
+ disposeRunInspector(config3.run, actorId);
28376
29272
  try {
28377
29273
  if (typeof config3.onDestroy === "function") {
28378
29274
  await config3.onDestroy(actorCtx);
28379
29275
  }
28380
29276
  } finally {
28381
- const actorId = callNativeSync(() => runtime.actorId(ctx));
28382
- nativeRunHandlerActiveByActorId.delete(actorId);
28383
- disposeRunInspector(config3.run, actorId);
28384
29277
  resolveNativeDestroy(runtime, ctx);
28385
29278
  await actorCtx.closeDatabase();
28386
29279
  clearNativeRuntimeState(runtime, ctx);
@@ -28428,7 +29321,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28428
29321
  ctx,
28429
29322
  connId
28430
29323
  )
28431
- )
29324
+ ),
29325
+ () => actorCtx.assertCanMutateState()
28432
29326
  );
28433
29327
  try {
28434
29328
  const nextConnState = hasStaticConnState ? structuredClone(config3.connState) : await config3.createConnState(
@@ -28465,7 +29359,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28465
29359
  ctx,
28466
29360
  connId
28467
29361
  )
28468
- )
29362
+ ),
29363
+ () => actorCtx.assertCanMutateState()
28469
29364
  );
28470
29365
  try {
28471
29366
  await config3.onConnect(
@@ -28497,7 +29392,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28497
29392
  ctx,
28498
29393
  connId
28499
29394
  )
28500
- )
29395
+ ),
29396
+ () => actorCtx.assertCanMutateState()
28501
29397
  )
28502
29398
  );
28503
29399
  }
@@ -28641,7 +29537,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28641
29537
  }
28642
29538
  ) : void 0,
28643
29539
  run: (() => {
28644
- const run = getRunFunction(config3.run);
28645
29540
  if (!run) {
28646
29541
  return void 0;
28647
29542
  }
@@ -28649,18 +29544,30 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28649
29544
  async (error46, payload) => {
28650
29545
  const { ctx } = unwrapTsfnPayload(error46, payload);
28651
29546
  const actorId = callNativeSync(() => runtime.actorId(ctx));
28652
- const actorCtx = makeActorCtx(ctx);
28653
- nativeRunHandlerActiveByActorId.set(actorId, true);
28654
- try {
28655
- await run(actorCtx);
28656
- } finally {
28657
- nativeRunHandlerActiveByActorId.delete(actorId);
28658
- await actorCtx.dispose();
29547
+ const executeRun = async () => {
29548
+ const actorCtx = makeActorCtx(ctx);
29549
+ try {
29550
+ await run(actorCtx);
29551
+ } finally {
29552
+ await actorCtx.dispose();
29553
+ }
29554
+ };
29555
+ if (runHandlerCoordinator) {
29556
+ const outcome = await runHandlerCoordinator.run(
29557
+ actorId,
29558
+ () => callNativeSync(
29559
+ () => runtime.actorRestartRunHandler(ctx)
29560
+ ),
29561
+ executeRun
29562
+ );
29563
+ return outcome !== "suppressed";
28659
29564
  }
29565
+ await executeRun();
29566
+ return true;
28660
29567
  }
28661
29568
  );
28662
29569
  })(),
28663
- getWorkflowHistory: getRunInspectorConfig(config3.run) !== void 0 ? wrapNativeCallback(
29570
+ getWorkflowHistory: hasRunInspectorConfig(config3.run) ? wrapNativeCallback(
28664
29571
  async (error46, payload) => {
28665
29572
  var _a22;
28666
29573
  const { ctx } = unwrapTsfnPayload(error46, payload);
@@ -28668,7 +29575,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28668
29575
  return history == null ? void 0 : toUint8Array(history);
28669
29576
  }
28670
29577
  ) : void 0,
28671
- replayWorkflow: getRunInspectorConfig(config3.run) !== void 0 ? wrapNativeCallback(
29578
+ replayWorkflow: hasRunInspectorConfig(config3.run) ? wrapNativeCallback(
28672
29579
  async (error46, payload) => {
28673
29580
  const { ctx, entryId } = unwrapTsfnPayload(
28674
29581
  error46,
@@ -28678,9 +29585,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28678
29585
  if (!(workflowInspector == null ? void 0 : workflowInspector.replayFromStep)) {
28679
29586
  return void 0;
28680
29587
  }
28681
- const history = await workflowInspector.replayFromStep(
28682
- entryId
28683
- ) ?? null;
29588
+ const history = await workflowInspector.replayFromStep(entryId) ?? null;
28684
29589
  return history == null ? void 0 : toUint8Array(history);
28685
29590
  }
28686
29591
  ) : void 0,
@@ -28733,7 +29638,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28733
29638
  jsRequest,
28734
29639
  stateEnabled,
28735
29640
  onStateChange,
28736
- cancelToken
29641
+ cancelToken,
29642
+ run !== void 0
28737
29643
  );
28738
29644
  try {
28739
29645
  if (!schemaConfig.queues || !hasSchemaConfigKey(schemaConfig.queues, name)) {
@@ -29702,6 +30608,7 @@ export {
29702
30608
  actor,
29703
30609
  buildActorNames,
29704
30610
  createClientWithDriver,
30611
+ defineRunHandler,
29705
30612
  event,
29706
30613
  isStaticActorDefinition,
29707
30614
  isStaticActorInstance,