@rivetkit/supabase 2.3.12-rc.4 → 2.3.13

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 +359 -123
  2. package/dist/mod.mjs +359 -123
  3. package/package.json +3 -3
package/dist/mod.mjs CHANGED
@@ -297,7 +297,7 @@ var require_retry2 = __commonJS({
297
297
  // src/mod.ts
298
298
  import * as wasmBindings from "@rivetkit/rivetkit-wasm";
299
299
 
300
- // ../rivetkit/dist/tsup/chunk-IXBD7BXC.js
300
+ // ../rivetkit/dist/tsup/chunk-OUQUIBVW.js
301
301
  var INTERNAL_ERROR_CODE = "internal_error";
302
302
  var INTERNAL_ERROR_DESCRIPTION = "An internal error occurred";
303
303
  var USER_ERROR_CODE = "user_error";
@@ -481,7 +481,7 @@ function unsupportedFeature(feature) {
481
481
  );
482
482
  }
483
483
 
484
- // ../rivetkit/dist/tsup/chunk-64DT44V2.js
484
+ // ../rivetkit/dist/tsup/chunk-UZWKXBMV.js
485
485
  import {
486
486
  pino,
487
487
  stdTimeFunctions
@@ -13157,7 +13157,7 @@ var classic_default = external_exports;
13157
13157
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/index.js
13158
13158
  var v4_default = classic_default;
13159
13159
 
13160
- // ../rivetkit/dist/tsup/chunk-64DT44V2.js
13160
+ // ../rivetkit/dist/tsup/chunk-UZWKXBMV.js
13161
13161
  var import_invariant = __toESM(require_invariant(), 1);
13162
13162
  import * as cbor from "cbor-x";
13163
13163
  var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
@@ -13176,6 +13176,10 @@ var getRivetRunEnginePort = () => {
13176
13176
  return value !== void 0 ? parseInt(value, 10) : void 0;
13177
13177
  };
13178
13178
  var getRivetRunEngineVersion = () => getEnvUniversal("RIVET_RUN_ENGINE_VERSION");
13179
+ var getRivetRunServices = () => {
13180
+ const value = getEnvUniversal("RIVET_RUN_SERVICES");
13181
+ return value === void 0 ? void 0 : value === "1";
13182
+ };
13179
13183
  var getRivetEnvoyVersion = () => {
13180
13184
  const value = getEnvUniversal("RIVET_ENVOY_VERSION");
13181
13185
  return value !== void 0 ? parseInt(value, 10) : void 0;
@@ -13327,7 +13331,7 @@ function noopNext() {
13327
13331
  }
13328
13332
  var package_default = {
13329
13333
  name: "rivetkit",
13330
- version: "2.3.12-rc.4",
13334
+ version: "2.3.13",
13331
13335
  description: "Lightweight libraries for building stateful actors on edge platforms",
13332
13336
  license: "Apache-2.0",
13333
13337
  keywords: [
@@ -13537,6 +13541,7 @@ var package_default = {
13537
13541
  dependencies: {
13538
13542
  "@hono/zod-openapi": "^1.1.5",
13539
13543
  "@rivet-dev/agent-os-core": "^0.1.1",
13544
+ "@rivet-dev/services": "^0.1.5",
13540
13545
  "@rivetkit/bare-ts": "^0.6.2",
13541
13546
  "@rivetkit/engine-cli": "workspace:*",
13542
13547
  "@rivetkit/engine-envoy-protocol": "workspace:*",
@@ -14630,7 +14635,7 @@ function Config({ initialBufferLength = 1024, maxBufferLength = 1024 * 1024 * 32
14630
14635
  };
14631
14636
  }
14632
14637
 
14633
- // ../rivetkit/dist/tsup/chunk-BQ7YJ3PG.js
14638
+ // ../rivetkit/dist/tsup/chunk-UQINOZ6M.js
14634
14639
  var config2 = /* @__PURE__ */ Config({});
14635
14640
  function readWorkflowCbor(bc) {
14636
14641
  return readData(bc);
@@ -14928,7 +14933,7 @@ function decodeWorkflowHistoryTransport(data) {
14928
14933
  return decodeWorkflowHistory(toUint8Array(data));
14929
14934
  }
14930
14935
 
14931
- // ../rivetkit/dist/tsup/chunk-DLQSZ6Q7.js
14936
+ // ../rivetkit/dist/tsup/chunk-6W5VGLFT.js
14932
14937
  function flattenActionHandlers(actions) {
14933
14938
  const flattened = /* @__PURE__ */ Object.create(null);
14934
14939
  for (const { name, handler } of collectActionEntries(actions)) {
@@ -15010,7 +15015,6 @@ function formatActionPath(path2) {
15010
15015
  return path2.length === 0 ? "actions" : `Action \`${path2.join(".")}\``;
15011
15016
  }
15012
15017
  var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
15013
- var DEFAULT_MAX_ACTIONS = 128;
15014
15018
  var ACTOR_CONTEXT_INTERNAL_SYMBOL = /* @__PURE__ */ Symbol(
15015
15019
  "rivetkit.actor_context_internal"
15016
15020
  );
@@ -15177,8 +15181,6 @@ var GlobalActorOptionsBaseSchema = external_exports.object({
15177
15181
  name: external_exports.string().optional(),
15178
15182
  /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
15179
15183
  icon: external_exports.string().optional(),
15180
- /** Maximum number of action handlers that may be defined on this actor. */
15181
- maxActions: external_exports.number().int().nonnegative().default(DEFAULT_MAX_ACTIONS),
15182
15184
  /** Enables the experimental Actor Runtime Socket for this actor. */
15183
15185
  enableActorRuntimeSocket: external_exports.boolean().default(false),
15184
15186
  /**
@@ -15270,26 +15272,12 @@ var ActorConfigSchema = external_exports.object({
15270
15272
  message: "Cannot define both 'vars' and 'createVars'",
15271
15273
  path: ["vars"]
15272
15274
  }
15273
- ).superRefine((data, ctx) => {
15274
- const actionCount = Object.keys(
15275
- flattenActionHandlers(data.actions)
15276
- ).length;
15277
- if (actionCount > data.options.maxActions) {
15278
- ctx.addIssue({
15279
- code: "custom",
15280
- message: `Actor defines ${actionCount} actions, but maxActions is ${data.options.maxActions}`,
15281
- path: ["actions"]
15282
- });
15283
- }
15284
- });
15275
+ );
15285
15276
  var DocActorOptionsSchema = external_exports.object({
15286
15277
  name: external_exports.string().optional().describe("Display name for the actor in the Inspector UI."),
15287
15278
  icon: external_exports.string().optional().describe(
15288
15279
  "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
15289
15280
  ),
15290
- maxActions: external_exports.number().int().nonnegative().optional().describe(
15291
- `Maximum number of action handlers that may be defined on this actor. Default: ${DEFAULT_MAX_ACTIONS}`
15292
- ),
15293
15281
  enableActorRuntimeSocket: external_exports.boolean().optional().describe(
15294
15282
  "Enables the experimental Actor Runtime Socket for this actor. Default: false"
15295
15283
  ),
@@ -15609,7 +15597,7 @@ var AsyncMutex = class {
15609
15597
  }
15610
15598
  };
15611
15599
 
15612
- // ../rivetkit/dist/tsup/chunk-NVMHEG5J.js
15600
+ // ../rivetkit/dist/tsup/chunk-AS47KFZD.js
15613
15601
  function logger() {
15614
15602
  return getLogger("actor-client");
15615
15603
  }
@@ -15647,7 +15635,7 @@ async function importWebSocket() {
15647
15635
  return webSocketPromise;
15648
15636
  }
15649
15637
 
15650
- // ../rivetkit/dist/tsup/chunk-O74736N5.js
15638
+ // ../rivetkit/dist/tsup/chunk-RZPPOGEQ.js
15651
15639
  var import_invariant2 = __toESM(require_invariant(), 1);
15652
15640
 
15653
15641
  // ../../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
@@ -15825,7 +15813,7 @@ function createVersionedDataHandler(config3) {
15825
15813
  return new VersionedDataHandler(config3);
15826
15814
  }
15827
15815
 
15828
- // ../rivetkit/dist/tsup/chunk-O74736N5.js
15816
+ // ../rivetkit/dist/tsup/chunk-RZPPOGEQ.js
15829
15817
  var import_invariant3 = __toESM(require_invariant(), 1);
15830
15818
  var import_invariant4 = __toESM(require_invariant(), 1);
15831
15819
  var PATH_CONNECT = "/connect";
@@ -15834,6 +15822,7 @@ var PATH_WEBSOCKET_PREFIX = "/websocket/";
15834
15822
  var HEADER_ACTOR_QUERY = "x-rivet-query";
15835
15823
  var HEADER_ENCODING = "x-rivet-encoding";
15836
15824
  var HEADER_CONN_PARAMS = "x-rivet-conn-params";
15825
+ var HEADER_ORIGINAL_REQUEST_URL = "x-rivet-internal-original-request-url";
15837
15826
  var HEADER_ACTOR_ID = "x-rivet-actor";
15838
15827
  var HEADER_ACTOR_GENERATION = "x-rivet-actor-generation";
15839
15828
  var HEADER_ACTOR_KEY = "x-rivet-actor-key";
@@ -17892,6 +17881,18 @@ async function checkForSchedulingError(group, code, actorId, query, driver, rayI
17892
17881
  }
17893
17882
  return null;
17894
17883
  }
17884
+ function isUrlLike(value) {
17885
+ return typeof value === "object" && value !== null && typeof value.href === "string" && typeof value.pathname === "string" && typeof value.search === "string";
17886
+ }
17887
+ function isRequestLike(value) {
17888
+ return typeof value === "object" && value !== null && typeof value.url === "string" && typeof value.method === "string" && isHeadersLike(value.headers);
17889
+ }
17890
+ function isResponseLike(value) {
17891
+ return typeof value === "object" && value !== null && typeof value.status === "number" && isHeadersLike(value.headers) && typeof value.arrayBuffer === "function";
17892
+ }
17893
+ function isHeadersLike(value) {
17894
+ return typeof value === "object" && value !== null && typeof value.entries === "function";
17895
+ }
17895
17896
  function* walkErrorChain(error46, maxDepth = 8) {
17896
17897
  let current = error46;
17897
17898
  let depth = 0;
@@ -18317,28 +18318,19 @@ function createQueueSender(senderOptions) {
18317
18318
  send
18318
18319
  };
18319
18320
  }
18320
- function isUrlLike(value) {
18321
- return typeof value === "object" && value !== null && typeof value.href === "string" && typeof value.pathname === "string" && typeof value.search === "string";
18322
- }
18323
- function isRequestLike(value) {
18324
- return typeof value === "object" && value !== null && typeof value.url === "string" && typeof value.method === "string" && isHeadersLike(value.headers);
18325
- }
18326
- function isResponseLike(value) {
18327
- return typeof value === "object" && value !== null && typeof value.status === "number" && isHeadersLike(value.headers) && typeof value.arrayBuffer === "function";
18328
- }
18329
- function isHeadersLike(value) {
18330
- return typeof value === "object" && value !== null && typeof value.entries === "function";
18331
- }
18332
18321
  async function rawHttpFetch(driver, target, params, input, init, options = {}) {
18333
18322
  let path2;
18323
+ let originalUrl;
18334
18324
  let mergedInit = init || {};
18335
18325
  if (typeof input === "string") {
18336
18326
  path2 = input;
18337
18327
  } else if (isUrlLike(input)) {
18338
18328
  path2 = input.pathname + input.search;
18329
+ originalUrl = input.toString();
18339
18330
  } else if (isRequestLike(input)) {
18340
18331
  const url2 = new URL(input.url);
18341
18332
  path2 = url2.pathname + url2.search;
18333
+ originalUrl = url2.toString();
18342
18334
  const requestHeaders = new Headers(input.headers);
18343
18335
  const initHeaders = new Headers((init == null ? void 0 : init.headers) || {});
18344
18336
  const mergedHeaders = new Headers(requestHeaders);
@@ -18380,6 +18372,10 @@ async function rawHttpFetch(driver, target, params, input, init, options = {}) {
18380
18372
  const normalizedPath = path2.startsWith("/") ? path2.slice(1) : path2;
18381
18373
  const url2 = new URL(`http://actor/request/${normalizedPath}`);
18382
18374
  const proxyRequestHeaders = new Headers(mergedInit.headers);
18375
+ proxyRequestHeaders.delete(HEADER_ORIGINAL_REQUEST_URL);
18376
+ if (originalUrl) {
18377
+ proxyRequestHeaders.set(HEADER_ORIGINAL_REQUEST_URL, originalUrl);
18378
+ }
18383
18379
  if (params) {
18384
18380
  proxyRequestHeaders.set(HEADER_CONN_PARAMS, JSON.stringify(params));
18385
18381
  }
@@ -18505,7 +18501,9 @@ var ActorHandleRaw = class {
18505
18501
  async #sendQueueMessage(name, body, options) {
18506
18502
  return await this.#queueSendMutex.run(async () => {
18507
18503
  const maxAttempts = this.#getDynamicQueryMaxAttempts();
18508
- let useQueryTarget = isDynamicActorQuery(this.#actorResolutionState);
18504
+ let useQueryTarget = isDynamicActorQuery(
18505
+ this.#actorResolutionState
18506
+ );
18509
18507
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
18510
18508
  let actorId;
18511
18509
  try {
@@ -18854,9 +18852,10 @@ var ActorHandleRaw = class {
18854
18852
  return this.#fetchWithResolvedActor(input, init);
18855
18853
  }
18856
18854
  async #fetchWithResolvedActor(input, init) {
18857
- const maxAttempts = this.#getDynamicQueryMaxAttempts();
18858
- let useQueryTarget = isDynamicActorQuery(this.#actorResolutionState);
18859
18855
  const { skipReadyWait, ...requestInit } = init ?? {};
18856
+ const hasBody = requestInit.body !== void 0 ? requestInit.body !== null : isRequestLike(input) && input.body !== null;
18857
+ const maxAttempts = hasBody ? 1 : this.#getDynamicQueryMaxAttempts();
18858
+ let useQueryTarget = isDynamicActorQuery(this.#actorResolutionState);
18860
18859
  const gatewayOptions = resolveActorGatewayOptions(
18861
18860
  this.#gatewayOptions,
18862
18861
  {
@@ -20624,23 +20623,19 @@ async function sendHttpRequestToGateway(runConfig, gatewayUrl, actorRequest, opt
20624
20623
  if (actorRequest.bodyUsed) {
20625
20624
  throw new Error("Request body has already been consumed");
20626
20625
  }
20627
- const reqBody = await actorRequest.arrayBuffer();
20628
- if (reqBody.byteLength !== 0) {
20629
- bodyToSend = reqBody;
20626
+ if (actorRequest.body) {
20627
+ bodyToSend = actorRequest.body;
20630
20628
  guardHeaders.delete("transfer-encoding");
20631
20629
  guardHeaders.delete("content-length");
20632
20630
  }
20633
20631
  }
20634
- const guardRequest = new Request(gatewayUrl, {
20632
+ return fetch(gatewayUrl, {
20635
20633
  method: actorRequest.method,
20636
20634
  headers: guardHeaders,
20637
20635
  body: bodyToSend,
20638
- signal: actorRequest.signal
20636
+ signal: actorRequest.signal,
20637
+ ...bodyToSend ? { duplex: "half" } : {}
20639
20638
  });
20640
- return mutableResponse(await fetch(guardRequest));
20641
- }
20642
- function mutableResponse(fetchRes) {
20643
- return new Response(fetchRes.body, fetchRes);
20644
20639
  }
20645
20640
  function buildGuardHeaders(runConfig, actorRequest, options) {
20646
20641
  const headers = new Headers();
@@ -21590,7 +21585,7 @@ function apiActorToOutput(actor2) {
21590
21585
  };
21591
21586
  }
21592
21587
 
21593
- // ../rivetkit/dist/tsup/chunk-AF2VKCFA.js
21588
+ // ../rivetkit/dist/tsup/chunk-2EV7TJGB.js
21594
21589
  var nativeStateTransactionOpeners = /* @__PURE__ */ new WeakMap();
21595
21590
  var nativeStateTransactionClientBinders = /* @__PURE__ */ new WeakMap();
21596
21591
  function registerNativeStateTransactionOpener(provider, opener) {
@@ -23666,6 +23661,12 @@ var RegistryConfigSchema = external_exports.object({
23666
23661
  enginePort: external_exports.number().int().min(1).max(65535).optional().default(() => getRivetRunEnginePort() ?? ENGINE_PORT),
23667
23662
  /** @experimental */
23668
23663
  engineVersion: external_exports.string().optional().default(() => getRivetRunEngineVersion() ?? VERSION),
23664
+ /**
23665
+ * Starts the first-party Services actor host when RivetKit manages
23666
+ * a local engine. Defaults to the local-engine decision. Set
23667
+ * RIVET_RUN_SERVICES=0 or 1 to override it.
23668
+ */
23669
+ startServices: external_exports.boolean().optional(),
23669
23670
  /**
23670
23671
  * @experimental
23671
23672
  *
@@ -23746,6 +23747,7 @@ var RegistryConfigSchema = external_exports.object({
23746
23747
  config3.enginePort
23747
23748
  );
23748
23749
  const endpoint = config3.startEngine ? localEngineEndpoint : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? localEngineEndpoint : void 0);
23750
+ const startServices = config3.startServices ?? getRivetRunServices() ?? Boolean(endpoint && isLocalEngineEndpoint(endpoint));
23749
23751
  const validateServerlessEndpoint = Boolean(
23750
23752
  config3.startEngine || parsedEndpoint
23751
23753
  );
@@ -23769,6 +23771,7 @@ var RegistryConfigSchema = external_exports.object({
23769
23771
  ...config3,
23770
23772
  sqlite,
23771
23773
  endpoint,
23774
+ startServices,
23772
23775
  namespace,
23773
23776
  token,
23774
23777
  publicEndpoint,
@@ -23882,6 +23885,9 @@ var DocRegistryConfigSchema = external_exports.object({
23882
23885
  engineVersion: external_exports.string().optional().describe(
23883
23886
  "Version of the local engine package to use. Defaults to the current RivetKit version."
23884
23887
  ),
23888
+ startServices: external_exports.boolean().optional().describe(
23889
+ "Starts Services when RivetKit manages a local Engine. Defaults to the local-Engine decision. Set RIVET_RUN_SERVICES=0 or 1 to override."
23890
+ ),
23885
23891
  configurePool: DocConfigurePoolSchema.describe(
23886
23892
  "Automatically configure serverless runners in the engine."
23887
23893
  ),
@@ -24391,16 +24397,30 @@ function toNapiApplication(application) {
24391
24397
  if (!request) {
24392
24398
  throw new Error("application fetch callback received no request");
24393
24399
  }
24394
- const response = await application({
24395
- ...request,
24396
- body: new Uint8Array(request.body)
24397
- });
24400
+ const response = await application(
24401
+ {
24402
+ ...request,
24403
+ body: new Uint8Array(request.body),
24404
+ cancelToken: request.cancelToken
24405
+ },
24406
+ request.responseBodyStream ? fromNapiHttpResponseBodyStream(
24407
+ request.responseBodyStream
24408
+ ) : void 0
24409
+ );
24398
24410
  return {
24399
24411
  ...response,
24400
- body: toNapiBuffer(response.body)
24412
+ body: response.body === void 0 ? void 0 : toNapiBuffer(response.body)
24401
24413
  };
24402
24414
  };
24403
24415
  }
24416
+ function fromNapiHttpResponseBodyStream(stream) {
24417
+ return {
24418
+ cancelled: () => stream.cancelled(),
24419
+ write: (chunk) => stream.write(Buffer.from(chunk)),
24420
+ end: () => stream.end(),
24421
+ error: (message) => stream.error(message)
24422
+ };
24423
+ }
24404
24424
  function toNapiHttpRequest(request) {
24405
24425
  if (!request) {
24406
24426
  return request;
@@ -24943,6 +24963,147 @@ async function loadNapiRuntime() {
24943
24963
  runtime: new NapiCoreRuntime(bindings)
24944
24964
  };
24945
24965
  }
24966
+ var HTTP_BODY_CHUNK_SIZE = 64 * 1024;
24967
+ function runtimeBytesToArrayBuffer(value) {
24968
+ return value.buffer.slice(
24969
+ value.byteOffset,
24970
+ value.byteOffset + value.byteLength
24971
+ );
24972
+ }
24973
+ function buildNativeHttpRequest(init) {
24974
+ var _a2;
24975
+ const headers = new Headers(init.headers);
24976
+ const originalUrl = headers.get(HEADER_ORIGINAL_REQUEST_URL);
24977
+ headers.delete(HEADER_ORIGINAL_REQUEST_URL);
24978
+ const url2 = originalUrl ?? (init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString());
24979
+ const method2 = init.method.toUpperCase();
24980
+ const bodyForbidden = method2 === "GET" || method2 === "HEAD";
24981
+ const body = bodyForbidden ? void 0 : init.bodyStream ? new ReadableStream({
24982
+ async pull(controller) {
24983
+ var _a22, _b;
24984
+ try {
24985
+ if (init.body && init.body.length > 0) {
24986
+ controller.enqueue(new Uint8Array(init.body));
24987
+ init.body = void 0;
24988
+ return;
24989
+ }
24990
+ const chunk = await ((_a22 = init.bodyStream) == null ? void 0 : _a22.read());
24991
+ if (!chunk) {
24992
+ controller.close();
24993
+ } else {
24994
+ controller.enqueue(new Uint8Array(chunk));
24995
+ }
24996
+ } catch (error46) {
24997
+ (_b = init.abortController) == null ? void 0 : _b.abort(error46);
24998
+ controller.error(error46);
24999
+ }
25000
+ },
25001
+ async cancel() {
25002
+ var _a22;
25003
+ await ((_a22 = init.bodyStream) == null ? void 0 : _a22.cancel());
25004
+ }
25005
+ }) : init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
25006
+ const streamInit = init.bodyStream && !bodyForbidden ? { duplex: "half" } : {};
25007
+ return new Request(url2, {
25008
+ method: method2,
25009
+ headers,
25010
+ body,
25011
+ signal: ((_a2 = init.abortController) == null ? void 0 : _a2.signal) ?? init.signal,
25012
+ ...streamInit
25013
+ });
25014
+ }
25015
+ async function cancelNativeHttpRequestBody(bodyStream) {
25016
+ await (bodyStream == null ? void 0 : bodyStream.cancel());
25017
+ }
25018
+ async function writeResponseChunk(stream, chunk) {
25019
+ for (let offset = 0; offset < chunk.byteLength; offset += HTTP_BODY_CHUNK_SIZE) {
25020
+ await stream.write(
25021
+ chunk.subarray(offset, offset + HTTP_BODY_CHUNK_SIZE)
25022
+ );
25023
+ }
25024
+ }
25025
+ async function pumpResponseBody(reader, stream) {
25026
+ var _a2;
25027
+ const cancelled = stream.cancelled().then(() => ({ cancelled: true }));
25028
+ try {
25029
+ for (; ; ) {
25030
+ const read = reader.read().then((next2) => ({ cancelled: false, next: next2 }));
25031
+ const result = await Promise.race([read, cancelled]);
25032
+ if (result.cancelled) {
25033
+ void reader.cancel(
25034
+ new Error(
25035
+ "native http response stream receiver dropped"
25036
+ )
25037
+ ).catch((error46) => {
25038
+ logger22().debug({
25039
+ msg: "failed to cancel native http response reader",
25040
+ error: error46
25041
+ });
25042
+ });
25043
+ return;
25044
+ }
25045
+ const { next } = result;
25046
+ if (next.done) {
25047
+ await stream.end();
25048
+ return;
25049
+ }
25050
+ if ((_a2 = next.value) == null ? void 0 : _a2.byteLength) {
25051
+ await writeResponseChunk(stream, next.value);
25052
+ }
25053
+ }
25054
+ } catch (error46) {
25055
+ try {
25056
+ await stream.error(stringifyError(error46));
25057
+ } catch (streamError) {
25058
+ logger22().debug({
25059
+ msg: "failed to report native http response stream error",
25060
+ error: streamError
25061
+ });
25062
+ }
25063
+ void reader.cancel(error46).catch(() => {
25064
+ });
25065
+ } finally {
25066
+ try {
25067
+ reader.releaseLock();
25068
+ } catch (error46) {
25069
+ logger22().debug({
25070
+ msg: "failed to release native http response reader lock",
25071
+ error: error46
25072
+ });
25073
+ }
25074
+ }
25075
+ }
25076
+ async function convertNativeHttpResponse(response, responseBodyStream) {
25077
+ const headers = Object.fromEntries(response.headers.entries());
25078
+ if (!response.body) {
25079
+ return {
25080
+ response: {
25081
+ status: response.status,
25082
+ headers,
25083
+ body: new Uint8Array()
25084
+ }
25085
+ };
25086
+ }
25087
+ if (responseBodyStream) {
25088
+ const reader = response.body.getReader();
25089
+ const bodyCompletion = pumpResponseBody(reader, responseBodyStream);
25090
+ return {
25091
+ response: {
25092
+ status: response.status,
25093
+ headers,
25094
+ stream: true
25095
+ },
25096
+ bodyCompletion
25097
+ };
25098
+ }
25099
+ return {
25100
+ response: {
25101
+ status: response.status,
25102
+ headers,
25103
+ body: new Uint8Array(await response.arrayBuffer())
25104
+ }
25105
+ };
25106
+ }
24946
25107
  var CONN_PARAMS_KEY = "__conn_params__";
24947
25108
  function validateActionArgs(schemas, name, args) {
24948
25109
  if (!(schemas == null ? void 0 : schemas[name])) {
@@ -26391,7 +26552,7 @@ function toRuntimeBytes(value) {
26391
26552
  function arrayBufferViewToRuntimeBytes(value) {
26392
26553
  return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
26393
26554
  }
26394
- function runtimeBytesToArrayBuffer(value) {
26555
+ function runtimeBytesToArrayBuffer2(value) {
26395
26556
  return value.buffer.slice(
26396
26557
  value.byteOffset,
26397
26558
  value.byteOffset + value.byteLength
@@ -26437,6 +26598,9 @@ function decodeNativeKvValue(value, options) {
26437
26598
  async function loadEngineCli() {
26438
26599
  return import(["@rivetkit", "engine-cli"].join("/"));
26439
26600
  }
26601
+ async function loadServices() {
26602
+ return import(["@rivet-dev", "services"].join("/"));
26603
+ }
26440
26604
  function decodeValue(value) {
26441
26605
  if (!value || value.length === 0) {
26442
26606
  return void 0;
@@ -26722,24 +26886,6 @@ function decodeArgs(value) {
26722
26886
  const decoded = decodeValue(value);
26723
26887
  return normalizeArgs(decoded);
26724
26888
  }
26725
- function buildRequest(init) {
26726
- const url2 = init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString();
26727
- const body = init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
26728
- return new Request(url2, {
26729
- method: init.method,
26730
- headers: init.headers,
26731
- body
26732
- });
26733
- }
26734
- async function toRuntimeHttpResponse(response) {
26735
- const headers = Object.fromEntries(response.headers.entries());
26736
- const body = new Uint8Array(await response.arrayBuffer());
26737
- return {
26738
- status: response.status,
26739
- headers,
26740
- body
26741
- };
26742
- }
26743
26889
  function toActorKey(segments) {
26744
26890
  return segments.map(
26745
26891
  (segment) => segment.kind === "number" ? String(segment.numberValue ?? 0) : segment.stringValue ?? ""
@@ -27452,7 +27598,7 @@ var NativeWebSocketAdapter = class {
27452
27598
  this.#runtime.webSocketSetEventCallback(this.#ws, (event2) => {
27453
27599
  if (event2.kind === "message") {
27454
27600
  this.#virtual.triggerMessage(
27455
- event2.binary ? runtimeBytesToArrayBuffer(event2.data) : event2.data,
27601
+ event2.binary ? runtimeBytesToArrayBuffer2(event2.data) : event2.data,
27456
27602
  event2.messageIndex
27457
27603
  );
27458
27604
  return;
@@ -28674,7 +28820,6 @@ function buildActorConfig(definition, registryConfig, runtimeKind) {
28674
28820
  return {
28675
28821
  name: options.name,
28676
28822
  icon: options.icon,
28677
- maxActions: options.maxActions,
28678
28823
  hasDatabase: true,
28679
28824
  remoteSqlite: usesRemoteSqlite,
28680
28825
  sqliteProfiling,
@@ -28836,12 +28981,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28836
28981
  cancelToken,
28837
28982
  run !== void 0
28838
28983
  );
28839
- const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
28984
+ const maybeHandleNativeInspectorRequest = async (ctx, rawRequest) => {
28840
28985
  var _a22, _b, _c, _d;
28841
- const url2 = new URL(jsRequest.url);
28986
+ const rawUrl = rawRequest.uri.startsWith("http") ? rawRequest.uri : new URL(rawRequest.uri, "http://127.0.0.1").toString();
28987
+ const url2 = new URL(rawUrl);
28842
28988
  if (!url2.pathname.startsWith("/inspector/")) {
28843
28989
  return void 0;
28844
28990
  }
28991
+ const jsRequest = buildNativeHttpRequest(rawRequest);
28845
28992
  const jsonResponse = (body, init) => new Response(JSON.stringify(body), {
28846
28993
  status: (init == null ? void 0 : init.status) ?? 200,
28847
28994
  headers: {
@@ -29372,7 +29519,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29372
29519
  );
29373
29520
  const actorCtx = makeActorCtx(
29374
29521
  ctx,
29375
- request ? buildRequest(request) : void 0
29522
+ request ? buildNativeHttpRequest(request) : void 0
29376
29523
  );
29377
29524
  try {
29378
29525
  await config3.onBeforeConnect(
@@ -29392,7 +29539,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29392
29539
  const { ctx, conn, params, request } = unwrapTsfnPayload(error46, payload);
29393
29540
  const actorCtx = makeActorCtx(
29394
29541
  ctx,
29395
- request ? buildRequest(request) : void 0
29542
+ request ? buildNativeHttpRequest(request) : void 0
29396
29543
  );
29397
29544
  const connAdapter = new NativeConnAdapter(
29398
29545
  runtime,
@@ -29430,7 +29577,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29430
29577
  );
29431
29578
  const actorCtx = makeActorCtx(
29432
29579
  ctx,
29433
- request ? buildRequest(request) : void 0
29580
+ request ? buildNativeHttpRequest(request) : void 0
29434
29581
  );
29435
29582
  const connAdapter = new NativeConnAdapter(
29436
29583
  runtime,
@@ -29537,27 +29684,45 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29537
29684
  onRequest: wrapNativeCallback(
29538
29685
  async (error46, payload) => {
29539
29686
  try {
29540
- const { ctx, request, cancelToken } = unwrapTsfnPayload(
29541
- error46,
29542
- payload
29543
- );
29544
- const jsRequest = buildRequest(request);
29545
- const inspectorResponse = await maybeHandleNativeInspectorRequest(
29546
- ctx,
29547
- request,
29548
- jsRequest
29549
- );
29687
+ const { ctx, request, cancelToken, responseBodyStream } = unwrapTsfnPayload(error46, payload);
29688
+ const inspectorResponse = await maybeHandleNativeInspectorRequest(ctx, request);
29550
29689
  if (inspectorResponse) {
29551
- return await toRuntimeHttpResponse(inspectorResponse);
29690
+ await cancelNativeHttpRequestBody(request.bodyStream);
29691
+ return (await convertNativeHttpResponse(
29692
+ inspectorResponse,
29693
+ responseBodyStream
29694
+ )).response;
29552
29695
  }
29553
29696
  if (typeof config3.onRequest !== "function") {
29554
- return await toRuntimeHttpResponse(
29555
- new Response(null, { status: 404 })
29556
- );
29697
+ await cancelNativeHttpRequestBody(request.bodyStream);
29698
+ return (await convertNativeHttpResponse(
29699
+ new Response(null, { status: 404 }),
29700
+ responseBodyStream
29701
+ )).response;
29557
29702
  }
29558
- const rawConnParams = jsRequest.headers.get(HEADER_CONN_PARAMS);
29703
+ const requestAbortController = new AbortController();
29704
+ const handlerRequest = buildNativeHttpRequest({
29705
+ ...request,
29706
+ abortController: requestAbortController
29707
+ });
29708
+ const rawConnParams = handlerRequest.headers.get(HEADER_CONN_PARAMS);
29559
29709
  let requestCtx;
29560
29710
  let conn;
29711
+ let removeRequestAbortListener;
29712
+ let cleanupDeferredToBody = false;
29713
+ let cleanedUp = false;
29714
+ const cleanupRequest = async () => {
29715
+ if (cleanedUp) return;
29716
+ cleanedUp = true;
29717
+ removeRequestAbortListener == null ? void 0 : removeRequestAbortListener();
29718
+ try {
29719
+ await (requestCtx == null ? void 0 : requestCtx.dispose());
29720
+ } finally {
29721
+ if (conn) {
29722
+ await runtime.connDisconnect(conn);
29723
+ }
29724
+ }
29725
+ };
29561
29726
  try {
29562
29727
  const connParams = validateConnParams(
29563
29728
  schemaConfig.connParamsSchema,
@@ -29573,23 +29738,56 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29573
29738
  requestCtx = makeConnCtx(
29574
29739
  ctx,
29575
29740
  conn,
29576
- jsRequest,
29741
+ handlerRequest,
29577
29742
  cancelToken
29578
29743
  );
29744
+ const ctxAbortSignal = requestCtx.abortSignal;
29745
+ const abortRequest = () => requestAbortController.abort(ctxAbortSignal.reason);
29746
+ if (ctxAbortSignal.aborted) {
29747
+ abortRequest();
29748
+ } else {
29749
+ ctxAbortSignal.addEventListener(
29750
+ "abort",
29751
+ abortRequest,
29752
+ { once: true }
29753
+ );
29754
+ removeRequestAbortListener = () => ctxAbortSignal.removeEventListener(
29755
+ "abort",
29756
+ abortRequest
29757
+ );
29758
+ }
29579
29759
  const response = await config3.onRequest(
29580
29760
  requestCtx,
29581
- jsRequest
29761
+ handlerRequest
29582
29762
  );
29583
29763
  if (!isResponseLike(response)) {
29584
29764
  throw new Error(
29585
29765
  "onRequest handler must return a Response"
29586
29766
  );
29587
29767
  }
29588
- return await toRuntimeHttpResponse(response);
29768
+ const conversion = await convertNativeHttpResponse(
29769
+ response,
29770
+ responseBodyStream
29771
+ );
29772
+ if (conversion.bodyCompletion) {
29773
+ cleanupDeferredToBody = true;
29774
+ void conversion.bodyCompletion.then(cleanupRequest).catch((cleanupError) => {
29775
+ logger22().error({
29776
+ msg: "failed to clean up native streaming http request",
29777
+ error: cleanupError
29778
+ });
29779
+ });
29780
+ }
29781
+ return conversion.response;
29589
29782
  } finally {
29590
- await (requestCtx == null ? void 0 : requestCtx.dispose());
29591
- if (conn) {
29592
- await runtime.connDisconnect(conn);
29783
+ try {
29784
+ await cancelNativeHttpRequestBody(
29785
+ request.bodyStream
29786
+ );
29787
+ } finally {
29788
+ if (!cleanupDeferredToBody) {
29789
+ await cleanupRequest();
29790
+ }
29593
29791
  }
29594
29792
  }
29595
29793
  } catch (error210) {
@@ -29604,7 +29802,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29604
29802
  onWebSocket: typeof config3.onWebSocket === "function" ? wrapNativeCallback(
29605
29803
  async (error46, payload) => {
29606
29804
  const { ctx, conn, ws, request } = unwrapTsfnPayload(error46, payload);
29607
- const jsRequest = request ? buildRequest(request) : void 0;
29805
+ const jsRequest = request ? buildNativeHttpRequest(request) : void 0;
29608
29806
  const actorCtx = makeConnCtx(ctx, conn, jsRequest);
29609
29807
  try {
29610
29808
  await config3.onWebSocket(
@@ -29710,7 +29908,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29710
29908
  timeoutMs,
29711
29909
  cancelToken
29712
29910
  } = unwrapTsfnPayload(error46, payload);
29713
- const jsRequest = buildRequest(request);
29911
+ const jsRequest = buildNativeHttpRequest(request);
29714
29912
  const actorCtx = withConnContext(
29715
29913
  runtime,
29716
29914
  ctx,
@@ -29780,7 +29978,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29780
29978
  buildActorConfig(definition, registryConfig, runtime.kind)
29781
29979
  );
29782
29980
  }
29783
- async function buildServeConfig(config3) {
29981
+ async function buildServeConfig(config3, resolveServicesBinary = true) {
29784
29982
  var _a2;
29785
29983
  if (!config3.endpoint) {
29786
29984
  throw nativeEndpointNotConfiguredError();
@@ -29791,6 +29989,7 @@ async function buildServeConfig(config3) {
29791
29989
  token: config3.token,
29792
29990
  namespace: config3.namespace,
29793
29991
  poolName: config3.envoy.poolName,
29992
+ startServices: resolveServicesBinary && config3.startServices,
29794
29993
  handleInspectorHttpInRuntime: true,
29795
29994
  serverlessBasePath: config3.serverless.basePath,
29796
29995
  serverlessPackageVersion: VERSION,
@@ -29809,6 +30008,17 @@ async function buildServeConfig(config3) {
29809
30008
  error: stringifyError(error46)
29810
30009
  });
29811
30010
  }
30011
+ if (resolveServicesBinary && config3.startServices) {
30012
+ try {
30013
+ const { getServicesPath } = await loadServices();
30014
+ serveConfig.servicesBinaryPath = getServicesPath();
30015
+ } catch (error46) {
30016
+ logger22().warn({
30017
+ msg: "could not resolve the Services binary; a local engine will fail with services.binary_unavailable \u2014 set RIVET_RUN_SERVICES=0 to disable Services or RIVET_SERVICES_BINARY to a local rivet-services binary",
30018
+ error: stringifyError(error46)
30019
+ });
30020
+ }
30021
+ }
29812
30022
  serveConfig.engineHost = config3.engineHost;
29813
30023
  serveConfig.enginePort = config3.enginePort;
29814
30024
  if ((_a2 = config3.test) == null ? void 0 : _a2.enabled) {
@@ -29835,7 +30045,7 @@ async function buildRegistryWithRuntime(config3, runtime) {
29835
30045
  return {
29836
30046
  runtime,
29837
30047
  registry: registry2,
29838
- serveConfig: await buildServeConfig(config3)
30048
+ serveConfig: await buildServeConfig(config3, runtime.kind === "napi")
29839
30049
  };
29840
30050
  }
29841
30051
  async function buildConfiguredRegistry(config3) {
@@ -29860,15 +30070,27 @@ function finishShutdownSignal(signal) {
29860
30070
  }
29861
30071
  process.kill(process.pid, signal);
29862
30072
  }
29863
- function createApplicationFetch(application) {
29864
- return async (request) => {
30073
+ function createApplicationFetch(application, runtime) {
30074
+ return async (request, responseBodyStream) => {
29865
30075
  const method2 = request.method.toUpperCase();
29866
30076
  const body = method2 === "GET" || method2 === "HEAD" || request.body.length === 0 ? void 0 : Uint8Array.from(request.body).buffer;
30077
+ const abortController = new AbortController();
30078
+ if (request.cancelToken) {
30079
+ if (runtime.cancellationTokenAborted(request.cancelToken)) {
30080
+ abortController.abort();
30081
+ } else {
30082
+ runtime.onCancellationTokenCancelled(
30083
+ request.cancelToken,
30084
+ () => abortController.abort()
30085
+ );
30086
+ }
30087
+ }
29867
30088
  const response = await application.fetch(
29868
30089
  new Request(request.url, {
29869
30090
  method: method2,
29870
30091
  headers: request.headers,
29871
- body
30092
+ body,
30093
+ signal: abortController.signal
29872
30094
  })
29873
30095
  );
29874
30096
  if (!isResponseLike(response)) {
@@ -29876,10 +30098,23 @@ function createApplicationFetch(application) {
29876
30098
  "registry.listen() application fetch must return a Response"
29877
30099
  );
29878
30100
  }
30101
+ const conversion = await convertNativeHttpResponse(
30102
+ response,
30103
+ responseBodyStream
30104
+ );
30105
+ if (conversion.bodyCompletion) {
30106
+ void conversion.bodyCompletion.catch((error46) => {
30107
+ logger22().error({
30108
+ msg: "application response stream failed",
30109
+ error: error46
30110
+ });
30111
+ });
30112
+ }
29879
30113
  return {
29880
- status: response.status,
29881
- headers: Object.fromEntries(response.headers.entries()),
29882
- body: new Uint8Array(await response.arrayBuffer())
30114
+ status: conversion.response.status ?? response.status,
30115
+ headers: conversion.response.headers ?? Object.fromEntries(response.headers.entries()),
30116
+ body: conversion.response.body,
30117
+ stream: conversion.response.stream
29883
30118
  };
29884
30119
  };
29885
30120
  }
@@ -30137,8 +30372,7 @@ var Registry = class {
30137
30372
  const port = opts.port ?? parsePortEnv(process.env.RIVET_PORT) ?? 3e3;
30138
30373
  const publicDir = opts.publicDir ?? getRivetkitPublicDir();
30139
30374
  const config3 = this.parseConfig();
30140
- const application = opts.application ? createApplicationFetch(opts.application) : void 0;
30141
- if (application && getRivetkitRuntimeMode() !== "serverless") {
30375
+ if (opts.application && getRivetkitRuntimeMode() !== "serverless") {
30142
30376
  if (config3.runtime === "wasm") {
30143
30377
  throw new Error(
30144
30378
  "registry.listen() requires the native runtime; use an application-owned HTTP server with WebAssembly"
@@ -30157,13 +30391,18 @@ var Registry = class {
30157
30391
  throw new Error("registry envoy startup did not initialize");
30158
30392
  }
30159
30393
  const { runtime: runtime2, registry: registry22, serveConfig: serveConfig2 } = await configuredRegistryPromise2;
30394
+ const application2 = createApplicationFetch(
30395
+ opts.application,
30396
+ runtime2
30397
+ );
30398
+ await readyPromise;
30160
30399
  const listenerPromise = runtime2.serveApplicationListener(
30161
30400
  registry22,
30162
30401
  {
30163
30402
  port,
30164
30403
  host: opts.host,
30165
30404
  publicDir,
30166
- application
30405
+ application: application2
30167
30406
  },
30168
30407
  serveConfig2
30169
30408
  );
@@ -30174,14 +30413,10 @@ var Registry = class {
30174
30413
  "registry envoy serve lifecycle did not initialize"
30175
30414
  );
30176
30415
  }
30177
- await Promise.all([
30178
- readyPromise,
30179
- listenerPromise,
30180
- serveLifecyclePromise
30181
- ]);
30416
+ await Promise.all([listenerPromise, serveLifecyclePromise]);
30182
30417
  return;
30183
30418
  }
30184
- const configuredRegistryPromise = buildConfiguredRegistry(config3);
30419
+ const configuredRegistryPromise = this.#buildConfiguredRegistry(config3);
30185
30420
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
30186
30421
  this.#runtimeServerlessPromise = configuredRegistryPromise;
30187
30422
  this.#installSignalHandlers(config3);
@@ -30192,6 +30427,7 @@ var Registry = class {
30192
30427
  });
30193
30428
  this.#ensureServerlessPoolConfigured(config3);
30194
30429
  const { runtime, registry: registry2, serveConfig } = await configuredRegistryPromise;
30430
+ const application = opts.application ? createApplicationFetch(opts.application, runtime) : void 0;
30195
30431
  await runtime.serveListener(
30196
30432
  registry2,
30197
30433
  {