@rivetkit/supabase 2.3.24-rc.1 → 2.3.25

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 +499 -708
  2. package/dist/mod.mjs +499 -708
  3. package/package.json +3 -3
package/dist/mod.js CHANGED
@@ -538,7 +538,7 @@ function unsupportedFeature(feature) {
538
538
  );
539
539
  }
540
540
 
541
- // ../rivetkit/dist/tsup/chunk-JJCUSUWO.js
541
+ // ../rivetkit/dist/tsup/chunk-BSQWFYSP.js
542
542
  var import_pino = require("pino");
543
543
 
544
544
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/classic/external.js
@@ -13211,7 +13211,7 @@ var classic_default = external_exports;
13211
13211
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/index.js
13212
13212
  var v4_default = classic_default;
13213
13213
 
13214
- // ../rivetkit/dist/tsup/chunk-JJCUSUWO.js
13214
+ // ../rivetkit/dist/tsup/chunk-BSQWFYSP.js
13215
13215
  var cbor = __toESM(require("cbor-x"), 1);
13216
13216
  var import_invariant = __toESM(require_invariant(), 1);
13217
13217
  var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
@@ -13382,7 +13382,7 @@ function noopNext() {
13382
13382
  }
13383
13383
  var package_default = {
13384
13384
  name: "rivetkit",
13385
- version: "2.3.24-rc.1",
13385
+ version: "2.3.25",
13386
13386
  description: "Lightweight libraries for building stateful actors on edge platforms",
13387
13387
  license: "Apache-2.0",
13388
13388
  keywords: [
@@ -14689,7 +14689,7 @@ function Config({ initialBufferLength = 1024, maxBufferLength = 1024 * 1024 * 32
14689
14689
  };
14690
14690
  }
14691
14691
 
14692
- // ../rivetkit/dist/tsup/chunk-M5J3PXNU.js
14692
+ // ../rivetkit/dist/tsup/chunk-FHRRLHJE.js
14693
14693
  var config2 = /* @__PURE__ */ Config({});
14694
14694
  function readWorkflowCbor(bc) {
14695
14695
  return readData(bc);
@@ -14987,7 +14987,7 @@ function decodeWorkflowHistoryTransport(data) {
14987
14987
  return decodeWorkflowHistory(toUint8Array(data));
14988
14988
  }
14989
14989
 
14990
- // ../rivetkit/dist/tsup/chunk-LTGBHN5Z.js
14990
+ // ../rivetkit/dist/tsup/chunk-CSOHAAZK.js
14991
14991
  function flattenActionHandlers(actions) {
14992
14992
  const flattened = /* @__PURE__ */ Object.create(null);
14993
14993
  for (const { name, handler } of collectActionEntries(actions)) {
@@ -15482,6 +15482,314 @@ var DocActorConfigSchema = external_exports.object({
15482
15482
  options: DocActorOptionsSchema.optional()
15483
15483
  }).describe("Actor configuration passed to the actor() function.");
15484
15484
 
15485
+ // ../rivetkit/dist/tsup/chunk-JTHHCZCZ.js
15486
+ var MIGRATION_TRANSACTION_TIMEOUT_MS = 5 * 6e4;
15487
+ function isManualTransactionControl(query) {
15488
+ return /^\s*(?:BEGIN|SAVEPOINT|COMMIT|END|ROLLBACK)\b/i.test(query);
15489
+ }
15490
+ function validateTransactionTimeout(timeout) {
15491
+ if (timeout !== void 0 && (!Number.isFinite(timeout) || timeout <= 0)) {
15492
+ throw new Error(
15493
+ "db.transaction() timeout must be a positive finite number of milliseconds"
15494
+ );
15495
+ }
15496
+ }
15497
+ function validateTransactionName(name) {
15498
+ if (name === void 0) {
15499
+ return;
15500
+ }
15501
+ if (name.length === 0) {
15502
+ throw new Error("db.transaction() name must not be empty");
15503
+ }
15504
+ }
15505
+ function isSqliteBindingValue(value) {
15506
+ if (value === null || typeof value === "number" || typeof value === "string" || typeof value === "bigint" || value instanceof Uint8Array) {
15507
+ return true;
15508
+ }
15509
+ if (Array.isArray(value)) {
15510
+ return value.every((item) => typeof item === "number");
15511
+ }
15512
+ return false;
15513
+ }
15514
+ function isPlainObject3(value) {
15515
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
15516
+ return false;
15517
+ }
15518
+ return Object.getPrototypeOf(value) === Object.prototype;
15519
+ }
15520
+ function isSqliteBindingObject(value) {
15521
+ if (!isPlainObject3(value)) {
15522
+ return false;
15523
+ }
15524
+ return Object.values(value).every((entry) => isSqliteBindingValue(entry));
15525
+ }
15526
+ function toSqliteBindings(input) {
15527
+ if (Array.isArray(input)) {
15528
+ for (const value of input) {
15529
+ if (!isSqliteBindingValue(value)) {
15530
+ throw new Error(
15531
+ `unsupported sqlite binding type: ${typeof value}`
15532
+ );
15533
+ }
15534
+ }
15535
+ return input;
15536
+ }
15537
+ if (isSqliteBindingObject(input)) {
15538
+ return input;
15539
+ }
15540
+ throw new Error("unsupported sqlite binding collection");
15541
+ }
15542
+ var AsyncMutex = class {
15543
+ #locked = false;
15544
+ #waiting = [];
15545
+ async acquire() {
15546
+ while (this.#locked) {
15547
+ await new Promise((resolve) => this.#waiting.push(resolve));
15548
+ }
15549
+ this.#locked = true;
15550
+ }
15551
+ release() {
15552
+ this.#locked = false;
15553
+ const next = this.#waiting.shift();
15554
+ if (next) {
15555
+ next();
15556
+ }
15557
+ }
15558
+ async run(fn) {
15559
+ await this.acquire();
15560
+ try {
15561
+ return await fn();
15562
+ } finally {
15563
+ this.release();
15564
+ }
15565
+ }
15566
+ };
15567
+
15568
+ // ../rivetkit/dist/tsup/chunk-BRYK7XVR.js
15569
+ var nativeStateTransactionOpeners = /* @__PURE__ */ new WeakMap();
15570
+ var nativeStateTransactionClientBinders = /* @__PURE__ */ new WeakMap();
15571
+ function registerNativeStateTransactionOpener(provider, opener) {
15572
+ nativeStateTransactionOpeners.set(provider, opener);
15573
+ return provider;
15574
+ }
15575
+ function bindNativeStateTransactionContext(client, context2) {
15576
+ if ((typeof client !== "object" || client === null) && typeof client !== "function") {
15577
+ return client;
15578
+ }
15579
+ const bind = nativeStateTransactionClientBinders.get(client);
15580
+ return (bind == null ? void 0 : bind(context2)) ?? client;
15581
+ }
15582
+ function hasMultipleStatements(query) {
15583
+ const trimmed = query.trim().replace(/;+$/, "").trimEnd();
15584
+ return trimmed.includes(";");
15585
+ }
15586
+ function db({
15587
+ onMigrate,
15588
+ warnOnManualTransactions = true,
15589
+ profiling
15590
+ } = {}) {
15591
+ const provider = {
15592
+ sqliteProfiling: profiling,
15593
+ createClient: async (ctx) => {
15594
+ const nativeDatabaseProvider = ctx.nativeDatabaseProvider;
15595
+ if (!nativeDatabaseProvider) {
15596
+ throw new Error(
15597
+ "native SQLite is required, but the current runtime did not provide a native database provider"
15598
+ );
15599
+ }
15600
+ const db2 = await nativeDatabaseProvider.open(ctx.actorId);
15601
+ let closed = false;
15602
+ let manualTransactionWarned = false;
15603
+ const ensureOpen = () => {
15604
+ if (closed) {
15605
+ throw new Error(
15606
+ "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."
15607
+ );
15608
+ }
15609
+ };
15610
+ const createClient = (target, transactionScoped = false, stateTransactionContext) => {
15611
+ const client2 = {
15612
+ execute: async (query, ...args) => {
15613
+ var _a2, _b, _c, _d;
15614
+ ensureOpen();
15615
+ if (!transactionScoped && warnOnManualTransactions && !manualTransactionWarned && !hasMultipleStatements(query) && isManualTransactionControl(query)) {
15616
+ manualTransactionWarned = true;
15617
+ getLogger("database").warn(
15618
+ { actorId: ctx.actorId },
15619
+ "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."
15620
+ );
15621
+ }
15622
+ const kvReadsBefore = ((_a2 = ctx.metrics) == null ? void 0 : _a2.totalKvReads) ?? 0;
15623
+ const kvWritesBefore = ((_b = ctx.metrics) == null ? void 0 : _b.totalKvWrites) ?? 0;
15624
+ const start = performance.now();
15625
+ try {
15626
+ if (args.length > 0) {
15627
+ const bindings = args.length === 1 && isSqliteBindingObject(args[0]) ? toSqliteBindings(args[0]) : toSqliteBindings(args);
15628
+ const { rows, columns } = await target.execute(
15629
+ query,
15630
+ bindings
15631
+ );
15632
+ return rows.map(
15633
+ (row) => rowToObject(row, columns)
15634
+ );
15635
+ }
15636
+ if (!hasMultipleStatements(query)) {
15637
+ const { rows, columns } = await target.execute(
15638
+ query,
15639
+ void 0
15640
+ );
15641
+ return rows.map(
15642
+ (row) => rowToObject(row, columns)
15643
+ );
15644
+ }
15645
+ return await execMultiStatement(
15646
+ target,
15647
+ query
15648
+ );
15649
+ } finally {
15650
+ const durationMs = performance.now() - start;
15651
+ (_c = ctx.metrics) == null ? void 0 : _c.trackSql(query, durationMs);
15652
+ if (ctx.metrics) {
15653
+ const kvReads = ctx.metrics.totalKvReads - kvReadsBefore;
15654
+ const kvWrites = ctx.metrics.totalKvWrites - kvWritesBefore;
15655
+ (_d = ctx.log) == null ? void 0 : _d.debug({
15656
+ msg: "sql query",
15657
+ query: query.slice(0, 120),
15658
+ durationMs,
15659
+ kvReads,
15660
+ kvWrites
15661
+ });
15662
+ }
15663
+ }
15664
+ },
15665
+ transaction: async (callback, options) => {
15666
+ var _a2, _b;
15667
+ validateTransactionTimeout(options == null ? void 0 : options.timeout);
15668
+ validateTransactionName(options == null ? void 0 : options.name);
15669
+ if (transactionScoped && ((_a2 = options == null ? void 0 : options.experimental) == null ? void 0 : _a2.includeState)) {
15670
+ throw new Error(
15671
+ "experimental.includeState is not supported for nested transactions"
15672
+ );
15673
+ }
15674
+ const includeState = ((_b = options == null ? void 0 : options.experimental) == null ? void 0 : _b.includeState) === true;
15675
+ const stateScope = includeState && stateTransactionContext ? await stateTransactionContext.enter() : void 0;
15676
+ try {
15677
+ const transaction = includeState ? await (() => {
15678
+ const beginStateTransaction = ctx.nativeDatabaseProvider && nativeStateTransactionOpeners.get(
15679
+ ctx.nativeDatabaseProvider
15680
+ );
15681
+ if (!beginStateTransaction) {
15682
+ throw new Error(
15683
+ "experimental.includeState is only supported by RivetKit's embedded database provider"
15684
+ );
15685
+ }
15686
+ return beginStateTransaction(
15687
+ options == null ? void 0 : options.timeout,
15688
+ stateScope
15689
+ );
15690
+ })() : await db2.beginTransaction(
15691
+ options == null ? void 0 : options.timeout,
15692
+ options == null ? void 0 : options.name
15693
+ );
15694
+ const tx = createClient(transaction, true);
15695
+ try {
15696
+ const result = await callback(tx);
15697
+ await transaction.commit();
15698
+ return result;
15699
+ } catch (error46) {
15700
+ try {
15701
+ await transaction.rollback();
15702
+ } catch {
15703
+ }
15704
+ throw error46;
15705
+ }
15706
+ } finally {
15707
+ if (stateScope !== void 0) {
15708
+ stateTransactionContext == null ? void 0 : stateTransactionContext.exit(stateScope);
15709
+ }
15710
+ }
15711
+ },
15712
+ close: async () => {
15713
+ if (!closed) {
15714
+ closed = true;
15715
+ await db2.close();
15716
+ }
15717
+ },
15718
+ nativeMetrics: () => {
15719
+ var _a2;
15720
+ return ((_a2 = db2.nativeMetrics) == null ? void 0 : _a2.call(db2)) ?? null;
15721
+ }
15722
+ };
15723
+ if (!transactionScoped) {
15724
+ nativeStateTransactionClientBinders.set(
15725
+ client2,
15726
+ (context2) => createClient(target, false, context2)
15727
+ );
15728
+ }
15729
+ return client2;
15730
+ };
15731
+ const client = createClient(db2);
15732
+ return client;
15733
+ },
15734
+ onMigrate: async (client) => {
15735
+ if (onMigrate) {
15736
+ await withMigrationSavepoint(
15737
+ client,
15738
+ (leased) => onMigrate(leased)
15739
+ );
15740
+ }
15741
+ }
15742
+ };
15743
+ return provider;
15744
+ }
15745
+ function rowToObject(row, columns) {
15746
+ const rowObj = {};
15747
+ for (let i = 0; i < columns.length; i++) {
15748
+ rowObj[columns[i]] = row[i];
15749
+ }
15750
+ return rowObj;
15751
+ }
15752
+ async function execMultiStatement(db2, query) {
15753
+ const results = [];
15754
+ let columnNames = null;
15755
+ await db2.exec(query, (row, columns) => {
15756
+ if (!columnNames) {
15757
+ columnNames = columns;
15758
+ }
15759
+ results.push(rowToObject(row, columnNames));
15760
+ });
15761
+ return results;
15762
+ }
15763
+ async function withMigrationSavepoint(client, callback) {
15764
+ return await client.transaction(
15765
+ async (transaction) => {
15766
+ await transaction.execute("SAVEPOINT __rivet_on_migrate");
15767
+ try {
15768
+ const result = await callback(transaction);
15769
+ await transaction.execute(
15770
+ "RELEASE SAVEPOINT __rivet_on_migrate"
15771
+ );
15772
+ return result;
15773
+ } catch (error46) {
15774
+ try {
15775
+ await transaction.execute(
15776
+ "ROLLBACK TO SAVEPOINT __rivet_on_migrate"
15777
+ );
15778
+ } finally {
15779
+ await transaction.execute(
15780
+ "RELEASE SAVEPOINT __rivet_on_migrate"
15781
+ );
15782
+ }
15783
+ throw error46;
15784
+ }
15785
+ },
15786
+ {
15787
+ name: "rivetkit-migration",
15788
+ timeout: MIGRATION_TRANSACTION_TIMEOUT_MS
15789
+ }
15790
+ );
15791
+ }
15792
+
15485
15793
  // ../rivetkit/dist/tsup/chunk-JI6GZ2C2.js
15486
15794
  var EMPTY_KEY = "/";
15487
15795
  var KEY_SEPARATOR = "/";
@@ -15596,93 +15904,10 @@ function makePrefixedKey(key) {
15596
15904
  return prefixed;
15597
15905
  }
15598
15906
  function removePrefixFromKey(prefixedKey) {
15599
- return prefixedKey.slice(KEYS.KV.length);
15600
- }
15601
-
15602
- // ../rivetkit/dist/tsup/chunk-JTHHCZCZ.js
15603
- var MIGRATION_TRANSACTION_TIMEOUT_MS = 5 * 6e4;
15604
- function isManualTransactionControl(query) {
15605
- return /^\s*(?:BEGIN|SAVEPOINT|COMMIT|END|ROLLBACK)\b/i.test(query);
15606
- }
15607
- function validateTransactionTimeout(timeout) {
15608
- if (timeout !== void 0 && (!Number.isFinite(timeout) || timeout <= 0)) {
15609
- throw new Error(
15610
- "db.transaction() timeout must be a positive finite number of milliseconds"
15611
- );
15612
- }
15613
- }
15614
- function validateTransactionName(name) {
15615
- if (name === void 0) {
15616
- return;
15617
- }
15618
- if (name.length === 0) {
15619
- throw new Error("db.transaction() name must not be empty");
15620
- }
15621
- }
15622
- function isSqliteBindingValue(value) {
15623
- if (value === null || typeof value === "number" || typeof value === "string" || typeof value === "bigint" || value instanceof Uint8Array) {
15624
- return true;
15625
- }
15626
- if (Array.isArray(value)) {
15627
- return value.every((item) => typeof item === "number");
15628
- }
15629
- return false;
15630
- }
15631
- function isPlainObject3(value) {
15632
- if (!value || typeof value !== "object" || Array.isArray(value)) {
15633
- return false;
15634
- }
15635
- return Object.getPrototypeOf(value) === Object.prototype;
15636
- }
15637
- function isSqliteBindingObject(value) {
15638
- if (!isPlainObject3(value)) {
15639
- return false;
15640
- }
15641
- return Object.values(value).every((entry) => isSqliteBindingValue(entry));
15642
- }
15643
- function toSqliteBindings(input) {
15644
- if (Array.isArray(input)) {
15645
- for (const value of input) {
15646
- if (!isSqliteBindingValue(value)) {
15647
- throw new Error(
15648
- `unsupported sqlite binding type: ${typeof value}`
15649
- );
15650
- }
15651
- }
15652
- return input;
15653
- }
15654
- if (isSqliteBindingObject(input)) {
15655
- return input;
15656
- }
15657
- throw new Error("unsupported sqlite binding collection");
15658
- }
15659
- var AsyncMutex = class {
15660
- #locked = false;
15661
- #waiting = [];
15662
- async acquire() {
15663
- while (this.#locked) {
15664
- await new Promise((resolve) => this.#waiting.push(resolve));
15665
- }
15666
- this.#locked = true;
15667
- }
15668
- release() {
15669
- this.#locked = false;
15670
- const next = this.#waiting.shift();
15671
- if (next) {
15672
- next();
15673
- }
15674
- }
15675
- async run(fn) {
15676
- await this.acquire();
15677
- try {
15678
- return await fn();
15679
- } finally {
15680
- this.release();
15681
- }
15682
- }
15683
- };
15907
+ return prefixedKey.slice(KEYS.KV.length);
15908
+ }
15684
15909
 
15685
- // ../rivetkit/dist/tsup/chunk-OB5JLDBM.js
15910
+ // ../rivetkit/dist/tsup/chunk-3KHT4UQA.js
15686
15911
  function logger() {
15687
15912
  return getLogger("actor-client");
15688
15913
  }
@@ -15720,7 +15945,7 @@ async function importWebSocket() {
15720
15945
  return webSocketPromise;
15721
15946
  }
15722
15947
 
15723
- // ../rivetkit/dist/tsup/chunk-B6WTPGOR.js
15948
+ // ../rivetkit/dist/tsup/chunk-FV63WBQ5.js
15724
15949
  var import_invariant2 = __toESM(require_invariant(), 1);
15725
15950
 
15726
15951
  // ../../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
@@ -16935,7 +17160,7 @@ var TraceAPI = (
16935
17160
  // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js
16936
17161
  var trace = TraceAPI.getInstance();
16937
17162
 
16938
- // ../rivetkit/dist/tsup/chunk-B6WTPGOR.js
17163
+ // ../rivetkit/dist/tsup/chunk-FV63WBQ5.js
16939
17164
  var import_invariant3 = __toESM(require_invariant(), 1);
16940
17165
  var import_invariant4 = __toESM(require_invariant(), 1);
16941
17166
  var PATH_CONNECT = "/connect";
@@ -19018,6 +19243,14 @@ function isResponseLike(value) {
19018
19243
  function isHeadersLike(value) {
19019
19244
  return typeof value === "object" && value !== null && typeof value.entries === "function";
19020
19245
  }
19246
+ function readRequestBody(request) {
19247
+ if (!request.body) return request.arrayBuffer();
19248
+ return new Response(
19249
+ request.body.pipeThrough(new TransformStream(), {
19250
+ signal: request.signal
19251
+ })
19252
+ ).arrayBuffer();
19253
+ }
19021
19254
  function* walkErrorChain(error46, maxDepth = 8) {
19022
19255
  let current = error46;
19023
19256
  let depth = 0;
@@ -19546,9 +19779,10 @@ async function rawHttpFetch(driver, target, params, input, init, options = {}, t
19546
19779
  initHeaders.forEach((value, key) => {
19547
19780
  mergedHeaders.set(key, value);
19548
19781
  });
19782
+ const readsInputBody = (init == null ? void 0 : init.body) === void 0 && input.method !== "GET" && input.method !== "HEAD";
19549
19783
  mergedInit = {
19550
19784
  method: input.method,
19551
- body: input.body,
19785
+ body: readsInputBody ? await readRequestBody(input) : void 0,
19552
19786
  mode: input.mode,
19553
19787
  credentials: input.credentials,
19554
19788
  redirect: input.redirect,
@@ -21967,6 +22201,8 @@ var ClientConfigSchemaBase = v4_default.object({
21967
22201
  // This is required in the client config in order to support
21968
22202
  // `proxyWebSocket`
21969
22203
  getUpgradeWebSocket: v4_default.custom().optional(),
22204
+ /** Replaces global fetch for actor HTTP gateway requests. */
22205
+ fetch: v4_default.custom().optional(),
21970
22206
  /** Whether to automatically perform health checks when the client is created. */
21971
22207
  disableMetadataLookup: v4_default.boolean().optional().default(false),
21972
22208
  /**
@@ -22028,18 +22264,26 @@ async function sendHttpRequestToGateway(runConfig, gatewayUrl, actorRequest, opt
22028
22264
  if (actorRequest.bodyUsed) {
22029
22265
  throw new Error("Request body has already been consumed");
22030
22266
  }
22031
- if (actorRequest.body) {
22032
- bodyToSend = actorRequest.body;
22267
+ const bytes = await readRequestBody(actorRequest);
22268
+ if (bytes.byteLength > 0) {
22269
+ bodyToSend = bytes;
22033
22270
  guardHeaders.delete("transfer-encoding");
22034
22271
  guardHeaders.delete("content-length");
22035
22272
  }
22036
22273
  }
22037
- return fetch(gatewayUrl, {
22274
+ const fetchImpl = runConfig.fetch ?? fetch;
22275
+ return fetchImpl(gatewayUrl, {
22038
22276
  method: actorRequest.method,
22039
22277
  headers: guardHeaders,
22040
22278
  body: bodyToSend,
22041
22279
  signal: actorRequest.signal,
22042
- ...bodyToSend ? { duplex: "half" } : {}
22280
+ mode: actorRequest.mode,
22281
+ credentials: actorRequest.credentials,
22282
+ redirect: actorRequest.redirect,
22283
+ referrer: actorRequest.referrer,
22284
+ referrerPolicy: actorRequest.referrerPolicy,
22285
+ integrity: actorRequest.integrity,
22286
+ keepalive: actorRequest.keepalive
22043
22287
  });
22044
22288
  }
22045
22289
  function buildGuardHeaders(runConfig, actorRequest, options) {
@@ -23032,309 +23276,84 @@ var RemoteEngineControlClient = class {
23032
23276
  }
23033
23277
  setGetUpgradeWebSocket(getUpgradeWebSocket) {
23034
23278
  this.#config.getUpgradeWebSocket = getUpgradeWebSocket;
23035
- }
23036
- #buildGatewayUrlForTarget(config3, target, path2, options = {}) {
23037
- const endpoint = getEndpoint(config3);
23038
- if (shouldSkipReadyWait(options) && directActorIdFromTarget(target) && canUseDirectSkipReadyWaitPath(path2)) {
23039
- return combineUrlPath(endpoint, path2);
23040
- }
23041
- if ("directId" in target) {
23042
- return buildActorGatewayUrl(
23043
- endpoint,
23044
- target.directId,
23045
- config3.token,
23046
- path2
23047
- );
23048
- }
23049
- if ("getForId" in target) {
23050
- return buildActorGatewayUrl(
23051
- endpoint,
23052
- target.getForId.actorId,
23053
- config3.token,
23054
- path2
23055
- );
23056
- }
23057
- if ("getForKey" in target || "getOrCreateForKey" in target) {
23058
- return buildActorQueryGatewayUrl(
23059
- endpoint,
23060
- config3.namespace,
23061
- target,
23062
- config3.token,
23063
- path2,
23064
- config3.maxInputSize,
23065
- void 0,
23066
- "getOrCreateForKey" in target ? target.getOrCreateForKey.poolName ?? config3.poolName : void 0,
23067
- options
23068
- );
23069
- }
23070
- if ("create" in target) {
23071
- throw new Error(
23072
- "Gateway URLs only support direct actor IDs, get, and getOrCreate targets."
23073
- );
23074
- }
23075
- throw new Error("unreachable: unknown gateway target type");
23076
- }
23077
- };
23078
- function canUseDirectSkipReadyWaitPath(path2) {
23079
- return isActorHttpRequestPath(path2) || isPathOrQuery(path2, PATH_CONNECT) || isPathOrQuery(path2, PATH_WEBSOCKET_BASE) || path2.startsWith(PATH_WEBSOCKET_PREFIX);
23080
- }
23081
- function isPathOrQuery(path2, basePath) {
23082
- return path2 === basePath || path2.startsWith(`${basePath}?`);
23083
- }
23084
- function isActorHttpRequestPath(path2) {
23085
- const stripped = path2.slice("/request".length);
23086
- return path2.startsWith("/request") && (stripped.length === 0 || stripped.startsWith("/") || stripped.startsWith("?"));
23087
- }
23088
- function directActorIdFromTarget(target) {
23089
- if ("directId" in target) {
23090
- return target.directId;
23091
- }
23092
- if ("getForId" in target) {
23093
- return target.getForId.actorId;
23094
- }
23095
- return void 0;
23096
- }
23097
- function requestPath(req) {
23098
- const url2 = new URL(req.url);
23099
- return `${url2.pathname}${url2.search}`;
23100
- }
23101
- function apiActorToOutput(actor2) {
23102
- return {
23103
- actorId: actor2.actor_id,
23104
- name: actor2.name,
23105
- key: deserializeActorKey(actor2.key),
23106
- createTs: actor2.create_ts,
23107
- startTs: actor2.start_ts ?? null,
23108
- connectableTs: actor2.connectable_ts ?? null,
23109
- sleepTs: actor2.sleep_ts ?? null,
23110
- destroyTs: actor2.destroy_ts ?? null,
23111
- error: actor2.error ?? void 0
23112
- };
23113
- }
23114
-
23115
- // ../rivetkit/dist/tsup/chunk-QQ454DVR.js
23116
- var nativeStateTransactionOpeners = /* @__PURE__ */ new WeakMap();
23117
- var nativeStateTransactionClientBinders = /* @__PURE__ */ new WeakMap();
23118
- function registerNativeStateTransactionOpener(provider, opener) {
23119
- nativeStateTransactionOpeners.set(provider, opener);
23120
- return provider;
23121
- }
23122
- function bindNativeStateTransactionContext(client, context2) {
23123
- if ((typeof client !== "object" || client === null) && typeof client !== "function") {
23124
- return client;
23125
- }
23126
- const bind = nativeStateTransactionClientBinders.get(client);
23127
- return (bind == null ? void 0 : bind(context2)) ?? client;
23128
- }
23129
- function hasMultipleStatements(query) {
23130
- const trimmed = query.trim().replace(/;+$/, "").trimEnd();
23131
- return trimmed.includes(";");
23132
- }
23133
- function db({
23134
- onMigrate,
23135
- warnOnManualTransactions = true,
23136
- profiling
23137
- } = {}) {
23138
- const provider = {
23139
- sqliteProfiling: profiling,
23140
- createClient: async (ctx) => {
23141
- const nativeDatabaseProvider = ctx.nativeDatabaseProvider;
23142
- if (!nativeDatabaseProvider) {
23143
- throw new Error(
23144
- "native SQLite is required, but the current runtime did not provide a native database provider"
23145
- );
23146
- }
23147
- const db2 = await nativeDatabaseProvider.open(ctx.actorId);
23148
- let closed = false;
23149
- let manualTransactionWarned = false;
23150
- const ensureOpen = () => {
23151
- if (closed) {
23152
- throw new Error(
23153
- "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."
23154
- );
23155
- }
23156
- };
23157
- const createClient = (target, transactionScoped = false, stateTransactionContext) => {
23158
- const client2 = {
23159
- execute: async (query, ...args) => {
23160
- var _a2, _b, _c, _d;
23161
- ensureOpen();
23162
- if (!transactionScoped && warnOnManualTransactions && !manualTransactionWarned && !hasMultipleStatements(query) && isManualTransactionControl(query)) {
23163
- manualTransactionWarned = true;
23164
- getLogger("database").warn(
23165
- { actorId: ctx.actorId },
23166
- "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."
23167
- );
23168
- }
23169
- const kvReadsBefore = ((_a2 = ctx.metrics) == null ? void 0 : _a2.totalKvReads) ?? 0;
23170
- const kvWritesBefore = ((_b = ctx.metrics) == null ? void 0 : _b.totalKvWrites) ?? 0;
23171
- const start = performance.now();
23172
- try {
23173
- if (args.length > 0) {
23174
- const bindings = args.length === 1 && isSqliteBindingObject(args[0]) ? toSqliteBindings(args[0]) : toSqliteBindings(args);
23175
- const { rows, columns } = await target.execute(
23176
- query,
23177
- bindings
23178
- );
23179
- return rows.map(
23180
- (row) => rowToObject(row, columns)
23181
- );
23182
- }
23183
- if (!hasMultipleStatements(query)) {
23184
- const { rows, columns } = await target.execute(
23185
- query,
23186
- void 0
23187
- );
23188
- return rows.map(
23189
- (row) => rowToObject(row, columns)
23190
- );
23191
- }
23192
- return await execMultiStatement(
23193
- target,
23194
- query
23195
- );
23196
- } finally {
23197
- const durationMs = performance.now() - start;
23198
- (_c = ctx.metrics) == null ? void 0 : _c.trackSql(query, durationMs);
23199
- if (ctx.metrics) {
23200
- const kvReads = ctx.metrics.totalKvReads - kvReadsBefore;
23201
- const kvWrites = ctx.metrics.totalKvWrites - kvWritesBefore;
23202
- (_d = ctx.log) == null ? void 0 : _d.debug({
23203
- msg: "sql query",
23204
- query: query.slice(0, 120),
23205
- durationMs,
23206
- kvReads,
23207
- kvWrites
23208
- });
23209
- }
23210
- }
23211
- },
23212
- transaction: async (callback, options) => {
23213
- var _a2, _b;
23214
- validateTransactionTimeout(options == null ? void 0 : options.timeout);
23215
- validateTransactionName(options == null ? void 0 : options.name);
23216
- if (transactionScoped && ((_a2 = options == null ? void 0 : options.experimental) == null ? void 0 : _a2.includeState)) {
23217
- throw new Error(
23218
- "experimental.includeState is not supported for nested transactions"
23219
- );
23220
- }
23221
- const includeState = ((_b = options == null ? void 0 : options.experimental) == null ? void 0 : _b.includeState) === true;
23222
- const stateScope = includeState && stateTransactionContext ? await stateTransactionContext.enter() : void 0;
23223
- try {
23224
- const transaction = includeState ? await (() => {
23225
- const beginStateTransaction = ctx.nativeDatabaseProvider && nativeStateTransactionOpeners.get(
23226
- ctx.nativeDatabaseProvider
23227
- );
23228
- if (!beginStateTransaction) {
23229
- throw new Error(
23230
- "experimental.includeState is only supported by RivetKit's embedded database provider"
23231
- );
23232
- }
23233
- return beginStateTransaction(
23234
- options == null ? void 0 : options.timeout,
23235
- stateScope
23236
- );
23237
- })() : await db2.beginTransaction(
23238
- options == null ? void 0 : options.timeout,
23239
- options == null ? void 0 : options.name
23240
- );
23241
- const tx = createClient(transaction, true);
23242
- try {
23243
- const result = await callback(tx);
23244
- await transaction.commit();
23245
- return result;
23246
- } catch (error46) {
23247
- try {
23248
- await transaction.rollback();
23249
- } catch {
23250
- }
23251
- throw error46;
23252
- }
23253
- } finally {
23254
- if (stateScope !== void 0) {
23255
- stateTransactionContext == null ? void 0 : stateTransactionContext.exit(stateScope);
23256
- }
23257
- }
23258
- },
23259
- close: async () => {
23260
- if (!closed) {
23261
- closed = true;
23262
- await db2.close();
23263
- }
23264
- },
23265
- nativeMetrics: () => {
23266
- var _a2;
23267
- return ((_a2 = db2.nativeMetrics) == null ? void 0 : _a2.call(db2)) ?? null;
23268
- }
23269
- };
23270
- if (!transactionScoped) {
23271
- nativeStateTransactionClientBinders.set(
23272
- client2,
23273
- (context2) => createClient(target, false, context2)
23274
- );
23275
- }
23276
- return client2;
23277
- };
23278
- const client = createClient(db2);
23279
- return client;
23280
- },
23281
- onMigrate: async (client) => {
23282
- if (onMigrate) {
23283
- await withMigrationSavepoint(
23284
- client,
23285
- (leased) => onMigrate(leased)
23286
- );
23287
- }
23279
+ }
23280
+ #buildGatewayUrlForTarget(config3, target, path2, options = {}) {
23281
+ const endpoint = getEndpoint(config3);
23282
+ if (shouldSkipReadyWait(options) && directActorIdFromTarget(target) && canUseDirectSkipReadyWaitPath(path2)) {
23283
+ return combineUrlPath(endpoint, path2);
23288
23284
  }
23289
- };
23290
- return provider;
23285
+ if ("directId" in target) {
23286
+ return buildActorGatewayUrl(
23287
+ endpoint,
23288
+ target.directId,
23289
+ config3.token,
23290
+ path2
23291
+ );
23292
+ }
23293
+ if ("getForId" in target) {
23294
+ return buildActorGatewayUrl(
23295
+ endpoint,
23296
+ target.getForId.actorId,
23297
+ config3.token,
23298
+ path2
23299
+ );
23300
+ }
23301
+ if ("getForKey" in target || "getOrCreateForKey" in target) {
23302
+ return buildActorQueryGatewayUrl(
23303
+ endpoint,
23304
+ config3.namespace,
23305
+ target,
23306
+ config3.token,
23307
+ path2,
23308
+ config3.maxInputSize,
23309
+ void 0,
23310
+ "getOrCreateForKey" in target ? target.getOrCreateForKey.poolName ?? config3.poolName : void 0,
23311
+ options
23312
+ );
23313
+ }
23314
+ if ("create" in target) {
23315
+ throw new Error(
23316
+ "Gateway URLs only support direct actor IDs, get, and getOrCreate targets."
23317
+ );
23318
+ }
23319
+ throw new Error("unreachable: unknown gateway target type");
23320
+ }
23321
+ };
23322
+ function canUseDirectSkipReadyWaitPath(path2) {
23323
+ return isActorHttpRequestPath(path2) || isPathOrQuery(path2, PATH_CONNECT) || isPathOrQuery(path2, PATH_WEBSOCKET_BASE) || path2.startsWith(PATH_WEBSOCKET_PREFIX);
23291
23324
  }
23292
- function rowToObject(row, columns) {
23293
- const rowObj = {};
23294
- for (let i = 0; i < columns.length; i++) {
23295
- rowObj[columns[i]] = row[i];
23325
+ function isPathOrQuery(path2, basePath) {
23326
+ return path2 === basePath || path2.startsWith(`${basePath}?`);
23327
+ }
23328
+ function isActorHttpRequestPath(path2) {
23329
+ const stripped = path2.slice("/request".length);
23330
+ return path2.startsWith("/request") && (stripped.length === 0 || stripped.startsWith("/") || stripped.startsWith("?"));
23331
+ }
23332
+ function directActorIdFromTarget(target) {
23333
+ if ("directId" in target) {
23334
+ return target.directId;
23296
23335
  }
23297
- return rowObj;
23336
+ if ("getForId" in target) {
23337
+ return target.getForId.actorId;
23338
+ }
23339
+ return void 0;
23298
23340
  }
23299
- async function execMultiStatement(db2, query) {
23300
- const results = [];
23301
- let columnNames = null;
23302
- await db2.exec(query, (row, columns) => {
23303
- if (!columnNames) {
23304
- columnNames = columns;
23305
- }
23306
- results.push(rowToObject(row, columnNames));
23307
- });
23308
- return results;
23341
+ function requestPath(req) {
23342
+ const url2 = new URL(req.url);
23343
+ return `${url2.pathname}${url2.search}`;
23309
23344
  }
23310
- async function withMigrationSavepoint(client, callback) {
23311
- return await client.transaction(
23312
- async (transaction) => {
23313
- await transaction.execute("SAVEPOINT __rivet_on_migrate");
23314
- try {
23315
- const result = await callback(transaction);
23316
- await transaction.execute(
23317
- "RELEASE SAVEPOINT __rivet_on_migrate"
23318
- );
23319
- return result;
23320
- } catch (error46) {
23321
- try {
23322
- await transaction.execute(
23323
- "ROLLBACK TO SAVEPOINT __rivet_on_migrate"
23324
- );
23325
- } finally {
23326
- await transaction.execute(
23327
- "RELEASE SAVEPOINT __rivet_on_migrate"
23328
- );
23329
- }
23330
- throw error46;
23331
- }
23332
- },
23333
- {
23334
- name: "rivetkit-migration",
23335
- timeout: MIGRATION_TRANSACTION_TIMEOUT_MS
23336
- }
23337
- );
23345
+ function apiActorToOutput(actor2) {
23346
+ return {
23347
+ actorId: actor2.actor_id,
23348
+ name: actor2.name,
23349
+ key: deserializeActorKey(actor2.key),
23350
+ createTs: actor2.create_ts,
23351
+ startTs: actor2.start_ts ?? null,
23352
+ connectableTs: actor2.connectable_ts ?? null,
23353
+ sleepTs: actor2.sleep_ts ?? null,
23354
+ destroyTs: actor2.destroy_ts ?? null,
23355
+ error: actor2.error ?? void 0
23356
+ };
23338
23357
  }
23339
23358
 
23340
23359
  // ../../../shared/typescript/virtual-websocket/dist/mod.js
@@ -26171,12 +26190,6 @@ var NapiCoreRuntime = class {
26171
26190
  actorId(ctx) {
26172
26191
  return asNativeActorContext(ctx).actorId();
26173
26192
  }
26174
- actorGeneration(ctx) {
26175
- return asNativeActorContext(ctx).generation() ?? void 0;
26176
- }
26177
- actorIsLost(ctx) {
26178
- return asNativeActorContext(ctx).isLost();
26179
- }
26180
26193
  runWithActorInvocationContext(ctx, run) {
26181
26194
  return this.#runAs(asNativeActorContext(ctx), run);
26182
26195
  }
@@ -26790,27 +26803,6 @@ function notifyStateChanged(state) {
26790
26803
  waiter();
26791
26804
  }
26792
26805
  }
26793
- function createRunState(actorGeneration) {
26794
- return {
26795
- actorGeneration,
26796
- active: false,
26797
- closed: false,
26798
- exclusive: false,
26799
- exclusiveGeneration: 0,
26800
- inspectorInitialized: false,
26801
- queued: 0,
26802
- waiters: /* @__PURE__ */ new Set()
26803
- };
26804
- }
26805
- function closeRunState(state, disposeInspector = true) {
26806
- var _a2, _b;
26807
- state.closed = true;
26808
- if (disposeInspector) {
26809
- (_b = (_a2 = state.inspector) == null ? void 0 : _a2.dispose) == null ? void 0 : _b.call(_a2);
26810
- }
26811
- state.inspector = void 0;
26812
- notifyStateChanged(state);
26813
- }
26814
26806
  function waitForStateChange(state) {
26815
26807
  return new Promise((resolve) => {
26816
26808
  state.waiters.add(resolve);
@@ -26825,11 +26817,8 @@ var RunHandlerCoordinator = class {
26825
26817
  get inspectorKind() {
26826
26818
  return getRunInspectorKind(this.#run);
26827
26819
  }
26828
- async run(actorId, restart, callback, actorGeneration) {
26829
- const state = this.#getOrCreate(actorId, actorGeneration);
26830
- if (state.closed) {
26831
- return "closed";
26832
- }
26820
+ async run(actorId, restart, callback) {
26821
+ const state = this.#getOrCreate(actorId);
26833
26822
  state.restart = restart;
26834
26823
  this.#initializeInspector(actorId, state);
26835
26824
  state.queued += 1;
@@ -26856,27 +26845,21 @@ var RunHandlerCoordinator = class {
26856
26845
  notifyStateChanged(state);
26857
26846
  }
26858
26847
  }
26859
- getInspector(actorId, restart, actorGeneration) {
26848
+ getInspector(actorId, restart) {
26860
26849
  var _a2;
26861
- const state = this.#getOrCreate(actorId, actorGeneration);
26862
- if (state.closed) {
26863
- return void 0;
26864
- }
26850
+ const state = this.#getOrCreate(actorId);
26865
26851
  state.restart = restart;
26866
26852
  this.#initializeInspector(actorId, state);
26867
26853
  return (_a2 = state.inspector) == null ? void 0 : _a2.inspector;
26868
26854
  }
26869
- /**
26870
- * Closes the run state for `actorId`. With `actorGeneration`, only state owned by that
26871
- * generation is closed, so an older generation's late cleanup cannot close a newer one.
26872
- */
26873
- destroy(actorId, actorGeneration, options = {}) {
26855
+ destroy(actorId) {
26856
+ var _a2, _b;
26874
26857
  const state = this.#states.get(actorId);
26875
26858
  if (!state) return;
26876
- if (actorGeneration !== void 0 && state.actorGeneration !== void 0 && state.actorGeneration !== actorGeneration) {
26877
- return;
26878
- }
26879
- closeRunState(state, options.disposeInspector ?? true);
26859
+ state.closed = true;
26860
+ (_b = (_a2 = state.inspector) == null ? void 0 : _a2.dispose) == null ? void 0 : _b.call(_a2);
26861
+ state.inspector = void 0;
26862
+ notifyStateChanged(state);
26880
26863
  this.#states.delete(actorId);
26881
26864
  }
26882
26865
  #control(actorId, state) {
@@ -26922,20 +26905,18 @@ var RunHandlerCoordinator = class {
26922
26905
  }
26923
26906
  };
26924
26907
  }
26925
- #getOrCreate(actorId, actorGeneration) {
26908
+ #getOrCreate(actorId) {
26926
26909
  let state = this.#states.get(actorId);
26927
- if (state && actorGeneration !== void 0 && state.actorGeneration !== void 0 && state.actorGeneration !== actorGeneration) {
26928
- if (actorGeneration < state.actorGeneration) {
26929
- const detached = createRunState(actorGeneration);
26930
- detached.closed = true;
26931
- return detached;
26932
- }
26933
- closeRunState(state, false);
26934
- this.#states.delete(actorId);
26935
- state = void 0;
26936
- }
26937
26910
  if (!state) {
26938
- state = createRunState(actorGeneration);
26911
+ state = {
26912
+ active: false,
26913
+ closed: false,
26914
+ exclusive: false,
26915
+ exclusiveGeneration: 0,
26916
+ inspectorInitialized: false,
26917
+ queued: 0,
26918
+ waiters: /* @__PURE__ */ new Set()
26919
+ };
26939
26920
  this.#states.set(actorId, state);
26940
26921
  }
26941
26922
  return state;
@@ -26944,7 +26925,6 @@ var RunHandlerCoordinator = class {
26944
26925
  if (state.inspectorInitialized) return;
26945
26926
  const inspector = createRunInspector(this.#run, {
26946
26927
  actorId,
26947
- actorGeneration: state.actorGeneration,
26948
26928
  control: this.#control(actorId, state)
26949
26929
  });
26950
26930
  if (this.inspectorKind === "workflow") {
@@ -27270,12 +27250,6 @@ var WasmCoreRuntime = class {
27270
27250
  actorId(ctx) {
27271
27251
  return callHandle(asWasmActorContext(ctx), "actorId");
27272
27252
  }
27273
- actorGeneration(ctx) {
27274
- return callHandle(asWasmActorContext(ctx), "generation") ?? void 0;
27275
- }
27276
- actorIsLost(ctx) {
27277
- return callHandle(asWasmActorContext(ctx), "isLost");
27278
- }
27279
27253
  runWithActorInvocationContext(_ctx, run) {
27280
27254
  return run();
27281
27255
  }
@@ -28102,11 +28076,8 @@ async function cleanupNativeSleepRuntimeState(runtime, ctx, afterTrackedWorkDrai
28102
28076
  await closeNativeDatabaseClient(runtime, ctx);
28103
28077
  await closeNativeSqlDatabase(runtime, ctx);
28104
28078
  void runtime.actorWaitForTrackedShutdownWorkUnbounded(ctx).then(async () => {
28105
- try {
28106
- await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
28107
- } finally {
28108
- clearNativeRuntimeState(runtime, ctx);
28109
- }
28079
+ await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
28080
+ clearNativeRuntimeState(runtime, ctx);
28110
28081
  }).catch((error46) => {
28111
28082
  logger22().warn({
28112
28083
  msg: "deferred native sleep cleanup failed",
@@ -28115,24 +28086,10 @@ async function cleanupNativeSleepRuntimeState(runtime, ctx, afterTrackedWorkDrai
28115
28086
  });
28116
28087
  return;
28117
28088
  }
28118
- try {
28119
- await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
28120
- } finally {
28121
- try {
28122
- await closeNativeDatabaseClient(runtime, ctx);
28123
- await closeNativeSqlDatabase(runtime, ctx);
28124
- } finally {
28125
- clearNativeRuntimeState(runtime, ctx);
28126
- }
28127
- }
28128
- }
28129
- async function cleanupNativeLostRuntimeState(runtime, ctx) {
28089
+ await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
28130
28090
  await closeNativeDatabaseClient(runtime, ctx);
28131
- try {
28132
- await closeNativeSqlDatabase(runtime, ctx);
28133
- } finally {
28134
- clearNativeRuntimeState(runtime, ctx);
28135
- }
28091
+ await closeNativeSqlDatabase(runtime, ctx);
28092
+ clearNativeRuntimeState(runtime, ctx);
28136
28093
  }
28137
28094
  function closeNativeSqlDatabase(runtime, ctx) {
28138
28095
  const runtimeState = getNativeRuntimeState(runtime, ctx);
@@ -28150,9 +28107,6 @@ async function closeNativeDatabaseClient(runtime, ctx) {
28150
28107
  return;
28151
28108
  }
28152
28109
  runtimeState.databaseClient = void 0;
28153
- if (callNativeSync(() => runtime.actorIsLost(ctx))) {
28154
- return;
28155
- }
28156
28110
  if (entry.client && typeof entry.client === "object" && "close" in entry.client && typeof entry.client.close === "function") {
28157
28111
  await entry.client.close();
28158
28112
  }
@@ -28578,49 +28532,6 @@ function wrapNativeCallback(callback) {
28578
28532
  }
28579
28533
  };
28580
28534
  }
28581
- var LOST_GENERATION_CLEANUP_CALLBACKS = /* @__PURE__ */ new Set(["onSleep", "onDestroy"]);
28582
- function throwIfActorLost(runtime, ctx) {
28583
- if (callNativeSync(() => runtime.actorIsLost(ctx))) {
28584
- throw actorGenerationLostError();
28585
- }
28586
- }
28587
- function actorGenerationLostError() {
28588
- return new RivetError(
28589
- "actor",
28590
- "stopping",
28591
- "Actor generation was declared lost; it starts no new user callbacks."
28592
- );
28593
- }
28594
- function refuseCallbacksAfterLost(runtime, callbacks) {
28595
- const guard = (callback) => {
28596
- return async (...args) => {
28597
- var _a2;
28598
- const ctx = (_a2 = args[1]) == null ? void 0 : _a2.ctx;
28599
- if (ctx !== void 0 && callNativeSync(() => runtime.actorIsLost(ctx))) {
28600
- throw encodeNativeCallbackError(actorGenerationLostError());
28601
- }
28602
- return await callback(...args);
28603
- };
28604
- };
28605
- const guarded = {};
28606
- for (const [name, value] of Object.entries(callbacks)) {
28607
- if (LOST_GENERATION_CLEANUP_CALLBACKS.has(name)) {
28608
- guarded[name] = value;
28609
- } else if (typeof value === "function") {
28610
- guarded[name] = guard(value);
28611
- } else if (name === "actions" && value !== null && typeof value === "object") {
28612
- guarded[name] = Object.fromEntries(
28613
- Object.entries(value).map(([actionName, handler]) => [
28614
- actionName,
28615
- guard(handler)
28616
- ])
28617
- );
28618
- } else {
28619
- guarded[name] = value;
28620
- }
28621
- }
28622
- return guarded;
28623
- }
28624
28535
  function decodeArgs(value) {
28625
28536
  const decoded = decodeValue(value);
28626
28537
  return normalizeArgs(decoded);
@@ -29058,30 +28969,17 @@ var NativeQueueAdapter = class {
29058
28969
  this.#ctx = ctx;
29059
28970
  this.#schemas = schemas;
29060
28971
  }
29061
- // Queue results arrive after awaits, and their schema validation is user code, so each
29062
- // validation checks that the generation was not lost first.
29063
- #validateBody(name, body) {
29064
- throwIfActorLost(this.#runtime, this.#ctx);
29065
- return validateQueueBody(this.#schemas, name, body);
29066
- }
29067
- #validateComplete(name, response) {
29068
- throwIfActorLost(this.#runtime, this.#ctx);
29069
- return validateQueueComplete(this.#schemas, name, response);
29070
- }
29071
- #wrap(message) {
29072
- throwIfActorLost(this.#runtime, this.#ctx);
29073
- return wrapQueueMessage(message, this.#schemas);
29074
- }
29075
28972
  async send(name, body) {
29076
- const validatedBody = this.#validateBody(name, body);
29077
- return this.#wrap(
28973
+ const validatedBody = validateQueueBody(this.#schemas, name, body);
28974
+ return wrapQueueMessage(
29078
28975
  await callNative(
29079
28976
  () => this.#runtime.actorQueueSend(
29080
28977
  this.#ctx,
29081
28978
  name,
29082
28979
  encodeValue(validatedBody)
29083
28980
  )
29084
- )
28981
+ ),
28982
+ this.#schemas
29085
28983
  );
29086
28984
  }
29087
28985
  async next(options) {
@@ -29124,7 +29022,9 @@ var NativeQueueAdapter = class {
29124
29022
  token
29125
29023
  )
29126
29024
  );
29127
- const wrapped = messages.map((message) => this.#wrap(message));
29025
+ const wrapped = messages.map(
29026
+ (message) => wrapQueueMessage(message, this.#schemas)
29027
+ );
29128
29028
  return completable ? wrapped.map(
29129
29029
  (message) => this.#makeCompletableMessage(message)
29130
29030
  ) : wrapped;
@@ -29138,7 +29038,7 @@ var NativeQueueAdapter = class {
29138
29038
  options == null ? void 0 : options.signal
29139
29039
  );
29140
29040
  try {
29141
- return this.#wrap(
29041
+ return wrapQueueMessage(
29142
29042
  await callNative(
29143
29043
  () => this.#runtime.actorQueueWaitForNames(
29144
29044
  this.#ctx,
@@ -29149,7 +29049,8 @@ var NativeQueueAdapter = class {
29149
29049
  },
29150
29050
  token
29151
29051
  )
29152
- )
29052
+ ),
29053
+ this.#schemas
29153
29054
  );
29154
29055
  } finally {
29155
29056
  cleanup == null ? void 0 : cleanup();
@@ -29179,7 +29080,8 @@ var NativeQueueAdapter = class {
29179
29080
  await this.waitForNamesAvailable(names ?? [], options);
29180
29081
  }
29181
29082
  async complete(message, response) {
29182
- const validatedResponse = this.#validateComplete(
29083
+ const validatedResponse = validateQueueComplete(
29084
+ this.#schemas,
29183
29085
  message.name,
29184
29086
  response
29185
29087
  );
@@ -29194,7 +29096,7 @@ var NativeQueueAdapter = class {
29194
29096
  this.#pendingCompletableMessageIds.delete(message.id.toString());
29195
29097
  }
29196
29098
  async enqueueAndWait(name, body, options) {
29197
- const validatedBody = this.#validateBody(name, body);
29099
+ const validatedBody = validateQueueBody(this.#schemas, name, body);
29198
29100
  const { token, cleanup } = await createCancellationTokenHandle(
29199
29101
  this.#runtime,
29200
29102
  options == null ? void 0 : options.signal
@@ -29211,7 +29113,11 @@ var NativeQueueAdapter = class {
29211
29113
  token
29212
29114
  )
29213
29115
  );
29214
- return response === void 0 || response === null ? void 0 : this.#validateComplete(name, decodeValue(response));
29116
+ return response === void 0 || response === null ? void 0 : validateQueueComplete(
29117
+ this.#schemas,
29118
+ name,
29119
+ decodeValue(response)
29120
+ );
29215
29121
  } finally {
29216
29122
  cleanup == null ? void 0 : cleanup();
29217
29123
  }
@@ -29592,9 +29498,6 @@ var TrackedWebSocketHandleAdapter = class {
29592
29498
  }
29593
29499
  }
29594
29500
  #callHandler(type, handler, event2) {
29595
- if ((type === "message" || type === "open") && this.#ctx.isLost) {
29596
- return;
29597
- }
29598
29501
  try {
29599
29502
  const result = handler(event2);
29600
29503
  if (!this.#isPromiseLike(result)) {
@@ -29877,13 +29780,6 @@ var ActorContextHandleAdapter = class {
29877
29780
  get actorId() {
29878
29781
  return callNativeSync(() => this.#runtime.actorId(this.#ctx));
29879
29782
  }
29880
- get actorGeneration() {
29881
- return callNativeSync(() => this.#runtime.actorGeneration(this.#ctx));
29882
- }
29883
- /** Whether this generation was declared lost. A lost generation starts no new user code. */
29884
- get isLost() {
29885
- return callNativeSync(() => this.#runtime.actorIsLost(this.#ctx));
29886
- }
29887
29783
  get name() {
29888
29784
  return callNativeSync(() => this.#runtime.actorName(this.#ctx));
29889
29785
  }
@@ -29998,9 +29894,6 @@ var ActorContextHandleAdapter = class {
29998
29894
  return this.#db;
29999
29895
  }
30000
29896
  const actorId = this.actorId;
30001
- if (this.isLost) {
30002
- throw actorGenerationLostError();
30003
- }
30004
29897
  const createdClient = await this.#databaseProvider.createClient({
30005
29898
  actorId,
30006
29899
  kv: {
@@ -30153,11 +30046,9 @@ var ActorContextHandleAdapter = class {
30153
30046
  if (!this.#databaseProvider) {
30154
30047
  return;
30155
30048
  }
30156
- const client = await this.ensureDatabaseClient();
30157
- if (this.isLost) {
30158
- throw actorGenerationLostError();
30159
- }
30160
- await this.#databaseProvider.onMigrate(client);
30049
+ await this.#databaseProvider.onMigrate(
30050
+ await this.ensureDatabaseClient()
30051
+ );
30161
30052
  }
30162
30053
  async closeDatabase() {
30163
30054
  this.#db = void 0;
@@ -30429,7 +30320,7 @@ var ActorContextHandleAdapter = class {
30429
30320
  callNativeSync(
30430
30321
  () => this.#runtime.actorRequestSave(this.#ctx, { immediate: false })
30431
30322
  );
30432
- if (!this.#onStateChange || this.isLost) {
30323
+ if (!this.#onStateChange) {
30433
30324
  return;
30434
30325
  }
30435
30326
  actorState.isInOnStateChange = true;
@@ -30469,12 +30360,6 @@ var NativeWorkflowRuntimeAdapter = class {
30469
30360
  #onMessagesReceived;
30470
30361
  #completions = /* @__PURE__ */ new Map();
30471
30362
  id;
30472
- /** Actor generation, used to keep workflow registrations of different generations apart. */
30473
- generation;
30474
- /** Whether this generation was declared lost. Workflow code checks it before each user callback. */
30475
- get isLost() {
30476
- return this.#ctx.isLost;
30477
- }
30478
30363
  driver;
30479
30364
  queueManager;
30480
30365
  stateManager;
@@ -30482,7 +30367,6 @@ var NativeWorkflowRuntimeAdapter = class {
30482
30367
  this.#ctx = ctx;
30483
30368
  this.#onMessagesReceived = onMessagesReceived;
30484
30369
  this.id = ctx.actorId;
30485
- this.generation = ctx.actorGeneration;
30486
30370
  this.driver = {
30487
30371
  kvBatchGet: async (actorId, keys) => {
30488
30372
  this.#assertActorId(actorId);
@@ -30765,23 +30649,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
30765
30649
  const runHandlerCoordinator = getRunInspectorKind(config3.run) === "workflow" ? new RunHandlerCoordinator(config3.run) : void 0;
30766
30650
  const getNativeWorkflowInspector = (ctx) => {
30767
30651
  var _a22, _b;
30768
- if (callNativeSync(() => runtime.actorIsLost(ctx))) {
30769
- return void 0;
30770
- }
30771
30652
  const actorId = callNativeSync(() => runtime.actorId(ctx));
30772
30653
  const restart = () => callNativeSync(() => runtime.actorRestartRunHandler(ctx));
30773
- const actorGeneration = callNativeSync(
30774
- () => runtime.actorGeneration(ctx)
30775
- );
30776
- const inspector = ((_a22 = runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.getInspector(
30777
- actorId,
30778
- restart,
30779
- actorGeneration
30780
- )) == null ? void 0 : _a22.workflow) ?? ((_b = getRunInspectorConfig(config3.run, actorId)) == null ? void 0 : _b.workflow);
30781
- if (callNativeSync(() => runtime.actorIsLost(ctx))) {
30782
- return void 0;
30783
- }
30784
- return inspector;
30654
+ 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);
30785
30655
  };
30786
30656
  const onStateChange = typeof config3.onStateChange === "function" ? (actorCtx, nextState) => {
30787
30657
  config3.onStateChange(actorCtx, nextState);
@@ -30858,10 +30728,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
30858
30728
  return errorResponse(error46, 401);
30859
30729
  }
30860
30730
  }
30861
- const inspectorConnParams = (conn) => {
30862
- throwIfActorLost(runtime, ctx);
30863
- return conn.params;
30864
- };
30865
30731
  const workflowHistory = () => {
30866
30732
  var _a3;
30867
30733
  return serializeWorkflowHistoryForJson(
@@ -30895,7 +30761,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
30895
30761
  id: conn.id,
30896
30762
  details: {
30897
30763
  type: null,
30898
- params: inspectorConnParams(conn),
30764
+ params: conn.params,
30899
30765
  stateEnabled: true,
30900
30766
  state: conn.state,
30901
30767
  subscriptions: 0,
@@ -31099,7 +30965,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31099
30965
  id: conn.id,
31100
30966
  details: {
31101
30967
  type: null,
31102
- params: inspectorConnParams(conn),
30968
+ params: conn.params,
31103
30969
  stateEnabled: true,
31104
30970
  state: conn.state,
31105
30971
  subscriptions: 0,
@@ -31146,20 +31012,15 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31146
31012
  );
31147
31013
  }
31148
31014
  const args = body.properties !== void 0 ? [body.properties] : normalizeArgs(body.args);
31149
- if (callNativeSync(() => runtime.actorIsLost(ctx))) {
31150
- return jsonResponse(
31151
- { error: "actor generation was declared lost" },
31152
- { status: 503 }
31153
- );
31154
- }
31155
31015
  try {
31156
- const validatedArgs = validateActionArgs(
31157
- schemaConfig.actionInputSchemas,
31158
- actionName,
31159
- args
31016
+ const output = await action(
31017
+ actorCtx,
31018
+ ...validateActionArgs(
31019
+ schemaConfig.actionInputSchemas,
31020
+ actionName,
31021
+ args
31022
+ )
31160
31023
  );
31161
- throwIfActorLost(runtime, ctx);
31162
- const output = await action(actorCtx, ...validatedArgs);
31163
31024
  return jsonResponse({ output });
31164
31025
  } catch (error46) {
31165
31026
  logger22().error({
@@ -31263,9 +31124,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31263
31124
  await actorCtx.closeDatabase();
31264
31125
  }
31265
31126
  await actorCtx.runDatabaseMigrations();
31266
- if (typeof config3.onMigrate === "function" && !callNativeSync(
31267
- () => runtime.actorIsLost(ctx)
31268
- )) {
31127
+ if (typeof config3.onMigrate === "function") {
31269
31128
  await config3.onMigrate(actorCtx, isNew);
31270
31129
  }
31271
31130
  } catch (error210) {
@@ -31308,29 +31167,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31308
31167
  const { ctx } = unwrapTsfnPayload(error46, payload);
31309
31168
  const actorCtx = makeActorCtx(ctx);
31310
31169
  const actorId = callNativeSync(() => runtime.actorId(ctx));
31311
- const actorGeneration = callNativeSync(
31312
- () => runtime.actorGeneration(ctx)
31313
- );
31314
- const isLost = () => callNativeSync(() => runtime.actorIsLost(ctx));
31315
- if (isLost()) {
31316
- try {
31317
- await cleanupNativeLostRuntimeState(runtime, ctx);
31318
- } finally {
31319
- runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(
31320
- actorId,
31321
- actorGeneration,
31322
- {
31323
- disposeInspector: false
31324
- }
31325
- );
31326
- await actorCtx.dispose();
31327
- }
31328
- return;
31329
- }
31330
31170
  const saveActorState = async () => {
31331
- if (isLost()) {
31332
- return;
31333
- }
31334
31171
  if (runtime.kind === "wasm") {
31335
31172
  await runtime.actorSaveState(
31336
31173
  ctx,
@@ -31349,26 +31186,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31349
31186
  await saveActorState();
31350
31187
  } finally {
31351
31188
  try {
31352
- if (isLost()) {
31353
- await cleanupNativeLostRuntimeState(runtime, ctx);
31354
- } else {
31355
- await cleanupNativeSleepRuntimeState(
31356
- runtime,
31357
- ctx,
31358
- saveActorState
31359
- );
31360
- }
31361
- } finally {
31362
- runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(
31363
- actorId,
31364
- actorGeneration,
31365
- {
31366
- disposeInspector: !isLost()
31367
- }
31189
+ await cleanupNativeSleepRuntimeState(
31190
+ runtime,
31191
+ ctx,
31192
+ saveActorState
31368
31193
  );
31369
- if (!isLost()) {
31370
- disposeRunInspector(config3.run, actorId);
31371
- }
31194
+ } finally {
31195
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
31196
+ disposeRunInspector(config3.run, actorId);
31372
31197
  await actorCtx.dispose();
31373
31198
  }
31374
31199
  }
@@ -31379,17 +31204,10 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31379
31204
  const { ctx } = unwrapTsfnPayload(error46, payload);
31380
31205
  const actorCtx = makeActorCtx(ctx);
31381
31206
  const actorId = callNativeSync(() => runtime.actorId(ctx));
31382
- const isLost = () => callNativeSync(() => runtime.actorIsLost(ctx));
31383
- runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(
31384
- actorId,
31385
- callNativeSync(() => runtime.actorGeneration(ctx)),
31386
- { disposeInspector: !isLost() }
31387
- );
31388
- if (!isLost()) {
31389
- disposeRunInspector(config3.run, actorId);
31390
- }
31207
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
31208
+ disposeRunInspector(config3.run, actorId);
31391
31209
  try {
31392
- if (typeof config3.onDestroy === "function" && !isLost()) {
31210
+ if (typeof config3.onDestroy === "function") {
31393
31211
  await config3.onDestroy(actorCtx);
31394
31212
  }
31395
31213
  } finally {
@@ -31411,14 +31229,12 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31411
31229
  request ? buildNativeHttpRequest(request) : void 0
31412
31230
  );
31413
31231
  try {
31414
- const validatedParams = validateConnParams(
31415
- schemaConfig.connParamsSchema,
31416
- decodeValue(params)
31417
- );
31418
- throwIfActorLost(runtime, ctx);
31419
31232
  await config3.onBeforeConnect(
31420
31233
  actorCtx,
31421
- validatedParams
31234
+ validateConnParams(
31235
+ schemaConfig.connParamsSchema,
31236
+ decodeValue(params)
31237
+ )
31422
31238
  );
31423
31239
  } finally {
31424
31240
  await actorCtx.dispose();
@@ -31446,22 +31262,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31446
31262
  () => actorCtx.assertCanMutateState()
31447
31263
  );
31448
31264
  try {
31449
- let nextConnState;
31450
- if (hasStaticConnState) {
31451
- nextConnState = structuredClone(
31452
- config3.connState
31453
- );
31454
- } else {
31455
- const validatedParams = validateConnParams(
31265
+ const nextConnState = hasStaticConnState ? structuredClone(config3.connState) : await config3.createConnState(
31266
+ actorCtx,
31267
+ validateConnParams(
31456
31268
  schemaConfig.connParamsSchema,
31457
31269
  decodeValue(params)
31458
- );
31459
- throwIfActorLost(runtime, ctx);
31460
- nextConnState = await config3.createConnState(
31461
- actorCtx,
31462
- validatedParams
31463
- );
31464
- }
31270
+ )
31271
+ );
31465
31272
  connAdapter.initializeState(nextConnState);
31466
31273
  return encodeValue(nextConnState);
31467
31274
  } finally {
@@ -31566,9 +31373,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31566
31373
  onBeforeActionResponse: typeof config3.onBeforeActionResponse === "function" ? wrapNativeCallback(
31567
31374
  async (error46, payload) => {
31568
31375
  const { ctx, name, args, output } = unwrapTsfnPayload(error46, payload);
31569
- if (callNativeSync(() => runtime.actorIsLost(ctx))) {
31570
- return output;
31571
- }
31572
31376
  const actorCtx = makeActorCtx(ctx);
31573
31377
  try {
31574
31378
  return encodeValue(
@@ -31637,7 +31441,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31637
31441
  }
31638
31442
  };
31639
31443
  try {
31640
- throwIfActorLost(runtime, ctx);
31641
31444
  const connParams = validateConnParams(
31642
31445
  schemaConfig.connParamsSchema,
31643
31446
  rawConnParams ? JSON.parse(rawConnParams) : void 0
@@ -31672,11 +31475,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31672
31475
  abortRequest
31673
31476
  );
31674
31477
  }
31675
- if (callNativeSync(
31676
- () => runtime.actorIsLost(ctx)
31677
- )) {
31678
- throw actorGenerationLostError();
31679
- }
31680
31478
  const response = await config3.onRequest(
31681
31479
  requestCtx,
31682
31480
  handlerRequest
@@ -31749,9 +31547,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31749
31547
  const { ctx } = unwrapTsfnPayload(error46, payload);
31750
31548
  const actorId = callNativeSync(() => runtime.actorId(ctx));
31751
31549
  const executeRun = async () => {
31752
- if (callNativeSync(() => runtime.actorIsLost(ctx))) {
31753
- return;
31754
- }
31755
31550
  const actorCtx = makeActorCtx(ctx);
31756
31551
  try {
31757
31552
  await run(actorCtx);
@@ -31765,8 +31560,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31765
31560
  () => callNativeSync(
31766
31561
  () => runtime.actorRestartRunHandler(ctx)
31767
31562
  ),
31768
- executeRun,
31769
- callNativeSync(() => runtime.actorGeneration(ctx))
31563
+ executeRun
31770
31564
  );
31771
31565
  return outcome !== "suppressed";
31772
31566
  }
@@ -31806,16 +31600,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31806
31600
  const actorCtx = conn != null ? makeConnCtx(ctx, conn, void 0, cancelToken) : makeActorCtx(ctx, void 0, cancelToken);
31807
31601
  const runAction = async () => {
31808
31602
  try {
31809
- const validatedArgs = validateActionArgs(
31810
- schemaConfig.actionInputSchemas,
31811
- name,
31812
- decodeArgs(args)
31813
- );
31814
- throwIfActorLost(runtime, ctx);
31815
31603
  return encodeValue(
31816
31604
  await handler(
31817
31605
  actorCtx,
31818
- ...validatedArgs,
31606
+ ...validateActionArgs(
31607
+ schemaConfig.actionInputSchemas,
31608
+ name,
31609
+ decodeArgs(args)
31610
+ ),
31819
31611
  ...scheduledFire ? [scheduledFire] : []
31820
31612
  )
31821
31613
  );
@@ -31871,7 +31663,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31871
31663
  if (canPublish && !await canPublish(actorCtx)) {
31872
31664
  throw forbiddenError();
31873
31665
  }
31874
- throwIfActorLost(runtime, ctx);
31875
31666
  const decodedBody = decodeValue(body);
31876
31667
  if (wait) {
31877
31668
  try {
@@ -31915,7 +31706,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
31915
31706
  )
31916
31707
  };
31917
31708
  return runtime.createActorFactory(
31918
- refuseCallbacksAfterLost(runtime, callbacks),
31709
+ callbacks,
31919
31710
  buildActorConfig(definition, registryConfig, runtime.kind)
31920
31711
  );
31921
31712
  }