@rivetkit/supabase 2.3.12-rc.3 → 2.3.12

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 +394 -140
  2. package/dist/mod.mjs +394 -140
  3. package/package.json +3 -3
package/dist/mod.js CHANGED
@@ -335,7 +335,7 @@ __export(mod_exports, {
335
335
  module.exports = __toCommonJS(mod_exports);
336
336
  var wasmBindings = __toESM(require("@rivetkit/rivetkit-wasm"));
337
337
 
338
- // ../rivetkit/dist/tsup/chunk-IXBD7BXC.js
338
+ // ../rivetkit/dist/tsup/chunk-OUQUIBVW.js
339
339
  var INTERNAL_ERROR_CODE = "internal_error";
340
340
  var INTERNAL_ERROR_DESCRIPTION = "An internal error occurred";
341
341
  var USER_ERROR_CODE = "user_error";
@@ -519,7 +519,7 @@ function unsupportedFeature(feature) {
519
519
  );
520
520
  }
521
521
 
522
- // ../rivetkit/dist/tsup/chunk-OLGQYFUW.js
522
+ // ../rivetkit/dist/tsup/chunk-MF42PRF2.js
523
523
  var import_pino = require("pino");
524
524
 
525
525
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/classic/external.js
@@ -13192,7 +13192,7 @@ var classic_default = external_exports;
13192
13192
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/index.js
13193
13193
  var v4_default = classic_default;
13194
13194
 
13195
- // ../rivetkit/dist/tsup/chunk-OLGQYFUW.js
13195
+ // ../rivetkit/dist/tsup/chunk-MF42PRF2.js
13196
13196
  var cbor = __toESM(require("cbor-x"), 1);
13197
13197
  var import_invariant = __toESM(require_invariant(), 1);
13198
13198
  var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
@@ -13211,6 +13211,10 @@ var getRivetRunEnginePort = () => {
13211
13211
  return value !== void 0 ? parseInt(value, 10) : void 0;
13212
13212
  };
13213
13213
  var getRivetRunEngineVersion = () => getEnvUniversal("RIVET_RUN_ENGINE_VERSION");
13214
+ var getRivetRunServices = () => {
13215
+ const value = getEnvUniversal("RIVET_RUN_SERVICES");
13216
+ return value === void 0 ? void 0 : value === "1";
13217
+ };
13214
13218
  var getRivetEnvoyVersion = () => {
13215
13219
  const value = getEnvUniversal("RIVET_ENVOY_VERSION");
13216
13220
  return value !== void 0 ? parseInt(value, 10) : void 0;
@@ -13362,7 +13366,7 @@ function noopNext() {
13362
13366
  }
13363
13367
  var package_default = {
13364
13368
  name: "rivetkit",
13365
- version: "2.3.12-rc.3",
13369
+ version: "2.3.12",
13366
13370
  description: "Lightweight libraries for building stateful actors on edge platforms",
13367
13371
  license: "Apache-2.0",
13368
13372
  keywords: [
@@ -13572,6 +13576,7 @@ var package_default = {
13572
13576
  dependencies: {
13573
13577
  "@hono/zod-openapi": "^1.1.5",
13574
13578
  "@rivet-dev/agent-os-core": "^0.1.1",
13579
+ "@rivet-dev/services": "^0.1.3",
13575
13580
  "@rivetkit/bare-ts": "^0.6.2",
13576
13581
  "@rivetkit/engine-cli": "workspace:*",
13577
13582
  "@rivetkit/engine-envoy-protocol": "workspace:*",
@@ -14665,7 +14670,7 @@ function Config({ initialBufferLength = 1024, maxBufferLength = 1024 * 1024 * 32
14665
14670
  };
14666
14671
  }
14667
14672
 
14668
- // ../rivetkit/dist/tsup/chunk-WVFTFWJL.js
14673
+ // ../rivetkit/dist/tsup/chunk-GEN4NHXM.js
14669
14674
  var config2 = /* @__PURE__ */ Config({});
14670
14675
  function readWorkflowCbor(bc) {
14671
14676
  return readData(bc);
@@ -15544,6 +15549,44 @@ function removePrefixFromKey(prefixedKey) {
15544
15549
  return prefixedKey.slice(KEYS.KV.length);
15545
15550
  }
15546
15551
 
15552
+ // ../rivetkit/dist/tsup/chunk-JYTXOMM7.js
15553
+ function logger() {
15554
+ return getLogger("actor-client");
15555
+ }
15556
+ var webSocketPromise = null;
15557
+ async function importWebSocket() {
15558
+ if (webSocketPromise !== null) {
15559
+ return webSocketPromise;
15560
+ }
15561
+ webSocketPromise = (async () => {
15562
+ let _WebSocket;
15563
+ if (typeof WebSocket !== "undefined") {
15564
+ _WebSocket = WebSocket;
15565
+ } else {
15566
+ try {
15567
+ const moduleName = "ws";
15568
+ const ws = await import(
15569
+ /* webpackIgnore: true */
15570
+ moduleName
15571
+ );
15572
+ _WebSocket = ws.default;
15573
+ logger().debug("using websocket from npm");
15574
+ } catch {
15575
+ _WebSocket = class MockWebSocket {
15576
+ constructor() {
15577
+ throw new Error(
15578
+ 'WebSocket support requires installing the "ws" peer dependency.'
15579
+ );
15580
+ }
15581
+ };
15582
+ logger().debug("using mock websocket");
15583
+ }
15584
+ }
15585
+ return _WebSocket;
15586
+ })();
15587
+ return webSocketPromise;
15588
+ }
15589
+
15547
15590
  // ../rivetkit/dist/tsup/chunk-JTHHCZCZ.js
15548
15591
  var MIGRATION_TRANSACTION_TIMEOUT_MS = 5 * 6e4;
15549
15592
  function isManualTransactionControl(query) {
@@ -15627,45 +15670,7 @@ var AsyncMutex = class {
15627
15670
  }
15628
15671
  };
15629
15672
 
15630
- // ../rivetkit/dist/tsup/chunk-XI4MEUUI.js
15631
- function logger() {
15632
- return getLogger("actor-client");
15633
- }
15634
- var webSocketPromise = null;
15635
- async function importWebSocket() {
15636
- if (webSocketPromise !== null) {
15637
- return webSocketPromise;
15638
- }
15639
- webSocketPromise = (async () => {
15640
- let _WebSocket;
15641
- if (typeof WebSocket !== "undefined") {
15642
- _WebSocket = WebSocket;
15643
- } else {
15644
- try {
15645
- const moduleName = "ws";
15646
- const ws = await import(
15647
- /* webpackIgnore: true */
15648
- moduleName
15649
- );
15650
- _WebSocket = ws.default;
15651
- logger().debug("using websocket from npm");
15652
- } catch {
15653
- _WebSocket = class MockWebSocket {
15654
- constructor() {
15655
- throw new Error(
15656
- 'WebSocket support requires installing the "ws" peer dependency.'
15657
- );
15658
- }
15659
- };
15660
- logger().debug("using mock websocket");
15661
- }
15662
- }
15663
- return _WebSocket;
15664
- })();
15665
- return webSocketPromise;
15666
- }
15667
-
15668
- // ../rivetkit/dist/tsup/chunk-YYIDQBBM.js
15673
+ // ../rivetkit/dist/tsup/chunk-VOYNLY57.js
15669
15674
  var import_invariant2 = __toESM(require_invariant(), 1);
15670
15675
 
15671
15676
  // ../../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
@@ -15843,7 +15848,7 @@ function createVersionedDataHandler(config3) {
15843
15848
  return new VersionedDataHandler(config3);
15844
15849
  }
15845
15850
 
15846
- // ../rivetkit/dist/tsup/chunk-YYIDQBBM.js
15851
+ // ../rivetkit/dist/tsup/chunk-VOYNLY57.js
15847
15852
  var import_invariant3 = __toESM(require_invariant(), 1);
15848
15853
  var import_invariant4 = __toESM(require_invariant(), 1);
15849
15854
  var PATH_CONNECT = "/connect";
@@ -15852,6 +15857,7 @@ var PATH_WEBSOCKET_PREFIX = "/websocket/";
15852
15857
  var HEADER_ACTOR_QUERY = "x-rivet-query";
15853
15858
  var HEADER_ENCODING = "x-rivet-encoding";
15854
15859
  var HEADER_CONN_PARAMS = "x-rivet-conn-params";
15860
+ var HEADER_ORIGINAL_REQUEST_URL = "x-rivet-internal-original-request-url";
15855
15861
  var HEADER_ACTOR_ID = "x-rivet-actor";
15856
15862
  var HEADER_ACTOR_GENERATION = "x-rivet-actor-generation";
15857
15863
  var HEADER_ACTOR_KEY = "x-rivet-actor-key";
@@ -17910,6 +17916,18 @@ async function checkForSchedulingError(group, code, actorId, query, driver, rayI
17910
17916
  }
17911
17917
  return null;
17912
17918
  }
17919
+ function isUrlLike(value) {
17920
+ return typeof value === "object" && value !== null && typeof value.href === "string" && typeof value.pathname === "string" && typeof value.search === "string";
17921
+ }
17922
+ function isRequestLike(value) {
17923
+ return typeof value === "object" && value !== null && typeof value.url === "string" && typeof value.method === "string" && isHeadersLike(value.headers);
17924
+ }
17925
+ function isResponseLike(value) {
17926
+ return typeof value === "object" && value !== null && typeof value.status === "number" && isHeadersLike(value.headers) && typeof value.arrayBuffer === "function";
17927
+ }
17928
+ function isHeadersLike(value) {
17929
+ return typeof value === "object" && value !== null && typeof value.entries === "function";
17930
+ }
17913
17931
  function* walkErrorChain(error46, maxDepth = 8) {
17914
17932
  let current = error46;
17915
17933
  let depth = 0;
@@ -18335,28 +18353,19 @@ function createQueueSender(senderOptions) {
18335
18353
  send
18336
18354
  };
18337
18355
  }
18338
- function isUrlLike(value) {
18339
- return typeof value === "object" && value !== null && typeof value.href === "string" && typeof value.pathname === "string" && typeof value.search === "string";
18340
- }
18341
- function isRequestLike(value) {
18342
- return typeof value === "object" && value !== null && typeof value.url === "string" && typeof value.method === "string" && isHeadersLike(value.headers);
18343
- }
18344
- function isResponseLike(value) {
18345
- return typeof value === "object" && value !== null && typeof value.status === "number" && isHeadersLike(value.headers) && typeof value.arrayBuffer === "function";
18346
- }
18347
- function isHeadersLike(value) {
18348
- return typeof value === "object" && value !== null && typeof value.entries === "function";
18349
- }
18350
18356
  async function rawHttpFetch(driver, target, params, input, init, options = {}) {
18351
18357
  let path2;
18358
+ let originalUrl;
18352
18359
  let mergedInit = init || {};
18353
18360
  if (typeof input === "string") {
18354
18361
  path2 = input;
18355
18362
  } else if (isUrlLike(input)) {
18356
18363
  path2 = input.pathname + input.search;
18364
+ originalUrl = input.toString();
18357
18365
  } else if (isRequestLike(input)) {
18358
18366
  const url2 = new URL(input.url);
18359
18367
  path2 = url2.pathname + url2.search;
18368
+ originalUrl = url2.toString();
18360
18369
  const requestHeaders = new Headers(input.headers);
18361
18370
  const initHeaders = new Headers((init == null ? void 0 : init.headers) || {});
18362
18371
  const mergedHeaders = new Headers(requestHeaders);
@@ -18398,6 +18407,10 @@ async function rawHttpFetch(driver, target, params, input, init, options = {}) {
18398
18407
  const normalizedPath = path2.startsWith("/") ? path2.slice(1) : path2;
18399
18408
  const url2 = new URL(`http://actor/request/${normalizedPath}`);
18400
18409
  const proxyRequestHeaders = new Headers(mergedInit.headers);
18410
+ proxyRequestHeaders.delete(HEADER_ORIGINAL_REQUEST_URL);
18411
+ if (originalUrl) {
18412
+ proxyRequestHeaders.set(HEADER_ORIGINAL_REQUEST_URL, originalUrl);
18413
+ }
18401
18414
  if (params) {
18402
18415
  proxyRequestHeaders.set(HEADER_CONN_PARAMS, JSON.stringify(params));
18403
18416
  }
@@ -18523,7 +18536,9 @@ var ActorHandleRaw = class {
18523
18536
  async #sendQueueMessage(name, body, options) {
18524
18537
  return await this.#queueSendMutex.run(async () => {
18525
18538
  const maxAttempts = this.#getDynamicQueryMaxAttempts();
18526
- let useQueryTarget = isDynamicActorQuery(this.#actorResolutionState);
18539
+ let useQueryTarget = isDynamicActorQuery(
18540
+ this.#actorResolutionState
18541
+ );
18527
18542
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
18528
18543
  let actorId;
18529
18544
  try {
@@ -18872,9 +18887,10 @@ var ActorHandleRaw = class {
18872
18887
  return this.#fetchWithResolvedActor(input, init);
18873
18888
  }
18874
18889
  async #fetchWithResolvedActor(input, init) {
18875
- const maxAttempts = this.#getDynamicQueryMaxAttempts();
18876
- let useQueryTarget = isDynamicActorQuery(this.#actorResolutionState);
18877
18890
  const { skipReadyWait, ...requestInit } = init ?? {};
18891
+ const hasBody = requestInit.body !== void 0 ? requestInit.body !== null : isRequestLike(input) && input.body !== null;
18892
+ const maxAttempts = hasBody ? 1 : this.#getDynamicQueryMaxAttempts();
18893
+ let useQueryTarget = isDynamicActorQuery(this.#actorResolutionState);
18878
18894
  const gatewayOptions = resolveActorGatewayOptions(
18879
18895
  this.#gatewayOptions,
18880
18896
  {
@@ -20642,23 +20658,19 @@ async function sendHttpRequestToGateway(runConfig, gatewayUrl, actorRequest, opt
20642
20658
  if (actorRequest.bodyUsed) {
20643
20659
  throw new Error("Request body has already been consumed");
20644
20660
  }
20645
- const reqBody = await actorRequest.arrayBuffer();
20646
- if (reqBody.byteLength !== 0) {
20647
- bodyToSend = reqBody;
20661
+ if (actorRequest.body) {
20662
+ bodyToSend = actorRequest.body;
20648
20663
  guardHeaders.delete("transfer-encoding");
20649
20664
  guardHeaders.delete("content-length");
20650
20665
  }
20651
20666
  }
20652
- const guardRequest = new Request(gatewayUrl, {
20667
+ return fetch(gatewayUrl, {
20653
20668
  method: actorRequest.method,
20654
20669
  headers: guardHeaders,
20655
20670
  body: bodyToSend,
20656
- signal: actorRequest.signal
20671
+ signal: actorRequest.signal,
20672
+ ...bodyToSend ? { duplex: "half" } : {}
20657
20673
  });
20658
- return mutableResponse(await fetch(guardRequest));
20659
- }
20660
- function mutableResponse(fetchRes) {
20661
- return new Response(fetchRes.body, fetchRes);
20662
20674
  }
20663
20675
  function buildGuardHeaders(runConfig, actorRequest, options) {
20664
20676
  const headers = new Headers();
@@ -21608,7 +21620,7 @@ function apiActorToOutput(actor2) {
21608
21620
  };
21609
21621
  }
21610
21622
 
21611
- // ../rivetkit/dist/tsup/chunk-PSXMESQJ.js
21623
+ // ../rivetkit/dist/tsup/chunk-EBXARMGI.js
21612
21624
  var nativeStateTransactionOpeners = /* @__PURE__ */ new WeakMap();
21613
21625
  var nativeStateTransactionClientBinders = /* @__PURE__ */ new WeakMap();
21614
21626
  function registerNativeStateTransactionOpener(provider, opener) {
@@ -23684,6 +23696,12 @@ var RegistryConfigSchema = external_exports.object({
23684
23696
  enginePort: external_exports.number().int().min(1).max(65535).optional().default(() => getRivetRunEnginePort() ?? ENGINE_PORT),
23685
23697
  /** @experimental */
23686
23698
  engineVersion: external_exports.string().optional().default(() => getRivetRunEngineVersion() ?? VERSION),
23699
+ /**
23700
+ * Starts the first-party Services actor host when RivetKit manages
23701
+ * a local engine. Defaults to the local-engine decision. Set
23702
+ * RIVET_RUN_SERVICES=0 or 1 to override it.
23703
+ */
23704
+ startServices: external_exports.boolean().optional(),
23687
23705
  /**
23688
23706
  * @experimental
23689
23707
  *
@@ -23764,6 +23782,7 @@ var RegistryConfigSchema = external_exports.object({
23764
23782
  config3.enginePort
23765
23783
  );
23766
23784
  const endpoint = config3.startEngine ? localEngineEndpoint : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? localEngineEndpoint : void 0);
23785
+ const startServices = config3.startServices ?? getRivetRunServices() ?? Boolean(endpoint && isLocalEngineEndpoint(endpoint));
23767
23786
  const validateServerlessEndpoint = Boolean(
23768
23787
  config3.startEngine || parsedEndpoint
23769
23788
  );
@@ -23787,6 +23806,7 @@ var RegistryConfigSchema = external_exports.object({
23787
23806
  ...config3,
23788
23807
  sqlite,
23789
23808
  endpoint,
23809
+ startServices,
23790
23810
  namespace,
23791
23811
  token,
23792
23812
  publicEndpoint,
@@ -23900,6 +23920,9 @@ var DocRegistryConfigSchema = external_exports.object({
23900
23920
  engineVersion: external_exports.string().optional().describe(
23901
23921
  "Version of the local engine package to use. Defaults to the current RivetKit version."
23902
23922
  ),
23923
+ startServices: external_exports.boolean().optional().describe(
23924
+ "Starts Services when RivetKit manages a local Engine. Defaults to the local-Engine decision. Set RIVET_RUN_SERVICES=0 or 1 to override."
23925
+ ),
23903
23926
  configurePool: DocConfigurePoolSchema.describe(
23904
23927
  "Automatically configure serverless runners in the engine."
23905
23928
  ),
@@ -24409,16 +24432,30 @@ function toNapiApplication(application) {
24409
24432
  if (!request) {
24410
24433
  throw new Error("application fetch callback received no request");
24411
24434
  }
24412
- const response = await application({
24413
- ...request,
24414
- body: new Uint8Array(request.body)
24415
- });
24435
+ const response = await application(
24436
+ {
24437
+ ...request,
24438
+ body: new Uint8Array(request.body),
24439
+ cancelToken: request.cancelToken
24440
+ },
24441
+ request.responseBodyStream ? fromNapiHttpResponseBodyStream(
24442
+ request.responseBodyStream
24443
+ ) : void 0
24444
+ );
24416
24445
  return {
24417
24446
  ...response,
24418
- body: toNapiBuffer(response.body)
24447
+ body: response.body === void 0 ? void 0 : toNapiBuffer(response.body)
24419
24448
  };
24420
24449
  };
24421
24450
  }
24451
+ function fromNapiHttpResponseBodyStream(stream) {
24452
+ return {
24453
+ cancelled: () => stream.cancelled(),
24454
+ write: (chunk) => stream.write(Buffer.from(chunk)),
24455
+ end: () => stream.end(),
24456
+ error: (message) => stream.error(message)
24457
+ };
24458
+ }
24422
24459
  function toNapiHttpRequest(request) {
24423
24460
  if (!request) {
24424
24461
  return request;
@@ -24961,6 +24998,147 @@ async function loadNapiRuntime() {
24961
24998
  runtime: new NapiCoreRuntime(bindings)
24962
24999
  };
24963
25000
  }
25001
+ var HTTP_BODY_CHUNK_SIZE = 64 * 1024;
25002
+ function runtimeBytesToArrayBuffer(value) {
25003
+ return value.buffer.slice(
25004
+ value.byteOffset,
25005
+ value.byteOffset + value.byteLength
25006
+ );
25007
+ }
25008
+ function buildNativeHttpRequest(init) {
25009
+ var _a2;
25010
+ const headers = new Headers(init.headers);
25011
+ const originalUrl = headers.get(HEADER_ORIGINAL_REQUEST_URL);
25012
+ headers.delete(HEADER_ORIGINAL_REQUEST_URL);
25013
+ const url2 = originalUrl ?? (init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString());
25014
+ const method2 = init.method.toUpperCase();
25015
+ const bodyForbidden = method2 === "GET" || method2 === "HEAD";
25016
+ const body = bodyForbidden ? void 0 : init.bodyStream ? new ReadableStream({
25017
+ async pull(controller) {
25018
+ var _a22, _b;
25019
+ try {
25020
+ if (init.body && init.body.length > 0) {
25021
+ controller.enqueue(new Uint8Array(init.body));
25022
+ init.body = void 0;
25023
+ return;
25024
+ }
25025
+ const chunk = await ((_a22 = init.bodyStream) == null ? void 0 : _a22.read());
25026
+ if (!chunk) {
25027
+ controller.close();
25028
+ } else {
25029
+ controller.enqueue(new Uint8Array(chunk));
25030
+ }
25031
+ } catch (error46) {
25032
+ (_b = init.abortController) == null ? void 0 : _b.abort(error46);
25033
+ controller.error(error46);
25034
+ }
25035
+ },
25036
+ async cancel() {
25037
+ var _a22;
25038
+ await ((_a22 = init.bodyStream) == null ? void 0 : _a22.cancel());
25039
+ }
25040
+ }) : init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
25041
+ const streamInit = init.bodyStream && !bodyForbidden ? { duplex: "half" } : {};
25042
+ return new Request(url2, {
25043
+ method: method2,
25044
+ headers,
25045
+ body,
25046
+ signal: ((_a2 = init.abortController) == null ? void 0 : _a2.signal) ?? init.signal,
25047
+ ...streamInit
25048
+ });
25049
+ }
25050
+ async function cancelNativeHttpRequestBody(bodyStream) {
25051
+ await (bodyStream == null ? void 0 : bodyStream.cancel());
25052
+ }
25053
+ async function writeResponseChunk(stream, chunk) {
25054
+ for (let offset = 0; offset < chunk.byteLength; offset += HTTP_BODY_CHUNK_SIZE) {
25055
+ await stream.write(
25056
+ chunk.subarray(offset, offset + HTTP_BODY_CHUNK_SIZE)
25057
+ );
25058
+ }
25059
+ }
25060
+ async function pumpResponseBody(reader, stream) {
25061
+ var _a2;
25062
+ const cancelled = stream.cancelled().then(() => ({ cancelled: true }));
25063
+ try {
25064
+ for (; ; ) {
25065
+ const read = reader.read().then((next2) => ({ cancelled: false, next: next2 }));
25066
+ const result = await Promise.race([read, cancelled]);
25067
+ if (result.cancelled) {
25068
+ void reader.cancel(
25069
+ new Error(
25070
+ "native http response stream receiver dropped"
25071
+ )
25072
+ ).catch((error46) => {
25073
+ logger22().debug({
25074
+ msg: "failed to cancel native http response reader",
25075
+ error: error46
25076
+ });
25077
+ });
25078
+ return;
25079
+ }
25080
+ const { next } = result;
25081
+ if (next.done) {
25082
+ await stream.end();
25083
+ return;
25084
+ }
25085
+ if ((_a2 = next.value) == null ? void 0 : _a2.byteLength) {
25086
+ await writeResponseChunk(stream, next.value);
25087
+ }
25088
+ }
25089
+ } catch (error46) {
25090
+ try {
25091
+ await stream.error(stringifyError(error46));
25092
+ } catch (streamError) {
25093
+ logger22().debug({
25094
+ msg: "failed to report native http response stream error",
25095
+ error: streamError
25096
+ });
25097
+ }
25098
+ void reader.cancel(error46).catch(() => {
25099
+ });
25100
+ } finally {
25101
+ try {
25102
+ reader.releaseLock();
25103
+ } catch (error46) {
25104
+ logger22().debug({
25105
+ msg: "failed to release native http response reader lock",
25106
+ error: error46
25107
+ });
25108
+ }
25109
+ }
25110
+ }
25111
+ async function convertNativeHttpResponse(response, responseBodyStream) {
25112
+ const headers = Object.fromEntries(response.headers.entries());
25113
+ if (!response.body) {
25114
+ return {
25115
+ response: {
25116
+ status: response.status,
25117
+ headers,
25118
+ body: new Uint8Array()
25119
+ }
25120
+ };
25121
+ }
25122
+ if (responseBodyStream) {
25123
+ const reader = response.body.getReader();
25124
+ const bodyCompletion = pumpResponseBody(reader, responseBodyStream);
25125
+ return {
25126
+ response: {
25127
+ status: response.status,
25128
+ headers,
25129
+ stream: true
25130
+ },
25131
+ bodyCompletion
25132
+ };
25133
+ }
25134
+ return {
25135
+ response: {
25136
+ status: response.status,
25137
+ headers,
25138
+ body: new Uint8Array(await response.arrayBuffer())
25139
+ }
25140
+ };
25141
+ }
24964
25142
  var CONN_PARAMS_KEY = "__conn_params__";
24965
25143
  function validateActionArgs(schemas, name, args) {
24966
25144
  if (!(schemas == null ? void 0 : schemas[name])) {
@@ -26409,7 +26587,7 @@ function toRuntimeBytes(value) {
26409
26587
  function arrayBufferViewToRuntimeBytes(value) {
26410
26588
  return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
26411
26589
  }
26412
- function runtimeBytesToArrayBuffer(value) {
26590
+ function runtimeBytesToArrayBuffer2(value) {
26413
26591
  return value.buffer.slice(
26414
26592
  value.byteOffset,
26415
26593
  value.byteOffset + value.byteLength
@@ -26455,6 +26633,9 @@ function decodeNativeKvValue(value, options) {
26455
26633
  async function loadEngineCli() {
26456
26634
  return import(["@rivetkit", "engine-cli"].join("/"));
26457
26635
  }
26636
+ async function loadServices() {
26637
+ return import(["@rivet-dev", "services"].join("/"));
26638
+ }
26458
26639
  function decodeValue(value) {
26459
26640
  if (!value || value.length === 0) {
26460
26641
  return void 0;
@@ -26740,24 +26921,6 @@ function decodeArgs(value) {
26740
26921
  const decoded = decodeValue(value);
26741
26922
  return normalizeArgs(decoded);
26742
26923
  }
26743
- function buildRequest(init) {
26744
- const url2 = init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString();
26745
- const body = init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
26746
- return new Request(url2, {
26747
- method: init.method,
26748
- headers: init.headers,
26749
- body
26750
- });
26751
- }
26752
- async function toRuntimeHttpResponse(response) {
26753
- const headers = Object.fromEntries(response.headers.entries());
26754
- const body = new Uint8Array(await response.arrayBuffer());
26755
- return {
26756
- status: response.status,
26757
- headers,
26758
- body
26759
- };
26760
- }
26761
26924
  function toActorKey(segments) {
26762
26925
  return segments.map(
26763
26926
  (segment) => segment.kind === "number" ? String(segment.numberValue ?? 0) : segment.stringValue ?? ""
@@ -27470,7 +27633,7 @@ var NativeWebSocketAdapter = class {
27470
27633
  this.#runtime.webSocketSetEventCallback(this.#ws, (event2) => {
27471
27634
  if (event2.kind === "message") {
27472
27635
  this.#virtual.triggerMessage(
27473
- event2.binary ? runtimeBytesToArrayBuffer(event2.data) : event2.data,
27636
+ event2.binary ? runtimeBytesToArrayBuffer2(event2.data) : event2.data,
27474
27637
  event2.messageIndex
27475
27638
  );
27476
27639
  return;
@@ -28853,12 +29016,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28853
29016
  cancelToken,
28854
29017
  run !== void 0
28855
29018
  );
28856
- const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
29019
+ const maybeHandleNativeInspectorRequest = async (ctx, rawRequest) => {
28857
29020
  var _a22, _b, _c, _d;
28858
- const url2 = new URL(jsRequest.url);
29021
+ const rawUrl = rawRequest.uri.startsWith("http") ? rawRequest.uri : new URL(rawRequest.uri, "http://127.0.0.1").toString();
29022
+ const url2 = new URL(rawUrl);
28859
29023
  if (!url2.pathname.startsWith("/inspector/")) {
28860
29024
  return void 0;
28861
29025
  }
29026
+ const jsRequest = buildNativeHttpRequest(rawRequest);
28862
29027
  const jsonResponse = (body, init) => new Response(JSON.stringify(body), {
28863
29028
  status: (init == null ? void 0 : init.status) ?? 200,
28864
29029
  headers: {
@@ -29389,7 +29554,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29389
29554
  );
29390
29555
  const actorCtx = makeActorCtx(
29391
29556
  ctx,
29392
- request ? buildRequest(request) : void 0
29557
+ request ? buildNativeHttpRequest(request) : void 0
29393
29558
  );
29394
29559
  try {
29395
29560
  await config3.onBeforeConnect(
@@ -29409,7 +29574,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29409
29574
  const { ctx, conn, params, request } = unwrapTsfnPayload(error46, payload);
29410
29575
  const actorCtx = makeActorCtx(
29411
29576
  ctx,
29412
- request ? buildRequest(request) : void 0
29577
+ request ? buildNativeHttpRequest(request) : void 0
29413
29578
  );
29414
29579
  const connAdapter = new NativeConnAdapter(
29415
29580
  runtime,
@@ -29447,7 +29612,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29447
29612
  );
29448
29613
  const actorCtx = makeActorCtx(
29449
29614
  ctx,
29450
- request ? buildRequest(request) : void 0
29615
+ request ? buildNativeHttpRequest(request) : void 0
29451
29616
  );
29452
29617
  const connAdapter = new NativeConnAdapter(
29453
29618
  runtime,
@@ -29554,27 +29719,45 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29554
29719
  onRequest: wrapNativeCallback(
29555
29720
  async (error46, payload) => {
29556
29721
  try {
29557
- const { ctx, request, cancelToken } = unwrapTsfnPayload(
29558
- error46,
29559
- payload
29560
- );
29561
- const jsRequest = buildRequest(request);
29562
- const inspectorResponse = await maybeHandleNativeInspectorRequest(
29563
- ctx,
29564
- request,
29565
- jsRequest
29566
- );
29722
+ const { ctx, request, cancelToken, responseBodyStream } = unwrapTsfnPayload(error46, payload);
29723
+ const inspectorResponse = await maybeHandleNativeInspectorRequest(ctx, request);
29567
29724
  if (inspectorResponse) {
29568
- return await toRuntimeHttpResponse(inspectorResponse);
29725
+ await cancelNativeHttpRequestBody(request.bodyStream);
29726
+ return (await convertNativeHttpResponse(
29727
+ inspectorResponse,
29728
+ responseBodyStream
29729
+ )).response;
29569
29730
  }
29570
29731
  if (typeof config3.onRequest !== "function") {
29571
- return await toRuntimeHttpResponse(
29572
- new Response(null, { status: 404 })
29573
- );
29732
+ await cancelNativeHttpRequestBody(request.bodyStream);
29733
+ return (await convertNativeHttpResponse(
29734
+ new Response(null, { status: 404 }),
29735
+ responseBodyStream
29736
+ )).response;
29574
29737
  }
29575
- const rawConnParams = jsRequest.headers.get(HEADER_CONN_PARAMS);
29738
+ const requestAbortController = new AbortController();
29739
+ const handlerRequest = buildNativeHttpRequest({
29740
+ ...request,
29741
+ abortController: requestAbortController
29742
+ });
29743
+ const rawConnParams = handlerRequest.headers.get(HEADER_CONN_PARAMS);
29576
29744
  let requestCtx;
29577
29745
  let conn;
29746
+ let removeRequestAbortListener;
29747
+ let cleanupDeferredToBody = false;
29748
+ let cleanedUp = false;
29749
+ const cleanupRequest = async () => {
29750
+ if (cleanedUp) return;
29751
+ cleanedUp = true;
29752
+ removeRequestAbortListener == null ? void 0 : removeRequestAbortListener();
29753
+ try {
29754
+ await (requestCtx == null ? void 0 : requestCtx.dispose());
29755
+ } finally {
29756
+ if (conn) {
29757
+ await runtime.connDisconnect(conn);
29758
+ }
29759
+ }
29760
+ };
29578
29761
  try {
29579
29762
  const connParams = validateConnParams(
29580
29763
  schemaConfig.connParamsSchema,
@@ -29590,23 +29773,56 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29590
29773
  requestCtx = makeConnCtx(
29591
29774
  ctx,
29592
29775
  conn,
29593
- jsRequest,
29776
+ handlerRequest,
29594
29777
  cancelToken
29595
29778
  );
29779
+ const ctxAbortSignal = requestCtx.abortSignal;
29780
+ const abortRequest = () => requestAbortController.abort(ctxAbortSignal.reason);
29781
+ if (ctxAbortSignal.aborted) {
29782
+ abortRequest();
29783
+ } else {
29784
+ ctxAbortSignal.addEventListener(
29785
+ "abort",
29786
+ abortRequest,
29787
+ { once: true }
29788
+ );
29789
+ removeRequestAbortListener = () => ctxAbortSignal.removeEventListener(
29790
+ "abort",
29791
+ abortRequest
29792
+ );
29793
+ }
29596
29794
  const response = await config3.onRequest(
29597
29795
  requestCtx,
29598
- jsRequest
29796
+ handlerRequest
29599
29797
  );
29600
29798
  if (!isResponseLike(response)) {
29601
29799
  throw new Error(
29602
29800
  "onRequest handler must return a Response"
29603
29801
  );
29604
29802
  }
29605
- return await toRuntimeHttpResponse(response);
29803
+ const conversion = await convertNativeHttpResponse(
29804
+ response,
29805
+ responseBodyStream
29806
+ );
29807
+ if (conversion.bodyCompletion) {
29808
+ cleanupDeferredToBody = true;
29809
+ void conversion.bodyCompletion.then(cleanupRequest).catch((cleanupError) => {
29810
+ logger22().error({
29811
+ msg: "failed to clean up native streaming http request",
29812
+ error: cleanupError
29813
+ });
29814
+ });
29815
+ }
29816
+ return conversion.response;
29606
29817
  } finally {
29607
- await (requestCtx == null ? void 0 : requestCtx.dispose());
29608
- if (conn) {
29609
- await runtime.connDisconnect(conn);
29818
+ try {
29819
+ await cancelNativeHttpRequestBody(
29820
+ request.bodyStream
29821
+ );
29822
+ } finally {
29823
+ if (!cleanupDeferredToBody) {
29824
+ await cleanupRequest();
29825
+ }
29610
29826
  }
29611
29827
  }
29612
29828
  } catch (error210) {
@@ -29621,7 +29837,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29621
29837
  onWebSocket: typeof config3.onWebSocket === "function" ? wrapNativeCallback(
29622
29838
  async (error46, payload) => {
29623
29839
  const { ctx, conn, ws, request } = unwrapTsfnPayload(error46, payload);
29624
- const jsRequest = request ? buildRequest(request) : void 0;
29840
+ const jsRequest = request ? buildNativeHttpRequest(request) : void 0;
29625
29841
  const actorCtx = makeConnCtx(ctx, conn, jsRequest);
29626
29842
  try {
29627
29843
  await config3.onWebSocket(
@@ -29727,7 +29943,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29727
29943
  timeoutMs,
29728
29944
  cancelToken
29729
29945
  } = unwrapTsfnPayload(error46, payload);
29730
- const jsRequest = buildRequest(request);
29946
+ const jsRequest = buildNativeHttpRequest(request);
29731
29947
  const actorCtx = withConnContext(
29732
29948
  runtime,
29733
29949
  ctx,
@@ -29797,7 +30013,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
29797
30013
  buildActorConfig(definition, registryConfig, runtime.kind)
29798
30014
  );
29799
30015
  }
29800
- async function buildServeConfig(config3) {
30016
+ async function buildServeConfig(config3, resolveServicesBinary = true) {
29801
30017
  var _a2;
29802
30018
  if (!config3.endpoint) {
29803
30019
  throw nativeEndpointNotConfiguredError();
@@ -29808,6 +30024,7 @@ async function buildServeConfig(config3) {
29808
30024
  token: config3.token,
29809
30025
  namespace: config3.namespace,
29810
30026
  poolName: config3.envoy.poolName,
30027
+ startServices: resolveServicesBinary && config3.startServices,
29811
30028
  handleInspectorHttpInRuntime: true,
29812
30029
  serverlessBasePath: config3.serverless.basePath,
29813
30030
  serverlessPackageVersion: VERSION,
@@ -29826,6 +30043,17 @@ async function buildServeConfig(config3) {
29826
30043
  error: stringifyError(error46)
29827
30044
  });
29828
30045
  }
30046
+ if (resolveServicesBinary && config3.startServices) {
30047
+ try {
30048
+ const { getServicesPath } = await loadServices();
30049
+ serveConfig.servicesBinaryPath = getServicesPath();
30050
+ } catch (error46) {
30051
+ logger22().warn({
30052
+ 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",
30053
+ error: stringifyError(error46)
30054
+ });
30055
+ }
30056
+ }
29829
30057
  serveConfig.engineHost = config3.engineHost;
29830
30058
  serveConfig.enginePort = config3.enginePort;
29831
30059
  if ((_a2 = config3.test) == null ? void 0 : _a2.enabled) {
@@ -29852,7 +30080,7 @@ async function buildRegistryWithRuntime(config3, runtime) {
29852
30080
  return {
29853
30081
  runtime,
29854
30082
  registry: registry2,
29855
- serveConfig: await buildServeConfig(config3)
30083
+ serveConfig: await buildServeConfig(config3, runtime.kind === "napi")
29856
30084
  };
29857
30085
  }
29858
30086
  async function buildConfiguredRegistry(config3) {
@@ -29877,15 +30105,27 @@ function finishShutdownSignal(signal) {
29877
30105
  }
29878
30106
  process.kill(process.pid, signal);
29879
30107
  }
29880
- function createApplicationFetch(application) {
29881
- return async (request) => {
30108
+ function createApplicationFetch(application, runtime) {
30109
+ return async (request, responseBodyStream) => {
29882
30110
  const method2 = request.method.toUpperCase();
29883
30111
  const body = method2 === "GET" || method2 === "HEAD" || request.body.length === 0 ? void 0 : Uint8Array.from(request.body).buffer;
30112
+ const abortController = new AbortController();
30113
+ if (request.cancelToken) {
30114
+ if (runtime.cancellationTokenAborted(request.cancelToken)) {
30115
+ abortController.abort();
30116
+ } else {
30117
+ runtime.onCancellationTokenCancelled(
30118
+ request.cancelToken,
30119
+ () => abortController.abort()
30120
+ );
30121
+ }
30122
+ }
29884
30123
  const response = await application.fetch(
29885
30124
  new Request(request.url, {
29886
30125
  method: method2,
29887
30126
  headers: request.headers,
29888
- body
30127
+ body,
30128
+ signal: abortController.signal
29889
30129
  })
29890
30130
  );
29891
30131
  if (!isResponseLike(response)) {
@@ -29893,10 +30133,23 @@ function createApplicationFetch(application) {
29893
30133
  "registry.listen() application fetch must return a Response"
29894
30134
  );
29895
30135
  }
30136
+ const conversion = await convertNativeHttpResponse(
30137
+ response,
30138
+ responseBodyStream
30139
+ );
30140
+ if (conversion.bodyCompletion) {
30141
+ void conversion.bodyCompletion.catch((error46) => {
30142
+ logger22().error({
30143
+ msg: "application response stream failed",
30144
+ error: error46
30145
+ });
30146
+ });
30147
+ }
29896
30148
  return {
29897
- status: response.status,
29898
- headers: Object.fromEntries(response.headers.entries()),
29899
- body: new Uint8Array(await response.arrayBuffer())
30149
+ status: conversion.response.status ?? response.status,
30150
+ headers: conversion.response.headers ?? Object.fromEntries(response.headers.entries()),
30151
+ body: conversion.response.body,
30152
+ stream: conversion.response.stream
29900
30153
  };
29901
30154
  };
29902
30155
  }
@@ -30154,8 +30407,7 @@ var Registry = class {
30154
30407
  const port = opts.port ?? parsePortEnv(process.env.RIVET_PORT) ?? 3e3;
30155
30408
  const publicDir = opts.publicDir ?? getRivetkitPublicDir();
30156
30409
  const config3 = this.parseConfig();
30157
- const application = opts.application ? createApplicationFetch(opts.application) : void 0;
30158
- if (application && getRivetkitRuntimeMode() !== "serverless") {
30410
+ if (opts.application && getRivetkitRuntimeMode() !== "serverless") {
30159
30411
  if (config3.runtime === "wasm") {
30160
30412
  throw new Error(
30161
30413
  "registry.listen() requires the native runtime; use an application-owned HTTP server with WebAssembly"
@@ -30174,13 +30426,18 @@ var Registry = class {
30174
30426
  throw new Error("registry envoy startup did not initialize");
30175
30427
  }
30176
30428
  const { runtime: runtime2, registry: registry22, serveConfig: serveConfig2 } = await configuredRegistryPromise2;
30429
+ const application2 = createApplicationFetch(
30430
+ opts.application,
30431
+ runtime2
30432
+ );
30433
+ await readyPromise;
30177
30434
  const listenerPromise = runtime2.serveApplicationListener(
30178
30435
  registry22,
30179
30436
  {
30180
30437
  port,
30181
30438
  host: opts.host,
30182
30439
  publicDir,
30183
- application
30440
+ application: application2
30184
30441
  },
30185
30442
  serveConfig2
30186
30443
  );
@@ -30191,14 +30448,10 @@ var Registry = class {
30191
30448
  "registry envoy serve lifecycle did not initialize"
30192
30449
  );
30193
30450
  }
30194
- await Promise.all([
30195
- readyPromise,
30196
- listenerPromise,
30197
- serveLifecyclePromise
30198
- ]);
30451
+ await Promise.all([listenerPromise, serveLifecyclePromise]);
30199
30452
  return;
30200
30453
  }
30201
- const configuredRegistryPromise = buildConfiguredRegistry(config3);
30454
+ const configuredRegistryPromise = this.#buildConfiguredRegistry(config3);
30202
30455
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
30203
30456
  this.#runtimeServerlessPromise = configuredRegistryPromise;
30204
30457
  this.#installSignalHandlers(config3);
@@ -30209,6 +30462,7 @@ var Registry = class {
30209
30462
  });
30210
30463
  this.#ensureServerlessPoolConfigured(config3);
30211
30464
  const { runtime, registry: registry2, serveConfig } = await configuredRegistryPromise;
30465
+ const application = opts.application ? createApplicationFetch(opts.application, runtime) : void 0;
30212
30466
  await runtime.serveListener(
30213
30467
  registry2,
30214
30468
  {