@powerhousedao/reactor-api 6.2.3-dev.76 → 6.2.3-dev.78

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.
package/dist/index.mjs CHANGED
@@ -1,28 +1,28 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c2728328-5512-5f96-b156-4cad5d80f920")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d978d340-82ad-56d2-8827-0daf9ed3bf67")}catch(e){}}();
3
3
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
4
- import { A as createCanonicalDocumentIdResolver, C as loadSubgraphs, D as AuthService, E as callerSubject, F as AuthenticationRequiredError, I as ForbiddenError, L as MalformedStoredOperationError, M as AuthorizedDocumentHandle, N as createAuthorizationService, O as createCredentialInvalidator, P as AuthEvaluationUnsupportedError, R as RefusalNotRecordedError, S as loadProcessors, T as BaseSubgraph, _ as PACKAGE_MODULE_FAILED, c as piecesFromListModule, d as buildGraphQlDriveDocument, f as buildGraphqlOperation, g as runDetached, h as reportFailure, i as PIECE_SOURCE_LIST, j as AuthorizationPolicy, k as CanonicalDocumentIdResolutionError, l as extractDocumentModels, m as isSubgraphClass, o as pieceListLocation, p as buildGraphqlOperations, s as piecesFromCdnList, t as extractSubgraphs, u as buildGraphQlDocument, v as debounce, w as manifestDeclaredSubgraphs, x as loadDocumentModels, y as extractUpgradeManifests } from "./subgraph-extraction-cSpPp3Hq.mjs";
5
- import { A as getDocumentModelSubgraphName, C as createMergedSchema, D as generateDocumentModelSchema, E as findSubgraphTypeCollisions, F as reservedTypeNamesTaken, I as typeDefinitionNames, L as schema_default$1, M as getGeneratedDocumentModelTypes, N as hasOperationSchemas, O as generatedTypesOf, P as reservedTypeNames, S as buildSubgraphSchemaModule, T as documentModelSubgraphTypes, _ as describeOwnershipConflicts, a as inspectionAdminTypeDefs, b as assembleSubgraphTypeDefs, c as HOST_ORIGIN, d as byClaimPriority, f as decideAdmission, g as collectSubgraphClaims, h as supergraphClaimLosers, i as inspectionTypeDefs, j as getDocumentModelTypeDefs, k as getDocumentModelSchemaName, l as RegistrationOrder, m as documentModelSubgraphSources, n as systemTypeDefs, o as CORE_ORIGIN, p as describeOrigin, r as schema_default$2, s as DOCUMENT_MODEL_ORIGIN, t as baseDocumentModels, u as admitDocumentModels, v as DocumentModelSchemaCache, w as createSchema, x as buildDocumentModelSchema, y as SubgraphTypeCollisionError } from "./base-document-models-BGt__Ctn.mjs";
4
+ import { A as CanonicalDocumentIdResolutionError, C as loadSubgraphs, D as RequestClientBinder, E as callerSubject, F as AuthEvaluationUnsupportedError, I as AuthenticationRequiredError, L as ForbiddenError, M as AuthorizationPolicy, N as AuthorizedDocumentHandle, O as AuthService, P as createAuthorizationService, R as MalformedStoredOperationError, S as loadProcessors, T as BaseSubgraph, _ as PACKAGE_MODULE_FAILED, c as piecesFromListModule, d as buildGraphQlDriveDocument, f as buildGraphqlOperation, g as runDetached, h as reportFailure, i as PIECE_SOURCE_LIST, j as createCanonicalDocumentIdResolver, k as createCredentialInvalidator, l as extractDocumentModels, m as isSubgraphClass, o as pieceListLocation, p as buildGraphqlOperations, s as piecesFromCdnList, t as extractSubgraphs, u as buildGraphQlDocument, v as debounce, w as manifestDeclaredSubgraphs, x as loadDocumentModels, y as extractUpgradeManifests, z as RefusalNotRecordedError } from "./subgraph-extraction-zUDn2zX_.mjs";
5
+ import { A as getDocumentModelSubgraphName, C as createMergedSchema, D as generateDocumentModelSchema, E as findSubgraphTypeCollisions, F as reservedTypeNamesTaken, I as typeDefinitionNames, L as schema_default$1, M as getGeneratedDocumentModelTypes, N as hasOperationSchemas, O as generatedTypesOf, P as reservedTypeNames, S as buildSubgraphSchemaModule, T as documentModelSubgraphTypes, _ as describeOwnershipConflicts, a as inspectionAdminTypeDefs, b as assembleSubgraphTypeDefs, c as HOST_ORIGIN, d as byClaimPriority, f as decideAdmission, g as collectSubgraphClaims, h as supergraphClaimLosers, i as inspectionTypeDefs, j as getDocumentModelTypeDefs, k as getDocumentModelSchemaName, l as RegistrationOrder, m as documentModelSubgraphSources, n as systemTypeDefs, o as CORE_ORIGIN, p as describeOrigin, r as schema_default$2, s as DOCUMENT_MODEL_ORIGIN, t as baseDocumentModels, u as admitDocumentModels, v as DocumentModelSchemaCache, w as createSchema, x as buildDocumentModelSchema, y as SubgraphTypeCollisionError } from "./base-document-models-By4P20-z.mjs";
6
6
  import { n as createApolloFetchHandler } from "./adapter-gateway-apollo-D-EdZ4e-.mjs";
7
- import { d as PGLITE_UTC_PARSERS, i as resolvePgliteFsync, r as createDurableNodeFs } from "./error-info-CCQcLAcW.mjs";
8
- import { f as openCurrentPgliteForVerify, p as preparePgliteDataDir } from "./pglite-node-BOFT_yUj.mjs";
7
+ import { a as resolvePgliteMaintenance, i as resolvePgliteFsync, m as PGLITE_UTC_PARSERS, r as createDurableNodeFs } from "./error-info-BaEL50f5.mjs";
8
+ import { f as openCurrentPgliteForVerify, p as preparePgliteDataDir } from "./pglite-node-DOFZDYCK.mjs";
9
9
  import { findPackageJSON, isBuiltin } from "node:module";
10
10
  import { AnalyticsQueryEngine } from "@powerhousedao/analytics-engine-core";
11
11
  import { AnalyticsModel, AnalyticsResolvers, typedefs } from "@powerhousedao/analytics-engine-graphql";
12
12
  import { gql } from "graphql-tag";
13
13
  import { GraphQLError, Kind, OperationTypeNode, buildASTSchema, getOperationAST, isTypeDefinitionNode, isTypeExtensionNode, parse, print, validateSchema, valueFromASTUntyped, visit } from "graphql";
14
- import { AuthEnforcementDisabledError, BareReadGate, BatchJobFailedError, CATCH_UP_LOAD_WINDOW_MS, ChannelError, ChannelErrorSource, DEFAULT_DRIVE_CONTAINER_TYPES, DriveCollectionId, DriveInspection, InvalidDeadLetterCursorError, JOB_NOT_FOUND_ERROR_NAME, JobStatus, ModelReadGate, PropagationMode as PropagationMode$1, READ_ONLY_ACCESS, SyncOperation, SyncScopeGate, consolidateSyncOperations, createReactorHostModuleBase, createReactorInspector, driveIdFromUrl, envelopesToSyncOperations, isCatchUpLevel, parseDriveUrl, readDecisionModel, supportsPurgeRefusals, syncOperationErrorType, toWireCatchUpPriority, toWireDeadLetter, toWireQueueState } from "@powerhousedao/reactor";
14
+ import { AuthEnforcementDisabledError, BareReadGate, BatchJobFailedError, CATCH_UP_LOAD_WINDOW_MS, ChannelError, ChannelErrorSource, DEFAULT_DRIVE_CONTAINER_TYPES, DriveCollectionId, DriveInspection, FacadeWriteClient, InvalidDeadLetterCursorError, JOB_NOT_FOUND_ERROR_NAME, JobStatus, ModelReadGate, PropagationMode as PropagationMode$1, READ_ONLY_ACCESS, SyncOperation, SyncScopeGate, consolidateSyncOperations, createReactorHostModuleBase, createReactorInspector, driveIdFromUrl, envelopesToSyncOperations, isCatchUpLevel, parseDriveUrl, readDecisionModel, supportsPurgeRefusals, syncOperationErrorType, toWireCatchUpPriority, toWireDeadLetter, toWireQueueState, warnOnce } from "@powerhousedao/reactor";
15
15
  import { deserializeSignature, readPeerManifest, serializeSignature, setName, withSignaturePolicy } from "@powerhousedao/shared/document-model";
16
16
  import { fetchDelegationCredential, resolveSwitchboardEndpoint } from "@renown/sdk";
17
- import { ConsoleLogger, childLogger } from "document-model";
18
17
  import { AsyncLocalStorage } from "node:async_hooks";
18
+ import { ConsoleLogger, childLogger } from "document-model";
19
19
  import path, { isAbsolute, join } from "node:path";
20
20
  import { match } from "path-to-regexp";
21
21
  import posix from "node:path/posix";
22
22
  import { Readable } from "node:stream";
23
- import nodeFs, { existsSync, readFileSync, watchFile } from "node:fs";
24
23
  import { pipeline } from "node:stream/promises";
25
24
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
25
+ import nodeFs, { existsSync, readFileSync, watchFile } from "node:fs";
26
26
  import { monitorEventLoopDelay } from "node:perf_hooks";
27
27
  import { pathToFileURL } from "node:url";
28
28
  import { camelCase } from "change-case";
@@ -402,133 +402,6 @@ const WS_AUTH_CLOSE_REASONS = [
402
402
  WS_CLOSE_REASON_CREDENTIAL_REVOKED
403
403
  ];
404
404
  //#endregion
405
- //#region src/http/namespace.ts
406
- /**
407
- * A package's namespace is its npm name, used verbatim as one or two path
408
- * segments. Nothing is slugged: dropping the scope, folding `.`/`_` to `-` or
409
- * lower-casing would all map distinct package names onto one namespace, and a
410
- * lossy mapping means two packages can silently claim the same URL space.
411
- * Verbatim is injective, so there is no collision left to detect.
412
- */
413
- /**
414
- * npm's package-name grammar, per segment. Deliberately the same shape the HTTP
415
- * package loader validates with, so a name that can be installed can be routed.
416
- */
417
- const SEGMENT = /^[a-z0-9][-a-z0-9._]*$/i;
418
- /** Segments that would read as path traversal rather than as a name. */
419
- const TRAVERSAL = /* @__PURE__ */ new Set([".", ".."]);
420
- var InvalidNamespaceError = class extends Error {};
421
- /**
422
- * Turns a package name into the path segments it occupies.
423
- * `@powerhousedao/workflow` → ["@powerhousedao", "workflow"]
424
- * `document-model` → ["document-model"]
425
- */
426
- function namespaceSegments(packageName) {
427
- if (!packageName) throw new InvalidNamespaceError("Package name is empty");
428
- const scoped = packageName.startsWith("@");
429
- const parts = (scoped ? packageName.slice(1) : packageName).split("/");
430
- if (parts.length !== (scoped ? 2 : 1)) throw new InvalidNamespaceError(`"${packageName}" is not a package name: expected ${scoped ? "@scope/name" : "name"}`);
431
- for (const part of parts) if (TRAVERSAL.has(part) || !SEGMENT.test(part)) throw new InvalidNamespaceError(`"${packageName}" contains a segment that is not a valid npm name part: "${part}"`);
432
- return scoped ? [`@${parts[0]}`, parts[1]] : parts;
433
- }
434
- /**
435
- * The path a package's routes hang off, relative to the package prefix.
436
- * Scoped names occupy two segments — the addressing unpkg and jsdelivr use.
437
- */
438
- function namespacePath(packageName) {
439
- return namespaceSegments(packageName).join("/");
440
- }
441
- /**
442
- * The same path with the leading `@` percent-encoded. Both routers match the
443
- * raw pathname, so a client that percent-encodes each segment would otherwise
444
- * 404. Registering both spellings avoids decoding the pathname before matching,
445
- * which would turn `%2f` into `/` and let a crafted URL cross segment
446
- * boundaries. `%40` cannot introduce a boundary, which is what makes this safe.
447
- */
448
- function encodedNamespacePath(packageName) {
449
- const path = namespacePath(packageName);
450
- return path.startsWith("@") ? `%40${path.slice(1)}` : void 0;
451
- }
452
- /**
453
- * A route path a package supplied. Must be relative and must not climb out of
454
- * the scope.
455
- */
456
- function assertRelativeRoutePath(path) {
457
- if (path.startsWith("/")) throw new InvalidNamespaceError(`Route path "${path}" must be relative to the scope, not absolute`);
458
- if (/^[a-z][a-z0-9+.-]*:/i.test(path)) throw new InvalidNamespaceError(`Route path "${path}" must be a path, not a URL`);
459
- if (path.split("/").some((segment) => TRAVERSAL.has(segment))) throw new InvalidNamespaceError(`Route path "${path}" must not contain "." or ".." segments`);
460
- return path.replace(/^\/+|\/+$/g, "");
461
- }
462
- /**
463
- * Resolves the npm name a package is routed under from the key the package
464
- * manager holds it by. That key is the specifier as configured, which is not
465
- * always a name:
466
- * - `@scope/pkg` — already a name.
467
- * - `@scope/pkg@1.3.9` — a registry spec; only the loader strips the tag.
468
- * - `/Users/me/project` — the local project, which switchboard registers by
469
- * `process.cwd()`. Its real name lives in its package.json.
470
- *
471
- * Deriving a URL segment straight from the key would give a developer's home
472
- * directory a route namespace, so the path form is resolved rather than slugged.
473
- */
474
- function resolvePackageName(key, readPackageJsonName = defaultReadName) {
475
- const withoutVersion = stripVersionSpec(key);
476
- if (isPackageName(withoutVersion)) return withoutVersion;
477
- if (key.startsWith("/") || key.startsWith(".")) {
478
- const name = readPackageJsonName(key);
479
- if (name && isPackageName(name)) return name;
480
- throw new InvalidNamespaceError(`Package at "${key}" has no usable name in its package.json, so it cannot host routes`);
481
- }
482
- throw new InvalidNamespaceError(`"${key}" is not a package name and not a path, so it cannot host routes`);
483
- }
484
- function isPackageName(value) {
485
- try {
486
- namespaceSegments(value);
487
- return true;
488
- } catch {
489
- return false;
490
- }
491
- }
492
- /** `@scope/pkg@1.3.9` → `@scope/pkg`; `pkg@1.0.0` → `pkg`. */
493
- function stripVersionSpec(key) {
494
- const at = key.lastIndexOf("@");
495
- if (at <= 0) return key;
496
- return key.slice(0, at);
497
- }
498
- function defaultReadName(dir) {
499
- try {
500
- const raw = readFileSync(join(dir, "package.json"), "utf8");
501
- const parsed = JSON.parse(raw);
502
- return typeof parsed.name === "string" ? parsed.name : void 0;
503
- } catch {
504
- return;
505
- }
506
- }
507
- /**
508
- * A mount path the host named for one of its own route groups.
509
- *
510
- * The host owns the whole URL space — it holds the adapter — so unlike a
511
- * package it may name an absolute path. That is the difference between hosting
512
- * and being hosted, and it is why this lives on the service rather than on a
513
- * scope: a package is only ever handed a scope, and a scope has no way to
514
- * express a path outside itself.
515
- *
516
- * What the host still may not name is anything that is not one stable literal
517
- * prefix. A traversal segment, or a pattern segment, would make the group's own
518
- * routes unpredictable relative to each other. Returns the normalized path,
519
- * with a leading and no trailing slash.
520
- */
521
- function assertHostMountPath(path) {
522
- if (!path.startsWith("/")) throw new InvalidNamespaceError(`Host mount path "${path}" must be absolute, e.g. "/webhooks"`);
523
- const segments = path.split("/").filter((segment) => segment.length > 0);
524
- if (segments.length === 0) throw new InvalidNamespaceError(`Host mount path "${path}" is the whole URL space, which is the adapter rather than a scope of it`);
525
- for (const segment of segments) {
526
- if (TRAVERSAL.has(segment)) throw new InvalidNamespaceError(`Host mount path "${path}" must not contain "." or ".." segments`);
527
- if (segment.startsWith(":") || segment.includes("*")) throw new InvalidNamespaceError(`Host mount path "${path}" must be a literal prefix, not a pattern: "${segment}"`);
528
- }
529
- return `/${segments.join("/")}`;
530
- }
531
- //#endregion
532
405
  //#region src/http/node-response.ts
533
406
  /** Converts Node incoming headers to Fetch Headers. */
534
407
  function fetchHeaders(req) {
@@ -631,744 +504,877 @@ function writeError(res, status, message) {
631
504
  res.setHeader("content-length", Buffer.byteLength(body));
632
505
  res.end(body);
633
506
  }
634
- //#endregion
635
- //#region src/http/route-service.ts
636
- const logger$2 = childLogger(["reactor-api", "http-routes"]);
637
- /** The segment package routes live under, inside the host's base path. */
638
- const PACKAGE_ROUTE_SEGMENT = "api";
639
- /** The namespace core's own subgraphs and services register under. */
640
- const CORE_PACKAGE_NAME = "@powerhousedao/reactor-api";
641
- /** Generous enough for any request a route should be buffering at all. */
642
- const DEFAULT_MAX_BODY_BYTES$1 = 1048576;
643
- const ANONYMOUS = {
644
- user: void 0,
645
- authEnabled: false
507
+ /** Header each scheme reads when the caller does not name one: the name the format is
508
+ * most often carried in, not a property of it, so `WebhookVerification.header` overrides any of them. */
509
+ const DEFAULT_SCHEME_HEADER = {
510
+ none: "",
511
+ token: "x-webhook-token",
512
+ hmac: "x-signature",
513
+ "hmac-prefixed": "x-hub-signature-256",
514
+ "hmac-timestamped": "stripe-signature"
646
515
  };
647
- /** Owns the URL space packages serve from, handing each a scope bound to its own namespace. The prefix nests inside
648
- * the host's base path (`<basePath>/api`), so core collisions are prevented by URL shape, not a reserved-name list. */
649
- var HttpRouteService = class {
650
- #adapter;
651
- #authService;
652
- #prefix;
653
- #publicUrl;
654
- #trustProxy;
655
- #scopes = /* @__PURE__ */ new Map();
656
- #webhooks;
657
- constructor({ httpAdapter, basePath = "/", authService, webhooks, publicUrl = "", trustProxy = false }) {
658
- this.#adapter = httpAdapter;
659
- this.#authService = authService;
660
- this.#webhooks = webhooks;
661
- this.#publicUrl = publicUrl.replace(/\/+$/, "");
662
- this.#trustProxy = trustProxy;
663
- this.#prefix = posix.join("/", basePath, "api");
664
- }
665
- /** The absolute path packages are mounted under. */
666
- get prefix() {
667
- return this.#prefix;
668
- }
669
- /** The scope for a package; idempotent per name, so a reload cannot accumulate namespaces. Throws when two packages
670
- * resolve to one namespace — with verbatim names that means one package configured twice, a genuine ambiguity. */
671
- scopeFor(packageKey) {
672
- const packageName = resolvePackageName(packageKey);
673
- const namespace = namespacePath(packageName);
674
- const encoded = encodedNamespacePath(packageName);
675
- return this.#scope({
676
- owner: packageName,
677
- base: posix.join(this.#prefix, namespace),
678
- encodedBase: encoded ? posix.join(this.#prefix, encoded) : void 0,
679
- claim: `the route namespace "${namespace}"`,
680
- webhooks: this.#webhooks?.scopeFor(packageName),
681
- onDispose: () => this.#webhooks?.disposeScope(packageName)
682
- });
683
- }
684
- /** A scope at a host-named path; on the service, not `IHttpScope`, so a package can never name one. Namespacing is package
685
- * policy: the host owns its URL space and third parties hold its URLs, so the path is verbatim and outside the package prefix. */
686
- hostScope(name, mountPath) {
687
- const base = assertHostMountPath(mountPath);
688
- if (base === this.#prefix || base.startsWith(`${this.#prefix}/`)) throw new InvalidNamespaceError(`Host scope "${name}" cannot mount at "${base}": that is the package route prefix, which packages own`);
689
- return this.#scope({
690
- owner: name,
691
- base,
692
- encodedBase: void 0,
693
- claim: `the mount path "${base}"`,
694
- webhooks: void 0,
695
- onDispose: () => void 0
696
- });
516
+ const OK = { ok: true };
517
+ /** Constant-time over equal-length inputs; a length mismatch is already a rejection, so
518
+ * the early return leaks nothing a caller could not measure. */
519
+ function secureEquals(a, b) {
520
+ const left = Buffer.from(a, "utf8");
521
+ const right = Buffer.from(b, "utf8");
522
+ if (left.length !== right.length) return false;
523
+ return timingSafeEqual(left, right);
524
+ }
525
+ function hmacDigest(secret, payload, verification) {
526
+ return createHmac(verification.algorithm ?? "sha256", secret).update(payload).digest(verification.encoding ?? "hex");
527
+ }
528
+ /** Hex folds case, so an uppercased digest still verifies. Base64 must not: two distinct
529
+ * digests can differ only in case, so folding there would accept a signature that is not the one computed. */
530
+ function digestEquals(presented, expected, verification) {
531
+ const candidate = presented.trim();
532
+ if ((verification.encoding ?? "hex") === "base64") return secureEquals(candidate, expected);
533
+ return secureEquals(candidate.toLowerCase(), expected.toLowerCase());
534
+ }
535
+ /** The label `hmac-prefixed` expects before the digest. */
536
+ function signaturePrefix(verification) {
537
+ return verification.prefix ?? `${verification.algorithm ?? "sha256"}=`;
538
+ }
539
+ /** `t=<unix>,v1=<hex>[,v1=<hex>…]`. Several `v1` values appear while a secret is being
540
+ * rotated, and any one of them matching is a pass. */
541
+ function parseTimestampedHeader(value) {
542
+ const signatures = [];
543
+ let timestamp;
544
+ for (const part of value.split(",")) {
545
+ const separator = part.indexOf("=");
546
+ if (separator < 0) continue;
547
+ const key = part.slice(0, separator).trim();
548
+ const item = part.slice(separator + 1).trim();
549
+ if (key === "t") timestamp = Number(item);
550
+ else if (key === "v1") signatures.push(item);
697
551
  }
698
- /** Idempotent per base path, so a package reload cannot accumulate namespaces. Two owners wanting one path is an error —
699
- * with verbatim names that needs one package configured twice at different versions, a genuine ambiguity, not a clash. */
700
- #scope(options) {
701
- const { owner, base } = options;
702
- const existing = this.#scopes.get(base);
703
- if (existing) {
704
- if (existing.owner !== owner) throw new Error(`"${owner}" wants ${options.claim}, which "${existing.owner}" already holds`);
705
- return existing;
706
- }
707
- const scope = new HttpScope({
708
- owner,
709
- base,
710
- encodedBase: options.encodedBase,
711
- publicUrl: this.#publicUrl,
712
- trustProxy: this.#trustProxy,
713
- adapter: this.#adapter,
714
- authService: this.#authService,
715
- webhooks: options.webhooks,
716
- onDispose: () => {
717
- this.#scopes.delete(base);
718
- options.onDispose();
719
- }
720
- });
721
- this.#scopes.set(base, scope);
722
- return scope;
723
- }
724
- /** Like {@link scopeFor}, but never throws: a key resolving to no usable npm name gets a scope that refuses
725
- * registrations, so one unroutable package cannot stop the host booting — it fails only if it serves a route. */
726
- scopeForOrNull(packageKey) {
727
- try {
728
- return this.scopeFor(packageKey);
729
- } catch (error) {
730
- if (!(error instanceof InvalidNamespaceError)) throw error;
731
- logger$2.warn("Package \"@package\" cannot host HTTP routes: @reason", packageKey, error.message);
732
- return new UnroutableScope(packageKey, error.message);
552
+ return {
553
+ timestamp,
554
+ signatures
555
+ };
556
+ }
557
+ function schemeHeader(verification) {
558
+ return (verification.header ?? DEFAULT_SCHEME_HEADER[verification.scheme]).toLowerCase();
559
+ }
560
+ /** Verifies a delivery against the configured scheme; `raw` must be the exact bytes
561
+ * received. The reason is for the log only: callers answer a fixed 401, so a probing sender learns nothing from the body. */
562
+ function verifyWebhook(options) {
563
+ const { verification, headers, raw } = options;
564
+ if (verification.scheme === "none") return OK;
565
+ if (!verification.secret) return {
566
+ ok: false,
567
+ reason: "signing secret missing"
568
+ };
569
+ const header = schemeHeader(verification);
570
+ const presented = headers[header];
571
+ if (!presented) return {
572
+ ok: false,
573
+ reason: `header "${header}" absent`
574
+ };
575
+ const secret = verification.secret;
576
+ const tolerance = verification.toleranceSeconds ?? 300;
577
+ switch (verification.scheme) {
578
+ case "token": return secureEquals(presented, secret) ? OK : {
579
+ ok: false,
580
+ reason: "token mismatch"
581
+ };
582
+ case "hmac": return digestEquals(presented, hmacDigest(secret, raw, verification), verification) ? OK : {
583
+ ok: false,
584
+ reason: "hmac mismatch"
585
+ };
586
+ case "hmac-prefixed": return digestEquals(presented, `${signaturePrefix(verification)}${hmacDigest(secret, raw, verification)}`, verification) ? OK : {
587
+ ok: false,
588
+ reason: "hmac mismatch"
589
+ };
590
+ case "hmac-timestamped": {
591
+ const { timestamp, signatures } = parseTimestampedHeader(presented);
592
+ if (timestamp === void 0 || !Number.isFinite(timestamp)) return {
593
+ ok: false,
594
+ reason: "no timestamp in the signature header"
595
+ };
596
+ if (signatures.length === 0) return {
597
+ ok: false,
598
+ reason: "no v1 signature in the header"
599
+ };
600
+ const nowMs = (options.now ?? /* @__PURE__ */ new Date()).getTime();
601
+ if (Math.abs(nowMs / 1e3 - timestamp) > tolerance) return {
602
+ ok: false,
603
+ reason: "timestamp outside the replay window"
604
+ };
605
+ const expected = hmacDigest(secret, Buffer.concat([Buffer.from(`${timestamp}.`, "utf8"), raw]), verification);
606
+ let matched = false;
607
+ for (const signature of signatures) if (digestEquals(signature, expected, verification)) matched = true;
608
+ return matched ? OK : {
609
+ ok: false,
610
+ reason: "hmac mismatch"
611
+ };
733
612
  }
734
613
  }
735
- /** Releases a package's routes, e.g. when it is replaced or removed. */
736
- disposeScope(packageKey) {
737
- try {
738
- const namespace = namespacePath(resolvePackageName(packageKey));
739
- this.#scopes.get(posix.join(this.#prefix, namespace))?.dispose();
740
- } catch (error) {
741
- if (!(error instanceof InvalidNamespaceError)) throw error;
742
- }
614
+ }
615
+ /** Headers that would put a credential in a log or run journal. The configured signature
616
+ * header joins them: it is an HMAC of the body under a live secret. */
617
+ const REDACTED_HEADERS = /* @__PURE__ */ new Set([
618
+ "authorization",
619
+ "proxy-authorization",
620
+ "cookie",
621
+ "set-cookie",
622
+ "x-api-key",
623
+ "x-webhook-token",
624
+ "x-signature",
625
+ "x-hub-signature",
626
+ "x-hub-signature-256",
627
+ "stripe-signature"
628
+ ]);
629
+ const REDACTED = "[redacted]";
630
+ function redactHeaders(headers, extra) {
631
+ const redacted = {};
632
+ for (const [name, value] of Object.entries(headers)) {
633
+ const key = name.toLowerCase();
634
+ redacted[key] = REDACTED_HEADERS.has(key) || extra && key === extra.toLowerCase() ? REDACTED : value;
743
635
  }
744
- disposeAll() {
745
- for (const scope of [...this.#scopes.values()]) scope.dispose();
636
+ return redacted;
637
+ }
638
+ /** JSON and form bodies become objects; anything else stays decoded text, so a verified
639
+ * XML or CSV payload is still reachable downstream. */
640
+ function parseWebhookBody(raw, contentType) {
641
+ if (raw.length === 0) return void 0;
642
+ const type = (contentType ?? "").split(";")[0].trim().toLowerCase();
643
+ const text = raw.toString("utf8");
644
+ if (type === "application/json" || type.endsWith("+json")) try {
645
+ return JSON.parse(text);
646
+ } catch {
647
+ return text;
746
648
  }
747
- };
748
- var HttpScope = class {
749
- owner;
750
- #base;
649
+ if (type === "application/x-www-form-urlencoded") return Object.fromEntries(new URLSearchParams(text));
650
+ return text;
651
+ }
652
+ //#endregion
653
+ //#region src/http/webhook-service.ts
654
+ const logger$2 = childLogger(["reactor-api", "webhooks"]);
655
+ /** The flat, token-addressed path family. */
656
+ const WEBHOOK_SEGMENT = "webhooks";
657
+ const DEFAULT_MAX_BODY_BYTES$1 = 1048576;
658
+ const DEFAULT_DEDUPE_TTL_SECONDS = 300;
659
+ function readPublicOrigin(origin) {
660
+ return (typeof origin === "function" ? origin() : origin).replace(/\/+$/, "");
661
+ }
662
+ /** One host route for `/webhooks/:token`, dispatching by token. The flat path leaks
663
+ * neither package nor document; the namespace lives in the token record, which is also what stops one package's token reaching another's handler. */
664
+ var WebhookService = class {
665
+ #store;
666
+ #path;
751
667
  #publicUrl;
752
- #trustProxy;
753
- #encodedBase;
754
- #adapter;
755
- #authService;
756
- #onDispose;
668
+ #scope;
757
669
  #registrations = /* @__PURE__ */ new Map();
758
- #webhooks;
759
- constructor(options) {
760
- this.owner = options.owner;
761
- this.#base = options.base;
762
- this.#publicUrl = options.publicUrl;
763
- this.#trustProxy = options.trustProxy;
764
- this.#encodedBase = options.encodedBase;
765
- this.#adapter = options.adapter;
766
- this.#authService = options.authService;
767
- this.#onDispose = options.onDispose;
768
- this.#webhooks = options.webhooks ?? unavailableWebhooks(options.owner);
769
- }
770
- get baseUrl() {
771
- return `${this.#publicUrl}${this.#base}`;
772
- }
773
- get webhooks() {
774
- return this.#webhooks;
775
- }
776
- get(path, a, b) {
777
- return this.#shorthand("GET", path, a, b);
778
- }
779
- post(path, a, b) {
780
- return this.#shorthand("POST", path, a, b);
670
+ #routes = [];
671
+ constructor({ store, basePath = "/", publicUrl }) {
672
+ this.#store = store;
673
+ this.#path = posix.join("/", basePath, WEBHOOK_SEGMENT);
674
+ this.#publicUrl = publicUrl;
781
675
  }
782
- put(path, a, b) {
783
- return this.#shorthand("PUT", path, a, b);
676
+ /** The scope the endpoint family serves from, handed over once the route service exists;
677
+ * separate from the constructor only because that service takes this one as an option. */
678
+ attach(scope) {
679
+ this.#scope = scope;
784
680
  }
785
- patch(path, a, b) {
786
- return this.#shorthand("PATCH", path, a, b);
681
+ async init() {
682
+ await this.#store.init();
683
+ if (this.#routes.length) return;
684
+ if (!this.#scope) throw new Error("The webhook service has no HTTP scope; the host must call attach() before a package registers");
685
+ this.#routes = [this.#scope.nodeRoute({
686
+ method: [
687
+ "DELETE",
688
+ "GET",
689
+ "HEAD",
690
+ "PATCH",
691
+ "POST",
692
+ "PUT"
693
+ ],
694
+ path: ":token",
695
+ auth: "public",
696
+ handler: (req, res, ctx) => void this.#deliver(req, res, ctx.params)
697
+ })];
787
698
  }
788
- delete(path, a, b) {
789
- return this.#shorthand("DELETE", path, a, b);
699
+ dispose() {
700
+ for (const handle of this.#routes) handle.dispose();
701
+ this.#routes = [];
702
+ this.#registrations.clear();
790
703
  }
791
- head(path, a, b) {
792
- return this.#shorthand("HEAD", path, a, b);
704
+ /** The facade a package's HTTP scope exposes as `scope.webhooks`. */
705
+ scopeFor(namespace) {
706
+ return {
707
+ hasPublicOrigin: this.hasPublicOrigin,
708
+ register: async (spec) => {
709
+ await this.init();
710
+ const key = `${namespace}|${spec.name}`;
711
+ this.#registrations.set(key, {
712
+ namespace,
713
+ spec
714
+ });
715
+ return {
716
+ endpointFor: async (ownerKey) => {
717
+ const row = await this.#store.ensure(namespace, spec.name, ownerKey);
718
+ return {
719
+ token: row.token,
720
+ url: this.urlFor(row.token),
721
+ createdAt: row.createdAt
722
+ };
723
+ },
724
+ revoke: (ownerKey) => this.#store.revoke(namespace, spec.name, ownerKey),
725
+ list: async () => (await this.#store.list(namespace, spec.name)).map((row) => ({
726
+ key: row.ownerKey,
727
+ token: row.token,
728
+ url: this.urlFor(row.token),
729
+ createdAt: row.createdAt
730
+ }))
731
+ };
732
+ }
733
+ };
793
734
  }
794
- #shorthand(method, path, a, b) {
795
- const options = typeof a === "function" ? {} : a;
796
- const handler = typeof a === "function" ? a : b;
797
- if (!handler) throw new Error(`Route ${method} ${path} was registered with no handler`);
798
- return this.route({
799
- ...options,
800
- method,
801
- path,
802
- handler
803
- });
735
+ /** Releases every registration a package made. */
736
+ disposeScope(namespace) {
737
+ for (const [key, registration] of this.#registrations) if (registration.namespace === namespace) this.#registrations.delete(key);
804
738
  }
805
- route(spec) {
806
- const body = spec.body ?? "parsed";
807
- return this.#register(spec, (req, res, ctx) => this.#serve(spec, body, req, res, ctx));
739
+ /** The URL to hand a provider. Absolute whenever the host knows its own origin: a
740
+ * relative path is useless to the third party that has to call it. */
741
+ urlFor(token) {
742
+ const path = posix.join(this.#path, token);
743
+ return this.#publicUrl === void 0 ? path : `${readPublicOrigin(this.#publicUrl)}${path}`;
808
744
  }
809
- nodeRoute(spec) {
810
- return this.#register(spec, (req, res, ctx) => spec.handler(req, res, ctx));
745
+ /** Whether `urlFor` can produce something a provider could call. */
746
+ get hasPublicOrigin() {
747
+ return this.#publicUrl !== void 0;
811
748
  }
812
- dispose() {
813
- for (const registration of this.#registrations.values()) for (const handle of registration.handles) handle.dispose();
814
- this.#registrations.clear();
815
- this.#onDispose();
816
- }
817
- /** Mounts one route under this scope's namespace, in both the verbatim and the
818
- * percent-encoded spelling of a scoped name. */
819
- #register(spec, run) {
820
- const relative = assertRelativeRoutePath(spec.path);
821
- const methods = Array.isArray(spec.method) ? spec.method : [spec.method];
822
- const routePath = relative ? posix.join(this.#base, relative) : this.#base;
823
- const key = `${methods.join(",")} ${routePath}`;
824
- if (this.#registrations.has(key)) throw new Error(`Route ${key} is already registered by "${this.owner}"`);
825
- const handles = [];
826
- const paths = [routePath];
827
- if (this.#encodedBase) paths.push(relative ? posix.join(this.#encodedBase, relative) : this.#encodedBase);
828
- for (const path of paths) for (const method of methods) handles.push(this.#adapter.mountNodeRoute(method, path, (req, res) => {
829
- this.#guard(spec, req, res, run);
830
- }, {
831
- rawBody: true,
832
- prefix: spec.prefix
833
- }));
834
- this.#registrations.set(key, {
835
- path: routePath,
836
- handles
837
- });
838
- logger$2.debug("Registered @route for @package", key, this.owner);
839
- return {
840
- url: `${this.#publicUrl}${routePath}`,
841
- dispose: () => {
842
- const registration = this.#registrations.get(key);
843
- if (!registration) return;
844
- for (const handle of registration.handles) handle.dispose();
845
- this.#registrations.delete(key);
846
- }
847
- };
848
- }
849
- /** Authenticate, then run. */
850
- async #guard(spec, req, res, run) {
851
- try {
852
- const actor = await this.#authenticate(spec.auth ?? "renown", req, res);
853
- if (actor === REJECTED) return;
854
- await run(req, res, {
855
- params: routeParams(req),
856
- user: actor?.user,
857
- authEnabled: actor?.authEnabled ?? false,
858
- transport: resolveTransport(req, this.#trustProxy)
859
- });
860
- } catch (error) {
861
- logger$2.error("Route handler failed for @package", this.owner, error);
862
- writeError(res, 500, "Internal server error");
863
- }
864
- }
865
- /** Resolves the caller, answering the request itself when the route refuses it;
866
- * returns REJECTED in that case so the caller stops. */
867
- async #authenticate(auth, req, res) {
868
- if (auth === "public") return void 0;
869
- if (typeof auth === "function") {
870
- const result = await auth(req);
871
- if (!result.authorized) {
872
- if ("response" in result) await writeResponse(res, result.response, req.method ?? "GET");
873
- else writeError(res, result.status, result.message);
874
- return REJECTED;
875
- }
749
+ async #deliver(req, res, params) {
750
+ const token = params.token;
751
+ if (!token) {
752
+ writeError(res, 404, "Unknown endpoint");
876
753
  return;
877
754
  }
878
- if (!this.#authService) return ANONYMOUS;
879
- const result = await this.#authService.verifyBearer(req.headers.authorization);
880
- if (result instanceof Response) {
881
- await writeResponse(res, result, req.method ?? "GET");
882
- return REJECTED;
883
- }
884
- if (result.auth_enabled && !result.user && auth === "renown") {
885
- writeError(res, 401, "Authentication required");
886
- return REJECTED;
887
- }
888
- return {
889
- user: result.user,
890
- authEnabled: result.auth_enabled
891
- };
892
- }
893
- /** Builds the Fetch Request from the raw stream and runs the handler. */
894
- async #serve(spec, body, req, res, ctx) {
895
- const method = req.method ?? "GET";
896
- const url = `${ctx.transport.baseUrl}${req.url ?? "/"}`;
897
- const controller = new AbortController();
898
- req.once("close", () => controller.abort());
899
- let raw;
900
- let init = {
901
- method,
902
- headers: fetchHeaders(req),
903
- signal: controller.signal
904
- };
905
- if (method !== "GET" && method !== "HEAD" && body !== "none") {
906
- if (body === "stream") init = {
907
- ...init,
908
- body: Readable.toWeb(req),
909
- duplex: "half"
755
+ try {
756
+ const row = await this.#store.find(token);
757
+ if (!row) {
758
+ writeError(res, 404, "Unknown endpoint");
759
+ return;
760
+ }
761
+ const registrationKey = `${row.namespace}|${row.endpoint}`;
762
+ const registration = this.#registrations.get(registrationKey);
763
+ if (!registration) {
764
+ writeError(res, 503, "Endpoint temporarily unavailable");
765
+ return;
766
+ }
767
+ const { spec } = registration;
768
+ const method = (req.method ?? "POST").toUpperCase();
769
+ const perEndpoint = spec.policyFor ? await spec.policyFor(row.ownerKey) : {};
770
+ if (!perEndpoint) {
771
+ writeError(res, 404, "Unknown endpoint");
772
+ return;
773
+ }
774
+ const policy = {
775
+ ...spec.defaults,
776
+ ...perEndpoint
910
777
  };
911
- else {
912
- try {
913
- raw = await readBody(req, spec.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES$1);
914
- } catch (error) {
915
- if (error instanceof BodyTooLargeError) {
916
- res.setHeader("connection", "close");
917
- res.once("finish", () => req.destroy());
918
- writeError(res, 413, "Payload too large");
919
- return;
920
- }
921
- throw error;
778
+ if (policy.methods && !policy.methods.includes(method)) {
779
+ writeError(res, 405, "Method not allowed");
780
+ return;
781
+ }
782
+ let raw;
783
+ try {
784
+ raw = await readBody(req, policy.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES$1);
785
+ } catch (error) {
786
+ if (error instanceof BodyTooLargeError) {
787
+ res.setHeader("connection", "close");
788
+ res.once("finish", () => req.destroy());
789
+ writeError(res, 413, "Payload too large");
790
+ return;
922
791
  }
923
- if (raw.length) init = {
924
- ...init,
925
- body: new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength)
926
- };
792
+ throw error;
793
+ }
794
+ const verification = policy.verify;
795
+ if (verification) {
796
+ const result = verifyWebhook({
797
+ verification,
798
+ headers: headerRecord(req),
799
+ raw
800
+ });
801
+ if (!result.ok) {
802
+ logger$2.warn("Rejected webhook delivery for @package/@endpoint: @reason", row.namespace, row.endpoint, result.reason);
803
+ writeError(res, 401, "Signature verification failed");
804
+ return;
805
+ }
806
+ }
807
+ const url = new URL(req.url ?? "/", "http://localhost");
808
+ const queryParams = Object.fromEntries(url.searchParams);
809
+ const signatureHeader = verification ? schemeHeader(verification) : void 0;
810
+ const headers = headerRecord(req);
811
+ const body = parseWebhookBody(raw, headers["content-type"]);
812
+ const challenge = challengeValue(policy.challengeField, queryParams, headers, body);
813
+ if (challenge !== void 0) {
814
+ res.statusCode = 200;
815
+ res.setHeader("content-type", "text/plain");
816
+ res.end(challenge);
817
+ return;
818
+ }
819
+ let recordedKey;
820
+ if (policy.dedupe) {
821
+ const key = dedupeKey(policy.dedupe.field, queryParams, headers, body);
822
+ recordedKey = key;
823
+ if (key !== void 0 && await this.#store.seen(token, key, policy.dedupe.ttlSeconds ?? DEFAULT_DEDUPE_TTL_SECONDS)) {
824
+ res.statusCode = 200;
825
+ res.end();
826
+ return;
827
+ }
828
+ }
829
+ const reply = await spec.onRequest({
830
+ key: row.ownerKey,
831
+ method,
832
+ path: url.pathname,
833
+ queryParams,
834
+ headers: redactHeaders(headers, signatureHeader),
835
+ raw,
836
+ body
837
+ });
838
+ if (reply.unprocessed === true && recordedKey !== void 0) try {
839
+ await this.#store.forget(token, recordedKey);
840
+ } catch (error) {
841
+ logger$2.warn("Could not forget an unprocessed webhook delivery: @error", error);
927
842
  }
843
+ res.statusCode = reply.status;
844
+ if (reply.body !== void 0 && method !== "HEAD") {
845
+ res.setHeader("content-type", reply.contentType ?? "text/plain");
846
+ res.end(reply.body);
847
+ } else res.end();
848
+ } catch (error) {
849
+ logger$2.error("Webhook delivery failed for @method", req.method, error);
850
+ writeError(res, 500, "Internal server error");
928
851
  }
929
- await writeResponse(res, await spec.handler(new Request(url, init), {
930
- ...ctx,
931
- rawBody: body === "raw" ? raw ?? Buffer.alloc(0) : void 0,
932
- signal: controller.signal
933
- }), method);
934
852
  }
935
853
  };
936
- const REJECTED = Symbol("rejected");
937
- function routeParams(req) {
938
- const params = req.params;
939
- if (!params || typeof params !== "object") return {};
940
- const out = {};
941
- for (const [key, value] of Object.entries(params)) if (typeof value === "string") out[key] = value;
942
- else if (Array.isArray(value)) out[key] = value.join("/");
943
- return out;
854
+ function headerRecord(req) {
855
+ const headers = {};
856
+ for (const [name, value] of Object.entries(req.headers)) {
857
+ if (value === void 0) continue;
858
+ headers[name.toLowerCase()] = Array.isArray(value) ? value.join(", ") : value;
859
+ }
860
+ return headers;
944
861
  }
945
- /** Stands in for a package that cannot be routed — its key resolves to no npm name. Registering a route throws with
946
- * the reason; nothing else does, so the package still loads and its non-HTTP behaviour is unaffected. */
947
- var UnroutableScope = class {
948
- owner;
949
- baseUrl = "";
950
- #reason;
951
- constructor(packageKey, reason) {
952
- this.owner = packageKey;
953
- this.#reason = reason;
862
+ function scalar(value) {
863
+ if (typeof value === "string" && value !== "") return value;
864
+ if (typeof value === "number") return String(value);
865
+ }
866
+ /** Walks a dot-separated path into the parsed body. */
867
+ function bodyPath(path, body) {
868
+ let current = body;
869
+ for (const segment of path.split(".")) {
870
+ if (!current || typeof current !== "object") return void 0;
871
+ current = current[segment];
954
872
  }
955
- #refuse() {
956
- throw new Error(`Package "${this.owner}" cannot host HTTP routes: ${this.#reason}`);
873
+ return scalar(current);
874
+ }
875
+ /** Resolves where a provider put a value. A bare string means query first, then a
876
+ * top-level body field; `{ header }` and `{ body }` reach what that cannot — GitHub's delivery id is a header, Stripe's event id is nested. */
877
+ function fieldValue(field, queryParams, headers, body) {
878
+ if (typeof field === "object") return "header" in field ? scalar(headers[field.header.toLowerCase()]) : bodyPath(field.body, body);
879
+ const fromQuery = scalar(queryParams[field]);
880
+ if (fromQuery !== void 0) return fromQuery;
881
+ return body && typeof body === "object" ? scalar(body[field]) : void 0;
882
+ }
883
+ function challengeValue(field, queryParams, headers, body) {
884
+ return field === void 0 ? void 0 : fieldValue(field, queryParams, headers, body);
885
+ }
886
+ function dedupeKey(field, queryParams, headers, body) {
887
+ return fieldValue(field, queryParams, headers, body);
888
+ }
889
+ //#endregion
890
+ //#region src/http/namespace.ts
891
+ /**
892
+ * A package's namespace is its npm name, used verbatim as one or two path
893
+ * segments. Nothing is slugged: dropping the scope, folding `.`/`_` to `-` or
894
+ * lower-casing would all map distinct package names onto one namespace, and a
895
+ * lossy mapping means two packages can silently claim the same URL space.
896
+ * Verbatim is injective, so there is no collision left to detect.
897
+ */
898
+ /**
899
+ * npm's package-name grammar, per segment. Deliberately the same shape the HTTP
900
+ * package loader validates with, so a name that can be installed can be routed.
901
+ */
902
+ const SEGMENT = /^[a-z0-9][-a-z0-9._]*$/i;
903
+ /** Segments that would read as path traversal rather than as a name. */
904
+ const TRAVERSAL = /* @__PURE__ */ new Set([".", ".."]);
905
+ var InvalidNamespaceError = class extends Error {};
906
+ /**
907
+ * Turns a package name into the path segments it occupies.
908
+ * `@powerhousedao/workflow` → ["@powerhousedao", "workflow"]
909
+ * `document-model` → ["document-model"]
910
+ */
911
+ function namespaceSegments(packageName) {
912
+ if (!packageName) throw new InvalidNamespaceError("Package name is empty");
913
+ const scoped = packageName.startsWith("@");
914
+ const parts = (scoped ? packageName.slice(1) : packageName).split("/");
915
+ if (parts.length !== (scoped ? 2 : 1)) throw new InvalidNamespaceError(`"${packageName}" is not a package name: expected ${scoped ? "@scope/name" : "name"}`);
916
+ for (const part of parts) if (TRAVERSAL.has(part) || !SEGMENT.test(part)) throw new InvalidNamespaceError(`"${packageName}" contains a segment that is not a valid npm name part: "${part}"`);
917
+ return scoped ? [`@${parts[0]}`, parts[1]] : parts;
918
+ }
919
+ /**
920
+ * The path a package's routes hang off, relative to the package prefix.
921
+ * Scoped names occupy two segments — the addressing unpkg and jsdelivr use.
922
+ */
923
+ function namespacePath(packageName) {
924
+ return namespaceSegments(packageName).join("/");
925
+ }
926
+ /**
927
+ * The same path with the leading `@` percent-encoded. Both routers match the
928
+ * raw pathname, so a client that percent-encodes each segment would otherwise
929
+ * 404. Registering both spellings avoids decoding the pathname before matching,
930
+ * which would turn `%2f` into `/` and let a crafted URL cross segment
931
+ * boundaries. `%40` cannot introduce a boundary, which is what makes this safe.
932
+ */
933
+ function encodedNamespacePath(packageName) {
934
+ const path = namespacePath(packageName);
935
+ return path.startsWith("@") ? `%40${path.slice(1)}` : void 0;
936
+ }
937
+ /**
938
+ * A route path a package supplied. Must be relative and must not climb out of
939
+ * the scope.
940
+ */
941
+ function assertRelativeRoutePath(path) {
942
+ if (path.startsWith("/")) throw new InvalidNamespaceError(`Route path "${path}" must be relative to the scope, not absolute`);
943
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path)) throw new InvalidNamespaceError(`Route path "${path}" must be a path, not a URL`);
944
+ if (path.split("/").some((segment) => TRAVERSAL.has(segment))) throw new InvalidNamespaceError(`Route path "${path}" must not contain "." or ".." segments`);
945
+ return path.replace(/^\/+|\/+$/g, "");
946
+ }
947
+ /**
948
+ * Resolves the npm name a package is routed under from the key the package
949
+ * manager holds it by. That key is the specifier as configured, which is not
950
+ * always a name:
951
+ * - `@scope/pkg` — already a name.
952
+ * - `@scope/pkg@1.3.9` — a registry spec; only the loader strips the tag.
953
+ * - `/Users/me/project` — the local project, which switchboard registers by
954
+ * `process.cwd()`. Its real name lives in its package.json.
955
+ *
956
+ * Deriving a URL segment straight from the key would give a developer's home
957
+ * directory a route namespace, so the path form is resolved rather than slugged.
958
+ */
959
+ function resolvePackageName(key, readPackageJsonName = defaultReadName) {
960
+ const withoutVersion = stripVersionSpec(key);
961
+ if (isPackageName(withoutVersion)) return withoutVersion;
962
+ if (key.startsWith("/") || key.startsWith(".")) {
963
+ const name = readPackageJsonName(key);
964
+ if (name && isPackageName(name)) return name;
965
+ throw new InvalidNamespaceError(`Package at "${key}" has no usable name in its package.json, so it cannot host routes`);
957
966
  }
958
- get() {
959
- this.#refuse();
967
+ throw new InvalidNamespaceError(`"${key}" is not a package name and not a path, so it cannot host routes`);
968
+ }
969
+ function isPackageName(value) {
970
+ try {
971
+ namespaceSegments(value);
972
+ return true;
973
+ } catch {
974
+ return false;
960
975
  }
961
- post() {
962
- this.#refuse();
976
+ }
977
+ /** `@scope/pkg@1.3.9` → `@scope/pkg`; `pkg@1.0.0` → `pkg`. */
978
+ function stripVersionSpec(key) {
979
+ const at = key.lastIndexOf("@");
980
+ if (at <= 0) return key;
981
+ return key.slice(0, at);
982
+ }
983
+ function defaultReadName(dir) {
984
+ try {
985
+ const raw = readFileSync(join(dir, "package.json"), "utf8");
986
+ const parsed = JSON.parse(raw);
987
+ return typeof parsed.name === "string" ? parsed.name : void 0;
988
+ } catch {
989
+ return;
963
990
  }
964
- put() {
965
- this.#refuse();
991
+ }
992
+ /**
993
+ * A mount path the host named for one of its own route groups.
994
+ *
995
+ * The host owns the whole URL space — it holds the adapter — so unlike a
996
+ * package it may name an absolute path. That is the difference between hosting
997
+ * and being hosted, and it is why this lives on the service rather than on a
998
+ * scope: a package is only ever handed a scope, and a scope has no way to
999
+ * express a path outside itself.
1000
+ *
1001
+ * What the host still may not name is anything that is not one stable literal
1002
+ * prefix. A traversal segment, or a pattern segment, would make the group's own
1003
+ * routes unpredictable relative to each other. Returns the normalized path,
1004
+ * with a leading and no trailing slash.
1005
+ */
1006
+ function assertHostMountPath(path) {
1007
+ if (!path.startsWith("/")) throw new InvalidNamespaceError(`Host mount path "${path}" must be absolute, e.g. "/webhooks"`);
1008
+ const segments = path.split("/").filter((segment) => segment.length > 0);
1009
+ if (segments.length === 0) throw new InvalidNamespaceError(`Host mount path "${path}" is the whole URL space, which is the adapter rather than a scope of it`);
1010
+ for (const segment of segments) {
1011
+ if (TRAVERSAL.has(segment)) throw new InvalidNamespaceError(`Host mount path "${path}" must not contain "." or ".." segments`);
1012
+ if (segment.startsWith(":") || segment.includes("*")) throw new InvalidNamespaceError(`Host mount path "${path}" must be a literal prefix, not a pattern: "${segment}"`);
966
1013
  }
967
- patch() {
968
- this.#refuse();
1014
+ return `/${segments.join("/")}`;
1015
+ }
1016
+ //#endregion
1017
+ //#region src/http/route-service.ts
1018
+ const logger$1 = childLogger(["reactor-api", "http-routes"]);
1019
+ /** The segment package routes live under, inside the host's base path. */
1020
+ const PACKAGE_ROUTE_SEGMENT = "api";
1021
+ /** The namespace core's own subgraphs and services register under. */
1022
+ const CORE_PACKAGE_NAME = "@powerhousedao/reactor-api";
1023
+ /** Generous enough for any request a route should be buffering at all. */
1024
+ const DEFAULT_MAX_BODY_BYTES = 1048576;
1025
+ const ANONYMOUS = {
1026
+ user: void 0,
1027
+ authEnabled: false
1028
+ };
1029
+ /** Owns the URL space packages serve from, handing each a scope bound to its own namespace. The prefix nests inside
1030
+ * the host's base path (`<basePath>/api`), so core collisions are prevented by URL shape, not a reserved-name list. */
1031
+ var HttpRouteService = class {
1032
+ #adapter;
1033
+ #authService;
1034
+ #prefix;
1035
+ #publicUrl;
1036
+ #trustProxy;
1037
+ #scopes = /* @__PURE__ */ new Map();
1038
+ #webhooks;
1039
+ constructor({ httpAdapter, basePath = "/", authService, webhooks, publicUrl = "", trustProxy = false }) {
1040
+ this.#adapter = httpAdapter;
1041
+ this.#authService = authService;
1042
+ this.#webhooks = webhooks;
1043
+ this.#publicUrl = publicUrl;
1044
+ this.#trustProxy = trustProxy;
1045
+ this.#prefix = posix.join("/", basePath, "api");
969
1046
  }
970
- delete() {
971
- this.#refuse();
1047
+ /** The absolute path packages are mounted under. */
1048
+ get prefix() {
1049
+ return this.#prefix;
972
1050
  }
973
- head() {
974
- this.#refuse();
1051
+ /** The scope for a package; idempotent per name, so a reload cannot accumulate namespaces. Throws when two packages
1052
+ * resolve to one namespace — with verbatim names that means one package configured twice, a genuine ambiguity. */
1053
+ scopeFor(packageKey) {
1054
+ const packageName = resolvePackageName(packageKey);
1055
+ const namespace = namespacePath(packageName);
1056
+ const encoded = encodedNamespacePath(packageName);
1057
+ return this.#scope({
1058
+ owner: packageName,
1059
+ base: posix.join(this.#prefix, namespace),
1060
+ encodedBase: encoded ? posix.join(this.#prefix, encoded) : void 0,
1061
+ claim: `the route namespace "${namespace}"`,
1062
+ webhooks: this.#webhooks?.scopeFor(packageName),
1063
+ onDispose: () => this.#webhooks?.disposeScope(packageName)
1064
+ });
1065
+ }
1066
+ /** A scope at a host-named path; on the service, not `IHttpScope`, so a package can never name one. Namespacing is package
1067
+ * policy: the host owns its URL space and third parties hold its URLs, so the path is verbatim and outside the package prefix. */
1068
+ hostScope(name, mountPath) {
1069
+ const base = assertHostMountPath(mountPath);
1070
+ if (base === this.#prefix || base.startsWith(`${this.#prefix}/`)) throw new InvalidNamespaceError(`Host scope "${name}" cannot mount at "${base}": that is the package route prefix, which packages own`);
1071
+ return this.#scope({
1072
+ owner: name,
1073
+ base,
1074
+ encodedBase: void 0,
1075
+ claim: `the mount path "${base}"`,
1076
+ webhooks: void 0,
1077
+ onDispose: () => void 0
1078
+ });
1079
+ }
1080
+ /** Idempotent per base path, so a package reload cannot accumulate namespaces. Two owners wanting one path is an error —
1081
+ * with verbatim names that needs one package configured twice at different versions, a genuine ambiguity, not a clash. */
1082
+ #scope(options) {
1083
+ const { owner, base } = options;
1084
+ const existing = this.#scopes.get(base);
1085
+ if (existing) {
1086
+ if (existing.owner !== owner) throw new Error(`"${owner}" wants ${options.claim}, which "${existing.owner}" already holds`);
1087
+ return existing;
1088
+ }
1089
+ const scope = new HttpScope({
1090
+ owner,
1091
+ base,
1092
+ encodedBase: options.encodedBase,
1093
+ publicUrl: this.#publicUrl,
1094
+ trustProxy: this.#trustProxy,
1095
+ adapter: this.#adapter,
1096
+ authService: this.#authService,
1097
+ webhooks: options.webhooks,
1098
+ onDispose: () => {
1099
+ this.#scopes.delete(base);
1100
+ options.onDispose();
1101
+ }
1102
+ });
1103
+ this.#scopes.set(base, scope);
1104
+ return scope;
1105
+ }
1106
+ /** Like {@link scopeFor}, but never throws: a key resolving to no usable npm name gets a scope that refuses
1107
+ * registrations, so one unroutable package cannot stop the host booting — it fails only if it serves a route. */
1108
+ scopeForOrNull(packageKey) {
1109
+ try {
1110
+ return this.scopeFor(packageKey);
1111
+ } catch (error) {
1112
+ if (!(error instanceof InvalidNamespaceError)) throw error;
1113
+ logger$1.warn("Package \"@package\" cannot host HTTP routes: @reason", packageKey, error.message);
1114
+ return new UnroutableScope(packageKey, error.message);
1115
+ }
1116
+ }
1117
+ /** Releases a package's routes, e.g. when it is replaced or removed. */
1118
+ disposeScope(packageKey) {
1119
+ try {
1120
+ const namespace = namespacePath(resolvePackageName(packageKey));
1121
+ this.#scopes.get(posix.join(this.#prefix, namespace))?.dispose();
1122
+ } catch (error) {
1123
+ if (!(error instanceof InvalidNamespaceError)) throw error;
1124
+ }
1125
+ }
1126
+ disposeAll() {
1127
+ for (const scope of [...this.#scopes.values()]) scope.dispose();
975
1128
  }
976
- route() {
977
- this.#refuse();
1129
+ };
1130
+ var HttpScope = class {
1131
+ owner;
1132
+ #base;
1133
+ #publicUrl;
1134
+ #trustProxy;
1135
+ #encodedBase;
1136
+ #adapter;
1137
+ #authService;
1138
+ #onDispose;
1139
+ #registrations = /* @__PURE__ */ new Map();
1140
+ #webhooks;
1141
+ constructor(options) {
1142
+ this.owner = options.owner;
1143
+ this.#base = options.base;
1144
+ this.#publicUrl = options.publicUrl;
1145
+ this.#trustProxy = options.trustProxy;
1146
+ this.#encodedBase = options.encodedBase;
1147
+ this.#adapter = options.adapter;
1148
+ this.#authService = options.authService;
1149
+ this.#onDispose = options.onDispose;
1150
+ this.#webhooks = options.webhooks ?? unavailableWebhooks(options.owner);
978
1151
  }
979
- nodeRoute() {
980
- this.#refuse();
1152
+ get baseUrl() {
1153
+ return `${readPublicOrigin(this.#publicUrl)}${this.#base}`;
981
1154
  }
982
1155
  get webhooks() {
983
- return unavailableWebhooks(this.owner);
1156
+ return this.#webhooks;
984
1157
  }
985
- dispose() {}
986
- };
987
- /** Stands in when the host has no webhook store configured. */
988
- function unavailableWebhooks(packageName) {
989
- return {
990
- hasPublicOrigin: false,
991
- register: () => Promise.reject(/* @__PURE__ */ new Error(`Webhooks are not available on this host, so "${packageName}" cannot register one`))
992
- };
993
- }
994
- /** Header each scheme reads when the caller does not name one: the name the format is
995
- * most often carried in, not a property of it, so `WebhookVerification.header` overrides any of them. */
996
- const DEFAULT_SCHEME_HEADER = {
997
- none: "",
998
- token: "x-webhook-token",
999
- hmac: "x-signature",
1000
- "hmac-prefixed": "x-hub-signature-256",
1001
- "hmac-timestamped": "stripe-signature"
1002
- };
1003
- const OK = { ok: true };
1004
- /** Constant-time over equal-length inputs; a length mismatch is already a rejection, so
1005
- * the early return leaks nothing a caller could not measure. */
1006
- function secureEquals(a, b) {
1007
- const left = Buffer.from(a, "utf8");
1008
- const right = Buffer.from(b, "utf8");
1009
- if (left.length !== right.length) return false;
1010
- return timingSafeEqual(left, right);
1011
- }
1012
- function hmacDigest(secret, payload, verification) {
1013
- return createHmac(verification.algorithm ?? "sha256", secret).update(payload).digest(verification.encoding ?? "hex");
1014
- }
1015
- /** Hex folds case, so an uppercased digest still verifies. Base64 must not: two distinct
1016
- * digests can differ only in case, so folding there would accept a signature that is not the one computed. */
1017
- function digestEquals(presented, expected, verification) {
1018
- const candidate = presented.trim();
1019
- if ((verification.encoding ?? "hex") === "base64") return secureEquals(candidate, expected);
1020
- return secureEquals(candidate.toLowerCase(), expected.toLowerCase());
1021
- }
1022
- /** The label `hmac-prefixed` expects before the digest. */
1023
- function signaturePrefix(verification) {
1024
- return verification.prefix ?? `${verification.algorithm ?? "sha256"}=`;
1025
- }
1026
- /** `t=<unix>,v1=<hex>[,v1=<hex>…]`. Several `v1` values appear while a secret is being
1027
- * rotated, and any one of them matching is a pass. */
1028
- function parseTimestampedHeader(value) {
1029
- const signatures = [];
1030
- let timestamp;
1031
- for (const part of value.split(",")) {
1032
- const separator = part.indexOf("=");
1033
- if (separator < 0) continue;
1034
- const key = part.slice(0, separator).trim();
1035
- const item = part.slice(separator + 1).trim();
1036
- if (key === "t") timestamp = Number(item);
1037
- else if (key === "v1") signatures.push(item);
1158
+ get(path, a, b) {
1159
+ return this.#shorthand("GET", path, a, b);
1038
1160
  }
1039
- return {
1040
- timestamp,
1041
- signatures
1042
- };
1043
- }
1044
- function schemeHeader(verification) {
1045
- return (verification.header ?? DEFAULT_SCHEME_HEADER[verification.scheme]).toLowerCase();
1046
- }
1047
- /** Verifies a delivery against the configured scheme; `raw` must be the exact bytes
1048
- * received. The reason is for the log only: callers answer a fixed 401, so a probing sender learns nothing from the body. */
1049
- function verifyWebhook(options) {
1050
- const { verification, headers, raw } = options;
1051
- if (verification.scheme === "none") return OK;
1052
- if (!verification.secret) return {
1053
- ok: false,
1054
- reason: "signing secret missing"
1055
- };
1056
- const header = schemeHeader(verification);
1057
- const presented = headers[header];
1058
- if (!presented) return {
1059
- ok: false,
1060
- reason: `header "${header}" absent`
1061
- };
1062
- const secret = verification.secret;
1063
- const tolerance = verification.toleranceSeconds ?? 300;
1064
- switch (verification.scheme) {
1065
- case "token": return secureEquals(presented, secret) ? OK : {
1066
- ok: false,
1067
- reason: "token mismatch"
1068
- };
1069
- case "hmac": return digestEquals(presented, hmacDigest(secret, raw, verification), verification) ? OK : {
1070
- ok: false,
1071
- reason: "hmac mismatch"
1072
- };
1073
- case "hmac-prefixed": return digestEquals(presented, `${signaturePrefix(verification)}${hmacDigest(secret, raw, verification)}`, verification) ? OK : {
1074
- ok: false,
1075
- reason: "hmac mismatch"
1076
- };
1077
- case "hmac-timestamped": {
1078
- const { timestamp, signatures } = parseTimestampedHeader(presented);
1079
- if (timestamp === void 0 || !Number.isFinite(timestamp)) return {
1080
- ok: false,
1081
- reason: "no timestamp in the signature header"
1082
- };
1083
- if (signatures.length === 0) return {
1084
- ok: false,
1085
- reason: "no v1 signature in the header"
1086
- };
1087
- const nowMs = (options.now ?? /* @__PURE__ */ new Date()).getTime();
1088
- if (Math.abs(nowMs / 1e3 - timestamp) > tolerance) return {
1089
- ok: false,
1090
- reason: "timestamp outside the replay window"
1091
- };
1092
- const expected = hmacDigest(secret, Buffer.concat([Buffer.from(`${timestamp}.`, "utf8"), raw]), verification);
1093
- let matched = false;
1094
- for (const signature of signatures) if (digestEquals(signature, expected, verification)) matched = true;
1095
- return matched ? OK : {
1096
- ok: false,
1097
- reason: "hmac mismatch"
1098
- };
1099
- }
1161
+ post(path, a, b) {
1162
+ return this.#shorthand("POST", path, a, b);
1100
1163
  }
1101
- }
1102
- /** Headers that would put a credential in a log or run journal. The configured signature
1103
- * header joins them: it is an HMAC of the body under a live secret. */
1104
- const REDACTED_HEADERS = /* @__PURE__ */ new Set([
1105
- "authorization",
1106
- "proxy-authorization",
1107
- "cookie",
1108
- "set-cookie",
1109
- "x-api-key",
1110
- "x-webhook-token",
1111
- "x-signature",
1112
- "x-hub-signature",
1113
- "x-hub-signature-256",
1114
- "stripe-signature"
1115
- ]);
1116
- const REDACTED = "[redacted]";
1117
- function redactHeaders(headers, extra) {
1118
- const redacted = {};
1119
- for (const [name, value] of Object.entries(headers)) {
1120
- const key = name.toLowerCase();
1121
- redacted[key] = REDACTED_HEADERS.has(key) || extra && key === extra.toLowerCase() ? REDACTED : value;
1164
+ put(path, a, b) {
1165
+ return this.#shorthand("PUT", path, a, b);
1122
1166
  }
1123
- return redacted;
1124
- }
1125
- /** JSON and form bodies become objects; anything else stays decoded text, so a verified
1126
- * XML or CSV payload is still reachable downstream. */
1127
- function parseWebhookBody(raw, contentType) {
1128
- if (raw.length === 0) return void 0;
1129
- const type = (contentType ?? "").split(";")[0].trim().toLowerCase();
1130
- const text = raw.toString("utf8");
1131
- if (type === "application/json" || type.endsWith("+json")) try {
1132
- return JSON.parse(text);
1133
- } catch {
1134
- return text;
1167
+ patch(path, a, b) {
1168
+ return this.#shorthand("PATCH", path, a, b);
1135
1169
  }
1136
- if (type === "application/x-www-form-urlencoded") return Object.fromEntries(new URLSearchParams(text));
1137
- return text;
1138
- }
1139
- //#endregion
1140
- //#region src/http/webhook-service.ts
1141
- const logger$1 = childLogger(["reactor-api", "webhooks"]);
1142
- /** The flat, token-addressed path family. */
1143
- const WEBHOOK_SEGMENT = "webhooks";
1144
- const DEFAULT_MAX_BODY_BYTES = 1048576;
1145
- const DEFAULT_DEDUPE_TTL_SECONDS = 300;
1146
- /** One host route for `/webhooks/:token`, dispatching by token. The flat path leaks
1147
- * neither package nor document; the namespace lives in the token record, which is also what stops one package's token reaching another's handler. */
1148
- var WebhookService = class {
1149
- #store;
1150
- #path;
1151
- #publicUrl;
1152
- #scope;
1153
- #registrations = /* @__PURE__ */ new Map();
1154
- #routes = [];
1155
- constructor({ store, basePath = "/", publicUrl }) {
1156
- this.#store = store;
1157
- this.#path = posix.join("/", basePath, WEBHOOK_SEGMENT);
1158
- this.#publicUrl = publicUrl?.replace(/\/+$/, "");
1170
+ delete(path, a, b) {
1171
+ return this.#shorthand("DELETE", path, a, b);
1159
1172
  }
1160
- /** The scope the endpoint family serves from, handed over once the route service exists;
1161
- * separate from the constructor only because that service takes this one as an option. */
1162
- attach(scope) {
1163
- this.#scope = scope;
1173
+ head(path, a, b) {
1174
+ return this.#shorthand("HEAD", path, a, b);
1164
1175
  }
1165
- async init() {
1166
- await this.#store.init();
1167
- if (this.#routes.length) return;
1168
- if (!this.#scope) throw new Error("The webhook service has no HTTP scope; the host must call attach() before a package registers");
1169
- this.#routes = [this.#scope.nodeRoute({
1170
- method: [
1171
- "DELETE",
1172
- "GET",
1173
- "HEAD",
1174
- "PATCH",
1175
- "POST",
1176
- "PUT"
1177
- ],
1178
- path: ":token",
1179
- auth: "public",
1180
- handler: (req, res, ctx) => void this.#deliver(req, res, ctx.params)
1181
- })];
1176
+ #shorthand(method, path, a, b) {
1177
+ const options = typeof a === "function" ? {} : a;
1178
+ const handler = typeof a === "function" ? a : b;
1179
+ if (!handler) throw new Error(`Route ${method} ${path} was registered with no handler`);
1180
+ return this.route({
1181
+ ...options,
1182
+ method,
1183
+ path,
1184
+ handler
1185
+ });
1186
+ }
1187
+ route(spec) {
1188
+ const body = spec.body ?? "parsed";
1189
+ return this.#register(spec, (req, res, ctx) => this.#serve(spec, body, req, res, ctx));
1190
+ }
1191
+ nodeRoute(spec) {
1192
+ return this.#register(spec, (req, res, ctx) => spec.handler(req, res, ctx));
1182
1193
  }
1183
1194
  dispose() {
1184
- for (const handle of this.#routes) handle.dispose();
1185
- this.#routes = [];
1195
+ for (const registration of this.#registrations.values()) for (const handle of registration.handles) handle.dispose();
1186
1196
  this.#registrations.clear();
1197
+ this.#onDispose();
1187
1198
  }
1188
- /** The facade a package's HTTP scope exposes as `scope.webhooks`. */
1189
- scopeFor(namespace) {
1199
+ /** Mounts one route under this scope's namespace, in both the verbatim and the
1200
+ * percent-encoded spelling of a scoped name. */
1201
+ #register(spec, run) {
1202
+ const relative = assertRelativeRoutePath(spec.path);
1203
+ const methods = Array.isArray(spec.method) ? spec.method : [spec.method];
1204
+ const routePath = relative ? posix.join(this.#base, relative) : this.#base;
1205
+ const key = `${methods.join(",")} ${routePath}`;
1206
+ if (this.#registrations.has(key)) throw new Error(`Route ${key} is already registered by "${this.owner}"`);
1207
+ const handles = [];
1208
+ const paths = [routePath];
1209
+ if (this.#encodedBase) paths.push(relative ? posix.join(this.#encodedBase, relative) : this.#encodedBase);
1210
+ for (const path of paths) for (const method of methods) handles.push(this.#adapter.mountNodeRoute(method, path, (req, res) => {
1211
+ this.#guard(spec, req, res, run);
1212
+ }, {
1213
+ rawBody: true,
1214
+ prefix: spec.prefix
1215
+ }));
1216
+ this.#registrations.set(key, {
1217
+ path: routePath,
1218
+ handles
1219
+ });
1220
+ logger$1.debug("Registered @route for @package", key, this.owner);
1221
+ const publicUrl = this.#publicUrl;
1190
1222
  return {
1191
- hasPublicOrigin: this.hasPublicOrigin,
1192
- register: async (spec) => {
1193
- await this.init();
1194
- const key = `${namespace}|${spec.name}`;
1195
- this.#registrations.set(key, {
1196
- namespace,
1197
- spec
1198
- });
1199
- return {
1200
- endpointFor: async (ownerKey) => {
1201
- const row = await this.#store.ensure(namespace, spec.name, ownerKey);
1202
- return {
1203
- token: row.token,
1204
- url: this.urlFor(row.token),
1205
- createdAt: row.createdAt
1206
- };
1207
- },
1208
- revoke: (ownerKey) => this.#store.revoke(namespace, spec.name, ownerKey),
1209
- list: async () => (await this.#store.list(namespace, spec.name)).map((row) => ({
1210
- key: row.ownerKey,
1211
- token: row.token,
1212
- url: this.urlFor(row.token),
1213
- createdAt: row.createdAt
1214
- }))
1215
- };
1223
+ get url() {
1224
+ return `${readPublicOrigin(publicUrl)}${routePath}`;
1225
+ },
1226
+ dispose: () => {
1227
+ const registration = this.#registrations.get(key);
1228
+ if (!registration) return;
1229
+ for (const handle of registration.handles) handle.dispose();
1230
+ this.#registrations.delete(key);
1216
1231
  }
1217
1232
  };
1218
1233
  }
1219
- /** Releases every registration a package made. */
1220
- disposeScope(namespace) {
1221
- for (const [key, registration] of this.#registrations) if (registration.namespace === namespace) this.#registrations.delete(key);
1222
- }
1223
- /** The URL to hand a provider. Absolute whenever the host knows its own origin: a
1224
- * relative path is useless to the third party that has to call it. */
1225
- urlFor(token) {
1226
- const path = posix.join(this.#path, token);
1227
- return this.#publicUrl ? `${this.#publicUrl}${path}` : path;
1228
- }
1229
- /** Whether `urlFor` can produce something a provider could call. */
1230
- get hasPublicOrigin() {
1231
- return this.#publicUrl !== void 0;
1234
+ /** Authenticate, then run. */
1235
+ async #guard(spec, req, res, run) {
1236
+ try {
1237
+ const actor = await this.#authenticate(spec.auth ?? "renown", req, res);
1238
+ if (actor === REJECTED) return;
1239
+ await run(req, res, {
1240
+ params: routeParams(req),
1241
+ user: actor?.user,
1242
+ authEnabled: actor?.authEnabled ?? false,
1243
+ transport: resolveTransport(req, this.#trustProxy)
1244
+ });
1245
+ } catch (error) {
1246
+ logger$1.error("Route handler failed for @package", this.owner, error);
1247
+ writeError(res, 500, "Internal server error");
1248
+ }
1232
1249
  }
1233
- async #deliver(req, res, params) {
1234
- const token = params.token;
1235
- if (!token) {
1236
- writeError(res, 404, "Unknown endpoint");
1250
+ /** Resolves the caller, answering the request itself when the route refuses it;
1251
+ * returns REJECTED in that case so the caller stops. */
1252
+ async #authenticate(auth, req, res) {
1253
+ if (auth === "public") return void 0;
1254
+ if (typeof auth === "function") {
1255
+ const result = await auth(req);
1256
+ if (!result.authorized) {
1257
+ if ("response" in result) await writeResponse(res, result.response, req.method ?? "GET");
1258
+ else writeError(res, result.status, result.message);
1259
+ return REJECTED;
1260
+ }
1237
1261
  return;
1238
1262
  }
1239
- try {
1240
- const row = await this.#store.find(token);
1241
- if (!row) {
1242
- writeError(res, 404, "Unknown endpoint");
1243
- return;
1244
- }
1245
- const registrationKey = `${row.namespace}|${row.endpoint}`;
1246
- const registration = this.#registrations.get(registrationKey);
1247
- if (!registration) {
1248
- writeError(res, 503, "Endpoint temporarily unavailable");
1249
- return;
1250
- }
1251
- const { spec } = registration;
1252
- const method = (req.method ?? "POST").toUpperCase();
1253
- const perEndpoint = spec.policyFor ? await spec.policyFor(row.ownerKey) : {};
1254
- if (!perEndpoint) {
1255
- writeError(res, 404, "Unknown endpoint");
1256
- return;
1257
- }
1258
- const policy = {
1259
- ...spec.defaults,
1260
- ...perEndpoint
1263
+ if (!this.#authService) return ANONYMOUS;
1264
+ const result = await this.#authService.verifyBearer(req.headers.authorization);
1265
+ if (result instanceof Response) {
1266
+ await writeResponse(res, result, req.method ?? "GET");
1267
+ return REJECTED;
1268
+ }
1269
+ if (result.auth_enabled && !result.user && auth === "renown") {
1270
+ writeError(res, 401, "Authentication required");
1271
+ return REJECTED;
1272
+ }
1273
+ return {
1274
+ user: result.user,
1275
+ authEnabled: result.auth_enabled
1276
+ };
1277
+ }
1278
+ /** Builds the Fetch Request from the raw stream and runs the handler. */
1279
+ async #serve(spec, body, req, res, ctx) {
1280
+ const method = req.method ?? "GET";
1281
+ const url = `${ctx.transport.baseUrl}${req.url ?? "/"}`;
1282
+ const controller = new AbortController();
1283
+ req.once("close", () => controller.abort());
1284
+ let raw;
1285
+ let init = {
1286
+ method,
1287
+ headers: fetchHeaders(req),
1288
+ signal: controller.signal
1289
+ };
1290
+ if (method !== "GET" && method !== "HEAD" && body !== "none") {
1291
+ if (body === "stream") init = {
1292
+ ...init,
1293
+ body: Readable.toWeb(req),
1294
+ duplex: "half"
1261
1295
  };
1262
- if (policy.methods && !policy.methods.includes(method)) {
1263
- writeError(res, 405, "Method not allowed");
1264
- return;
1265
- }
1266
- let raw;
1267
- try {
1268
- raw = await readBody(req, policy.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);
1269
- } catch (error) {
1270
- if (error instanceof BodyTooLargeError) {
1271
- res.setHeader("connection", "close");
1272
- res.once("finish", () => req.destroy());
1273
- writeError(res, 413, "Payload too large");
1274
- return;
1275
- }
1276
- throw error;
1277
- }
1278
- const verification = policy.verify;
1279
- if (verification) {
1280
- const result = verifyWebhook({
1281
- verification,
1282
- headers: headerRecord(req),
1283
- raw
1284
- });
1285
- if (!result.ok) {
1286
- logger$1.warn("Rejected webhook delivery for @package/@endpoint: @reason", row.namespace, row.endpoint, result.reason);
1287
- writeError(res, 401, "Signature verification failed");
1288
- return;
1289
- }
1290
- }
1291
- const url = new URL(req.url ?? "/", "http://localhost");
1292
- const queryParams = Object.fromEntries(url.searchParams);
1293
- const signatureHeader = verification ? schemeHeader(verification) : void 0;
1294
- const headers = headerRecord(req);
1295
- const body = parseWebhookBody(raw, headers["content-type"]);
1296
- const challenge = challengeValue(policy.challengeField, queryParams, headers, body);
1297
- if (challenge !== void 0) {
1298
- res.statusCode = 200;
1299
- res.setHeader("content-type", "text/plain");
1300
- res.end(challenge);
1301
- return;
1302
- }
1303
- let recordedKey;
1304
- if (policy.dedupe) {
1305
- const key = dedupeKey(policy.dedupe.field, queryParams, headers, body);
1306
- recordedKey = key;
1307
- if (key !== void 0 && await this.#store.seen(token, key, policy.dedupe.ttlSeconds ?? DEFAULT_DEDUPE_TTL_SECONDS)) {
1308
- res.statusCode = 200;
1309
- res.end();
1310
- return;
1296
+ else {
1297
+ try {
1298
+ raw = await readBody(req, spec.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);
1299
+ } catch (error) {
1300
+ if (error instanceof BodyTooLargeError) {
1301
+ res.setHeader("connection", "close");
1302
+ res.once("finish", () => req.destroy());
1303
+ writeError(res, 413, "Payload too large");
1304
+ return;
1305
+ }
1306
+ throw error;
1311
1307
  }
1308
+ if (raw.length) init = {
1309
+ ...init,
1310
+ body: new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength)
1311
+ };
1312
1312
  }
1313
- const reply = await spec.onRequest({
1314
- key: row.ownerKey,
1315
- method,
1316
- path: url.pathname,
1317
- queryParams,
1318
- headers: redactHeaders(headers, signatureHeader),
1319
- raw,
1320
- body
1321
- });
1322
- if (reply.unprocessed === true && recordedKey !== void 0) try {
1323
- await this.#store.forget(token, recordedKey);
1324
- } catch (error) {
1325
- logger$1.warn("Could not forget an unprocessed webhook delivery: @error", error);
1326
- }
1327
- res.statusCode = reply.status;
1328
- if (reply.body !== void 0 && method !== "HEAD") {
1329
- res.setHeader("content-type", reply.contentType ?? "text/plain");
1330
- res.end(reply.body);
1331
- } else res.end();
1332
- } catch (error) {
1333
- logger$1.error("Webhook delivery failed for @method", req.method, error);
1334
- writeError(res, 500, "Internal server error");
1335
1313
  }
1314
+ await writeResponse(res, await spec.handler(new Request(url, init), {
1315
+ ...ctx,
1316
+ rawBody: body === "raw" ? raw ?? Buffer.alloc(0) : void 0,
1317
+ signal: controller.signal
1318
+ }), method);
1319
+ }
1320
+ };
1321
+ const REJECTED = Symbol("rejected");
1322
+ function routeParams(req) {
1323
+ const params = req.params;
1324
+ if (!params || typeof params !== "object") return {};
1325
+ const out = {};
1326
+ for (const [key, value] of Object.entries(params)) if (typeof value === "string") out[key] = value;
1327
+ else if (Array.isArray(value)) out[key] = value.join("/");
1328
+ return out;
1329
+ }
1330
+ /** Stands in for a package that cannot be routed — its key resolves to no npm name. Registering a route throws with
1331
+ * the reason; nothing else does, so the package still loads and its non-HTTP behaviour is unaffected. */
1332
+ var UnroutableScope = class {
1333
+ owner;
1334
+ baseUrl = "";
1335
+ #reason;
1336
+ constructor(packageKey, reason) {
1337
+ this.owner = packageKey;
1338
+ this.#reason = reason;
1339
+ }
1340
+ #refuse() {
1341
+ throw new Error(`Package "${this.owner}" cannot host HTTP routes: ${this.#reason}`);
1342
+ }
1343
+ get() {
1344
+ this.#refuse();
1336
1345
  }
1337
- };
1338
- function headerRecord(req) {
1339
- const headers = {};
1340
- for (const [name, value] of Object.entries(req.headers)) {
1341
- if (value === void 0) continue;
1342
- headers[name.toLowerCase()] = Array.isArray(value) ? value.join(", ") : value;
1346
+ post() {
1347
+ this.#refuse();
1343
1348
  }
1344
- return headers;
1345
- }
1346
- function scalar(value) {
1347
- if (typeof value === "string" && value !== "") return value;
1348
- if (typeof value === "number") return String(value);
1349
- }
1350
- /** Walks a dot-separated path into the parsed body. */
1351
- function bodyPath(path, body) {
1352
- let current = body;
1353
- for (const segment of path.split(".")) {
1354
- if (!current || typeof current !== "object") return void 0;
1355
- current = current[segment];
1349
+ put() {
1350
+ this.#refuse();
1356
1351
  }
1357
- return scalar(current);
1358
- }
1359
- /** Resolves where a provider put a value. A bare string means query first, then a
1360
- * top-level body field; `{ header }` and `{ body }` reach what that cannot — GitHub's delivery id is a header, Stripe's event id is nested. */
1361
- function fieldValue(field, queryParams, headers, body) {
1362
- if (typeof field === "object") return "header" in field ? scalar(headers[field.header.toLowerCase()]) : bodyPath(field.body, body);
1363
- const fromQuery = scalar(queryParams[field]);
1364
- if (fromQuery !== void 0) return fromQuery;
1365
- return body && typeof body === "object" ? scalar(body[field]) : void 0;
1366
- }
1367
- function challengeValue(field, queryParams, headers, body) {
1368
- return field === void 0 ? void 0 : fieldValue(field, queryParams, headers, body);
1369
- }
1370
- function dedupeKey(field, queryParams, headers, body) {
1371
- return fieldValue(field, queryParams, headers, body);
1352
+ patch() {
1353
+ this.#refuse();
1354
+ }
1355
+ delete() {
1356
+ this.#refuse();
1357
+ }
1358
+ head() {
1359
+ this.#refuse();
1360
+ }
1361
+ route() {
1362
+ this.#refuse();
1363
+ }
1364
+ nodeRoute() {
1365
+ this.#refuse();
1366
+ }
1367
+ get webhooks() {
1368
+ return unavailableWebhooks(this.owner);
1369
+ }
1370
+ dispose() {}
1371
+ };
1372
+ /** Stands in when the host has no webhook store configured. */
1373
+ function unavailableWebhooks(packageName) {
1374
+ return {
1375
+ hasPublicOrigin: false,
1376
+ register: () => Promise.reject(/* @__PURE__ */ new Error(`Webhooks are not available on this host, so "${packageName}" cannot register one`))
1377
+ };
1372
1378
  }
1373
1379
  //#endregion
1374
1380
  //#region src/http/webhook-store.ts
@@ -1639,6 +1645,11 @@ let DocumentChangeType = /* @__PURE__ */ function(DocumentChangeType) {
1639
1645
  DocumentChangeType["Updated"] = "UPDATED";
1640
1646
  return DocumentChangeType;
1641
1647
  }({});
1648
+ let DriveNodeKind = /* @__PURE__ */ function(DriveNodeKind) {
1649
+ DriveNodeKind["File"] = "FILE";
1650
+ DriveNodeKind["Folder"] = "FOLDER";
1651
+ return DriveNodeKind;
1652
+ }({});
1642
1653
  let PropagationMode = /* @__PURE__ */ function(PropagationMode) {
1643
1654
  PropagationMode["Cascade"] = "CASCADE";
1644
1655
  PropagationMode["Orphan"] = "ORPHAN";
@@ -1653,6 +1664,7 @@ const isDefinedNonNullAny = (v) => v !== void 0 && v !== null;
1653
1664
  const definedNonNullAnySchema = z$1.any().refine((v) => isDefinedNonNullAny(v));
1654
1665
  const AuthDecisionSchema = z$1.enum(AuthDecision);
1655
1666
  const DocumentChangeTypeSchema = z$1.enum(DocumentChangeType);
1667
+ const DriveNodeKindSchema = z$1.enum(DriveNodeKind);
1656
1668
  const PropagationModeSchema = z$1.enum(PropagationMode);
1657
1669
  const SyncEnvelopeTypeSchema = z$1.enum(SyncEnvelopeType);
1658
1670
  function ActionCandidateInputSchema() {
@@ -1683,6 +1695,21 @@ function ActionInputSchema() {
1683
1695
  function ChannelMetaInputSchema() {
1684
1696
  return z$1.object({ id: z$1.string() });
1685
1697
  }
1698
+ function ConsistencyCoordinateInputSchema() {
1699
+ return z$1.object({
1700
+ branch: z$1.string(),
1701
+ documentId: z$1.string(),
1702
+ operationIndex: z$1.number(),
1703
+ scope: z$1.string()
1704
+ });
1705
+ }
1706
+ function ConsistencyTokenInputSchema() {
1707
+ return z$1.object({
1708
+ coordinates: z$1.array(z$1.lazy(() => ConsistencyCoordinateInputSchema())),
1709
+ createdAtUtcIso: z$1.string(),
1710
+ version: z$1.number()
1711
+ });
1712
+ }
1686
1713
  function DocumentOperationsFilterInputSchema() {
1687
1714
  return z$1.object({
1688
1715
  actionTypes: z$1.array(z$1.string()).nullish(),
@@ -1876,6 +1903,23 @@ const JobInfoFieldsFragmentDoc = gql`
1876
1903
  }
1877
1904
  }
1878
1905
  `;
1906
+ const DriveNodeFieldsFragmentDoc = gql`
1907
+ fragment DriveNodeFields on DriveNode {
1908
+ ... on DriveFileNode {
1909
+ id
1910
+ driveId
1911
+ name
1912
+ parentFolder
1913
+ documentType
1914
+ }
1915
+ ... on DriveFolderNode {
1916
+ id
1917
+ driveId
1918
+ name
1919
+ parentFolder
1920
+ }
1921
+ }
1922
+ `;
1879
1923
  const GetDocumentModelsDocument = gql`
1880
1924
  query GetDocumentModels($namespace: String, $paging: PagingInput) {
1881
1925
  documentModels(namespace: $namespace, paging: $paging) {
@@ -2126,6 +2170,44 @@ const GetCreateDefaultsDocument = gql`
2126
2170
  }
2127
2171
  }
2128
2172
  `;
2173
+ const GetDriveNodesDocument = gql`
2174
+ query GetDriveNodes(
2175
+ $driveId: ID!
2176
+ $parentFolder: ID
2177
+ $paging: PagingInput
2178
+ $kind: DriveNodeKind
2179
+ ) {
2180
+ driveNodes(
2181
+ driveId: $driveId
2182
+ parentFolder: $parentFolder
2183
+ paging: $paging
2184
+ kind: $kind
2185
+ ) {
2186
+ results {
2187
+ ...DriveNodeFields
2188
+ }
2189
+ nextCursor
2190
+ hasMore
2191
+ }
2192
+ }
2193
+ ${DriveNodeFieldsFragmentDoc}
2194
+ `;
2195
+ const GetDriveNodeDocument = gql`
2196
+ query GetDriveNode($driveId: ID!, $id: ID!) {
2197
+ driveNode(driveId: $driveId, id: $id) {
2198
+ ...DriveNodeFields
2199
+ }
2200
+ }
2201
+ ${DriveNodeFieldsFragmentDoc}
2202
+ `;
2203
+ const GetDriveDescendantsDocument = gql`
2204
+ query GetDriveDescendants($driveId: ID!, $root: ID!) {
2205
+ driveDescendants(driveId: $driveId, root: $root) {
2206
+ ...DriveNodeFields
2207
+ }
2208
+ }
2209
+ ${DriveNodeFieldsFragmentDoc}
2210
+ `;
2129
2211
  const EvaluateActionsDocument = gql`
2130
2212
  query EvaluateActions(
2131
2213
  $documentIdentifier: String!
@@ -2507,6 +2589,15 @@ function getSdk(requester) {
2507
2589
  GetCreateDefaults(variables, options) {
2508
2590
  return requester(GetCreateDefaultsDocument, variables, options);
2509
2591
  },
2592
+ GetDriveNodes(variables, options) {
2593
+ return requester(GetDriveNodesDocument, variables, options);
2594
+ },
2595
+ GetDriveNode(variables, options) {
2596
+ return requester(GetDriveNodeDocument, variables, options);
2597
+ },
2598
+ GetDriveDescendants(variables, options) {
2599
+ return requester(GetDriveDescendantsDocument, variables, options);
2600
+ },
2510
2601
  EvaluateActions(variables, options) {
2511
2602
  return requester(EvaluateActionsDocument, variables, options);
2512
2603
  },
@@ -2980,43 +3071,67 @@ function isDriveContainerType(documentType) {
2980
3071
  }
2981
3072
  //#endregion
2982
3073
  //#region src/graphql/reactor/resolvers.ts
2983
- const REACTOR_DRIVE_DOCUMENT_TYPE = "powerhouse/reactor-drive";
3074
+ /** The branch a mutation applies to when the caller names none. */
3075
+ const DEFAULT_BRANCH = "main";
3076
+ /** The `Query.<field>` coordinates handed the write client outside a mutation. */
3077
+ const WRITE_CLIENT_QUERIES = Object.entries({
3078
+ evaluateActions: "write",
3079
+ pollSyncEnvelopes: "syncManager",
3080
+ syncHolds: "syncManager",
3081
+ peerAgreement: "syncManager",
3082
+ jobStatus: "read"
3083
+ }).filter(([, binding]) => binding === "write").map(([field]) => field);
2984
3084
  /**
2985
- * Returns the drive client to use for the given drive-container parent type.
2986
- * Throws when the parent is a reactor-drive container but no
2987
- * `reactorDriveClient` was provided.
3085
+ * Adds a document to a drive parent and returns what to read back once the
3086
+ * write is readable. `write.drives` picks the drive type's strategy.
2988
3087
  */
2989
- function pickDriveClient(reactorClient, driveContainerType, reactorDriveClient) {
2990
- if (driveContainerType === REACTOR_DRIVE_DOCUMENT_TYPE) {
2991
- if (!reactorDriveClient) throw new GraphQLError("Reactor-drive parent encountered but no reactorDriveClient is configured on this switchboard");
2992
- return reactorDriveClient;
2993
- }
2994
- return reactorClient.drives;
3088
+ async function addFileToDrive(clients, driveId, document) {
3089
+ return (await clients.write.drives.addFile(driveId, document)).readable;
3090
+ }
3091
+ /** Removes a drive parent's node, waiting until the removal is readable. */
3092
+ async function removeNodeFromDrive(clients, driveId, nodeId) {
3093
+ await (await clients.write.drives.removeNode(driveId, nodeId)).readable;
2995
3094
  }
2996
3095
  /**
2997
- * A mutation's document re-read as the caller, since the client reads it back
2998
- * as its signer. A caller who may write but not read gets it stripped.
3096
+ * A mutation's document read back on the read half, as the caller, bounded by
3097
+ * the write's token: `read.get(receipt.documentId, { subject, branch },
3098
+ * undefined, receipt.token)`. A caller who may write but not read gets it
3099
+ * stripped.
2999
3100
  */
3000
- async function readAsCaller(reactorClient, document, subject, branch) {
3001
- if (!subject) return document;
3101
+ async function readAsCaller(read, receipt, subject, branch) {
3002
3102
  try {
3003
- return await reactorClient.get(document.header.id, {
3103
+ return await read.get(receipt.documentId, {
3004
3104
  subject,
3005
- branch
3006
- });
3105
+ branch: branch ?? receipt.branch
3106
+ }, void 0, receipt.token);
3007
3107
  } catch (error) {
3008
3108
  throw new GraphQLError(`Failed to read the document back: ${error instanceof Error ? error.message : "Unknown error"}`);
3009
3109
  }
3010
3110
  }
3111
+ /** The token a read waits for, or none; only version 1 tokens exist. */
3112
+ function toConsistencyToken(input) {
3113
+ if (!input) return;
3114
+ if (input.version !== 1) throw new GraphQLError(`Unsupported consistency token version ${input.version}`, { extensions: { code: "BAD_USER_INPUT" } });
3115
+ return {
3116
+ version: 1,
3117
+ createdAtUtcIso: input.createdAtUtcIso,
3118
+ coordinates: input.coordinates.map((coordinate) => ({
3119
+ documentId: coordinate.documentId,
3120
+ scope: coordinate.scope,
3121
+ branch: coordinate.branch,
3122
+ operationIndex: coordinate.operationIndex
3123
+ }))
3124
+ };
3125
+ }
3011
3126
  /** The defaults `create` gives a new document; the parent must already be gated. */
3012
- async function createDefaults(reactorClient, parentIdOrSlug) {
3013
- const [signaturePolicy, protocolVersions] = await Promise.all([reactorClient.getCreateSignaturePolicy(), reactorClient.getCreateProtocolVersions(parentIdOrSlug)]);
3127
+ async function createDefaults(read, parentIdOrSlug) {
3128
+ const [signaturePolicy, protocolVersions] = await Promise.all([read.getCreateSignaturePolicy(), read.getCreateProtocolVersions(parentIdOrSlug)]);
3014
3129
  return {
3015
3130
  signaturePolicy,
3016
3131
  protocolVersions
3017
3132
  };
3018
3133
  }
3019
- async function documentModels(reactorClient, args) {
3134
+ async function documentModels(read, args) {
3020
3135
  const namespace = fromInputMaybe(args.namespace);
3021
3136
  let paging;
3022
3137
  if (args.paging) {
@@ -3029,7 +3144,7 @@ async function documentModels(reactorClient, args) {
3029
3144
  }
3030
3145
  let result;
3031
3146
  try {
3032
- result = await reactorClient.getDocumentModelModules(namespace, paging);
3147
+ result = await read.getDocumentModelModules(namespace, paging);
3033
3148
  } catch (error) {
3034
3149
  throw new GraphQLError(`Failed to fetch document models: ${error instanceof Error ? error.message : "Unknown error"}`);
3035
3150
  }
@@ -3039,22 +3154,23 @@ async function documentModels(reactorClient, args) {
3039
3154
  throw new GraphQLError(`Failed to convert document models to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3040
3155
  }
3041
3156
  }
3042
- async function document(reactorClient, args, subject) {
3157
+ async function document(read, args, subject) {
3043
3158
  let view = subject ? { subject } : void 0;
3044
3159
  if (args.view) view = {
3045
3160
  subject,
3046
3161
  branch: fromInputMaybe(args.view.branch),
3047
3162
  scopes: toMutableArray(fromInputMaybe(args.view.scopes))
3048
3163
  };
3164
+ const token = toConsistencyToken(args.consistency);
3049
3165
  let result;
3050
3166
  try {
3051
- result = await reactorClient.get(args.idOrSlug, view);
3167
+ result = await read.get(args.idOrSlug, view, void 0, token);
3052
3168
  } catch (error) {
3053
3169
  throw new GraphQLError(`Failed to fetch document: ${error instanceof Error ? error.message : "Unknown error"}`);
3054
3170
  }
3055
3171
  let children;
3056
3172
  try {
3057
- children = await reactorClient.getOutgoingRelationships(args.idOrSlug, "child", view);
3173
+ children = await read.getOutgoingRelationships(args.idOrSlug, "child", view, void 0, void 0, token);
3058
3174
  } catch (error) {
3059
3175
  throw new GraphQLError(`Failed to fetch children: ${error instanceof Error ? error.message : "Unknown error"}`);
3060
3176
  }
@@ -3067,7 +3183,7 @@ async function document(reactorClient, args, subject) {
3067
3183
  throw new GraphQLError(`Failed to convert document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3068
3184
  }
3069
3185
  }
3070
- async function documentOutgoingRelationships(reactorClient, args, subject) {
3186
+ async function documentOutgoingRelationships(read, args, subject) {
3071
3187
  let view = subject ? { subject } : void 0;
3072
3188
  if (args.view) view = {
3073
3189
  subject,
@@ -3085,7 +3201,7 @@ async function documentOutgoingRelationships(reactorClient, args, subject) {
3085
3201
  }
3086
3202
  let result;
3087
3203
  try {
3088
- result = await reactorClient.getOutgoingRelationships(args.sourceIdOrSlug, args.relationshipType, view, paging);
3204
+ result = await read.getOutgoingRelationships(args.sourceIdOrSlug, args.relationshipType, view, paging, void 0, toConsistencyToken(args.consistency));
3089
3205
  } catch (error) {
3090
3206
  throw new GraphQLError(`Failed to fetch outgoing relationships: ${error instanceof Error ? error.message : "Unknown error"}`);
3091
3207
  }
@@ -3095,7 +3211,7 @@ async function documentOutgoingRelationships(reactorClient, args, subject) {
3095
3211
  throw new GraphQLError(`Failed to convert outgoing relationships to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3096
3212
  }
3097
3213
  }
3098
- async function documentIncomingRelationships(reactorClient, args, subject) {
3214
+ async function documentIncomingRelationships(read, args, subject) {
3099
3215
  let view = subject ? { subject } : void 0;
3100
3216
  if (args.view) view = {
3101
3217
  subject,
@@ -3113,7 +3229,7 @@ async function documentIncomingRelationships(reactorClient, args, subject) {
3113
3229
  }
3114
3230
  let result;
3115
3231
  try {
3116
- result = await reactorClient.getIncomingRelationships(args.targetIdOrSlug, args.relationshipType, view, paging);
3232
+ result = await read.getIncomingRelationships(args.targetIdOrSlug, args.relationshipType, view, paging, void 0, toConsistencyToken(args.consistency));
3117
3233
  } catch (error) {
3118
3234
  throw new GraphQLError(`Failed to fetch incoming relationships: ${error instanceof Error ? error.message : "Unknown error"}`);
3119
3235
  }
@@ -3123,12 +3239,12 @@ async function documentIncomingRelationships(reactorClient, args, subject) {
3123
3239
  throw new GraphQLError(`Failed to convert incoming relationships to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3124
3240
  }
3125
3241
  }
3126
- async function documentOutgoingRelationshipEdges(reactorClient, args, subject) {
3242
+ async function documentOutgoingRelationshipEdges(read, args, subject) {
3127
3243
  const view = toRelationshipViewFilter(args.view, subject);
3128
3244
  const paging = toRelationshipPagingOptions(args.paging);
3129
3245
  let result;
3130
3246
  try {
3131
- result = await reactorClient.getOutgoingRelationshipEdges(args.sourceIdOrSlug, fromInputMaybe(args.relationshipType), view, paging);
3247
+ result = await read.getOutgoingRelationshipEdges(args.sourceIdOrSlug, fromInputMaybe(args.relationshipType), view, paging, void 0, toConsistencyToken(args.consistency));
3132
3248
  } catch (error) {
3133
3249
  throw new GraphQLError(`Failed to fetch outgoing relationship edges: ${error instanceof Error ? error.message : "Unknown error"}`);
3134
3250
  }
@@ -3138,12 +3254,12 @@ async function documentOutgoingRelationshipEdges(reactorClient, args, subject) {
3138
3254
  throw new GraphQLError(`Failed to convert outgoing relationship edges to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3139
3255
  }
3140
3256
  }
3141
- async function documentIncomingRelationshipEdges(reactorClient, args, subject) {
3257
+ async function documentIncomingRelationshipEdges(read, args, subject) {
3142
3258
  const view = toRelationshipViewFilter(args.view, subject);
3143
3259
  const paging = toRelationshipPagingOptions(args.paging);
3144
3260
  let result;
3145
3261
  try {
3146
- result = await reactorClient.getIncomingRelationshipEdges(args.targetIdOrSlug, fromInputMaybe(args.relationshipType), view, paging);
3262
+ result = await read.getIncomingRelationshipEdges(args.targetIdOrSlug, fromInputMaybe(args.relationshipType), view, paging, void 0, toConsistencyToken(args.consistency));
3147
3263
  } catch (error) {
3148
3264
  throw new GraphQLError(`Failed to fetch incoming relationship edges: ${error instanceof Error ? error.message : "Unknown error"}`);
3149
3265
  }
@@ -3171,7 +3287,7 @@ function toRelationshipPagingOptions(input) {
3171
3287
  limit: limit || 10
3172
3288
  };
3173
3289
  }
3174
- async function findDocuments(reactorClient, args, subject) {
3290
+ async function findDocuments(read, args, subject) {
3175
3291
  let view = subject ? { subject } : void 0;
3176
3292
  if (args.view) view = {
3177
3293
  subject,
@@ -3193,7 +3309,7 @@ async function findDocuments(reactorClient, args, subject) {
3193
3309
  };
3194
3310
  let result;
3195
3311
  try {
3196
- result = await reactorClient.find(search, view, paging);
3312
+ result = await read.find(search, view, paging, void 0, toConsistencyToken(args.consistency));
3197
3313
  } catch (error) {
3198
3314
  throw new GraphQLError(`Failed to find documents: ${error instanceof Error ? error.message : "Unknown error"}`);
3199
3315
  }
@@ -3231,10 +3347,10 @@ function unknownJob(jobId) {
3231
3347
  }
3232
3348
  };
3233
3349
  }
3234
- async function jobStatus(reactorClient, args, serves, readable = serves) {
3350
+ async function jobStatus(read, args, serves, readable = serves) {
3235
3351
  let result;
3236
3352
  try {
3237
- result = await reactorClient.getJobStatus(args.jobId);
3353
+ result = await read.getJobStatus(args.jobId);
3238
3354
  } catch (error) {
3239
3355
  throw new GraphQLError(`Failed to fetch job status: ${error instanceof Error ? error.message : "Unknown error"}`);
3240
3356
  }
@@ -3254,7 +3370,7 @@ async function jobStatus(reactorClient, args, serves, readable = serves) {
3254
3370
  throw new GraphQLError(`Failed to convert job status to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3255
3371
  }
3256
3372
  }
3257
- async function documentOperations(reactorClient, args, subject) {
3373
+ async function documentOperations(read, args, subject) {
3258
3374
  let view = subject ? { subject } : void 0;
3259
3375
  const branch = fromInputMaybe(args.filter.branch);
3260
3376
  const scopes = toMutableArray(fromInputMaybe(args.filter.scopes));
@@ -3285,7 +3401,7 @@ async function documentOperations(reactorClient, args, subject) {
3285
3401
  }
3286
3402
  let result;
3287
3403
  try {
3288
- result = await reactorClient.getOperations(args.filter.documentIdOrSlug, view, operationFilter, paging);
3404
+ result = await read.getOperations(args.filter.documentIdOrSlug, view, operationFilter, paging);
3289
3405
  } catch (error) {
3290
3406
  throw new GraphQLError(`Failed to fetch document operations: ${error instanceof Error ? error.message : "Unknown error"}`);
3291
3407
  }
@@ -3308,7 +3424,7 @@ async function documentOperations(reactorClient, args, subject) {
3308
3424
  * A reactor without authEnforcement raises the named error, which becomes an
3309
3425
  * "unsupported" code rather than a denial.
3310
3426
  */
3311
- async function evaluateActions(reactorClient, args, subject) {
3427
+ async function evaluateActions(write, args, subject) {
3312
3428
  const branch = fromInputMaybe(args.branch) ?? "main";
3313
3429
  const candidates = args.candidates.map((candidate) => ({
3314
3430
  scope: candidate.scope,
@@ -3317,7 +3433,7 @@ async function evaluateActions(reactorClient, args, subject) {
3317
3433
  }));
3318
3434
  let result;
3319
3435
  try {
3320
- result = await reactorClient.evaluateActions(args.documentIdOrSlug, branch, candidates, subject);
3436
+ result = await write.evaluateActions(args.documentIdOrSlug, branch, candidates, subject);
3321
3437
  } catch (error) {
3322
3438
  if (AuthEnforcementDisabledError.isError(error)) throw new AuthEvaluationUnsupportedError();
3323
3439
  throw new GraphQLError(`Failed to evaluate actions: ${error instanceof Error ? error.message : "Unknown error"}`);
@@ -3332,11 +3448,11 @@ async function evaluateActions(reactorClient, args, subject) {
3332
3448
  }
3333
3449
  const isDocumentNotFound = (error) => error instanceof Error && error.name === "DocumentNotFoundError";
3334
3450
  /** Refuses a slug another document holds: the reactor would move it to the new one. */
3335
- async function assertSlugAvailable(reactorClient, slug, documentId) {
3451
+ async function assertSlugAvailable(read, slug, documentId) {
3336
3452
  if (!slug || slug === documentId) return;
3337
3453
  let holder;
3338
3454
  try {
3339
- const id = await reactorClient.resolveIdOrSlug(slug);
3455
+ const id = await read.resolveIdOrSlug(slug);
3340
3456
  if (id === documentId) return;
3341
3457
  holder = `document ${id}`;
3342
3458
  } catch (error) {
@@ -3345,65 +3461,65 @@ async function assertSlugAvailable(reactorClient, slug, documentId) {
3345
3461
  }
3346
3462
  throw new GraphQLError(`The slug "${slug}" is taken by ${holder}; choose another.`);
3347
3463
  }
3348
- async function createDocument(reactorClient, args, reactorDriveClient, subject) {
3464
+ async function createDocument(clients, args, _reactorDriveClient, subject) {
3349
3465
  if (!args.document || typeof args.document !== "object") throw new GraphQLError("Invalid document: must be an object");
3350
3466
  const document = args.document;
3351
3467
  if (!document.header || typeof document.header !== "object") throw new GraphQLError("Invalid document: missing or invalid header");
3352
3468
  const parentIdOrSlug = fromInputMaybe(args.parentIdOrSlug);
3353
- await assertSlugAvailable(reactorClient, document.header.slug, document.header.id);
3354
- let result;
3469
+ await assertSlugAvailable(clients.read, document.header.slug, document.header.id);
3470
+ let receipt;
3355
3471
  try {
3356
3472
  if (parentIdOrSlug) {
3357
- const parent = await reactorClient.get(parentIdOrSlug, subject && { subject });
3358
- if (isDriveContainerType(parent.header.documentType)) result = await pickDriveClient(reactorClient, parent.header.documentType, reactorDriveClient).addFile(parent.header.id, document);
3359
- else result = await reactorClient.create(document, parentIdOrSlug);
3360
- } else result = await reactorClient.create(document);
3473
+ const parent = await clients.read.get(parentIdOrSlug, subject && { subject });
3474
+ if (isDriveContainerType(parent.header.documentType)) receipt = await addFileToDrive(clients, parent.header.id, document);
3475
+ else receipt = await (await clients.write.create(document, parentIdOrSlug)).readable;
3476
+ } else receipt = await (await clients.write.create(document)).readable;
3361
3477
  } catch (error) {
3362
3478
  throw new GraphQLError(`Failed to create document: ${error instanceof Error ? error.message : "Unknown error"}`);
3363
3479
  }
3364
- result = await readAsCaller(reactorClient, result, subject);
3480
+ const result = await readAsCaller(clients.read, receipt, subject);
3365
3481
  try {
3366
3482
  return toGqlPhDocument(result);
3367
3483
  } catch (error) {
3368
3484
  throw new GraphQLError(`Failed to convert created document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3369
3485
  }
3370
3486
  }
3371
- async function createEmptyDocument(reactorClient, args, reactorDriveClient, subject) {
3487
+ async function createEmptyDocument(clients, args, _reactorDriveClient, subject) {
3372
3488
  const parentIdOrSlug = fromInputMaybe(args.parentIdOrSlug);
3373
3489
  const name = fromInputMaybe(args.name);
3374
- let result;
3490
+ let receipt;
3375
3491
  try {
3376
3492
  if (parentIdOrSlug) {
3377
- const parent = await reactorClient.get(parentIdOrSlug, subject && { subject });
3493
+ const parent = await clients.read.get(parentIdOrSlug, subject && { subject });
3378
3494
  if (isDriveContainerType(parent.header.documentType)) {
3379
- const module = await reactorClient.getDocumentModelModule(args.documentType);
3380
- const document = withSignaturePolicy(module.utils.createDocument(), await reactorClient.getCreateSignaturePolicy());
3495
+ const module = await clients.read.getDocumentModelModule(args.documentType);
3496
+ const document = withSignaturePolicy(module.utils.createDocument(), await clients.read.getCreateSignaturePolicy());
3381
3497
  if (name) document.header.name = name;
3382
- result = await pickDriveClient(reactorClient, parent.header.documentType, reactorDriveClient).addFile(parent.header.id, document);
3383
- } else result = await reactorClient.createEmpty(args.documentType, { parentIdentifier: parentIdOrSlug });
3384
- } else result = await reactorClient.createEmpty(args.documentType, {});
3498
+ receipt = await addFileToDrive(clients, parent.header.id, document);
3499
+ } else receipt = await (await clients.write.createEmpty(args.documentType, { parentIdentifier: parentIdOrSlug })).readable;
3500
+ } else receipt = await (await clients.write.createEmpty(args.documentType, {})).readable;
3385
3501
  } catch (error) {
3386
3502
  throw new GraphQLError(`Failed to create empty document: ${error instanceof Error ? error.message : "Unknown error"}`);
3387
3503
  }
3388
- result = await readAsCaller(reactorClient, result, subject);
3504
+ const result = await readAsCaller(clients.read, receipt, subject);
3389
3505
  try {
3390
3506
  return toGqlPhDocument(result);
3391
3507
  } catch (error) {
3392
3508
  throw new GraphQLError(`Failed to convert created document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3393
3509
  }
3394
3510
  }
3395
- async function createDocumentWithInitialState(reactorClient, args, reactorDriveClient, subject) {
3511
+ async function createDocumentWithInitialState(clients, args, _reactorDriveClient, subject) {
3396
3512
  const parentIdOrSlug = fromInputMaybe(args.parentIdOrSlug);
3397
3513
  const name = fromInputMaybe(args.name);
3398
3514
  const slug = fromInputMaybe(args.slug);
3399
3515
  const preferredEditor = fromInputMaybe(args.preferredEditor);
3400
3516
  let module;
3401
3517
  try {
3402
- module = await reactorClient.getDocumentModelModule(args.documentType);
3518
+ module = await clients.read.getDocumentModelModule(args.documentType);
3403
3519
  } catch (error) {
3404
3520
  throw new GraphQLError(`Document model not found for type ${args.documentType}: ${error instanceof Error ? error.message : "Unknown error"}`);
3405
3521
  }
3406
- const document = withSignaturePolicy(module.utils.createDocument(), await reactorClient.getCreateSignaturePolicy());
3522
+ const document = withSignaturePolicy(module.utils.createDocument(), await clients.read.getCreateSignaturePolicy());
3407
3523
  const allowedScopes = new Set(Object.keys(module.documentModel.global.specifications.at(-1)?.state ?? {}));
3408
3524
  const state = document.state;
3409
3525
  for (const [scope, scopeState] of Object.entries(args.initialState)) if (allowedScopes.has(scope) && scope in state) state[scope] = {
@@ -3412,64 +3528,62 @@ async function createDocumentWithInitialState(reactorClient, args, reactorDriveC
3412
3528
  };
3413
3529
  if (name) document.header.name = name;
3414
3530
  if (slug) {
3415
- await assertSlugAvailable(reactorClient, slug);
3531
+ await assertSlugAvailable(clients.read, slug);
3416
3532
  document.header.slug = slug;
3417
3533
  }
3418
3534
  if (preferredEditor) document.header.meta = {
3419
3535
  ...document.header.meta,
3420
3536
  preferredEditor
3421
3537
  };
3422
- let result;
3538
+ let receipt;
3423
3539
  if (parentIdOrSlug) {
3424
3540
  let parent;
3425
3541
  try {
3426
- parent = await reactorClient.get(parentIdOrSlug, subject && { subject });
3542
+ parent = await clients.read.get(parentIdOrSlug, subject && { subject });
3427
3543
  } catch (error) {
3428
3544
  throw new GraphQLError(`Parent document not found: ${error instanceof Error ? error.message : "Unknown error"}`);
3429
3545
  }
3430
- if (isDriveContainerType(parent.header.documentType)) {
3431
- const driveClient = pickDriveClient(reactorClient, parent.header.documentType, reactorDriveClient);
3432
- try {
3433
- result = await driveClient.addFile(parent.header.id, document);
3434
- } catch (error) {
3435
- throw new GraphQLError(`Failed to create document in drive: ${error instanceof Error ? error.message : "Unknown error"}`);
3436
- }
3437
- } else try {
3438
- result = await reactorClient.create(document, parentIdOrSlug);
3546
+ if (isDriveContainerType(parent.header.documentType)) try {
3547
+ receipt = await addFileToDrive(clients, parent.header.id, document);
3548
+ } catch (error) {
3549
+ throw new GraphQLError(`Failed to create document in drive: ${error instanceof Error ? error.message : "Unknown error"}`);
3550
+ }
3551
+ else try {
3552
+ receipt = await (await clients.write.create(document, parentIdOrSlug)).readable;
3439
3553
  } catch (error) {
3440
3554
  throw new GraphQLError(`Failed to create document with parent: ${error instanceof Error ? error.message : "Unknown error"}`);
3441
3555
  }
3442
3556
  } else try {
3443
- result = await reactorClient.create(document);
3557
+ receipt = await (await clients.write.create(document)).readable;
3444
3558
  } catch (error) {
3445
3559
  throw new GraphQLError(`Failed to create document: ${error instanceof Error ? error.message : "Unknown error"}`);
3446
3560
  }
3447
- result = await readAsCaller(reactorClient, result, subject);
3561
+ const result = await readAsCaller(clients.read, receipt, subject);
3448
3562
  try {
3449
3563
  return toGqlPhDocument(result);
3450
3564
  } catch (error) {
3451
3565
  throw new GraphQLError(`Failed to convert created document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3452
3566
  }
3453
3567
  }
3454
- /** The branch a mutation applies to when the caller names none. */
3455
- const DEFAULT_BRANCH = "main";
3456
3568
  /**
3457
- * Applies actions to a document and waits for the result.
3569
+ * Applies actions to a document and waits for the result: the write half
3570
+ * submits, the read half reads the document back with the write's token.
3458
3571
  *
3459
3572
  * The wire form of `IReactorClient.execute`, and named for it. Takes the actions
3460
3573
  * already coerced against `ActionInput`, so the only conversion left is the one
3461
3574
  * the schema cannot express: a signature travels as one string, and verification
3462
3575
  * reads it as the tuple it was.
3463
3576
  */
3464
- async function execute(reactorClient, args, subject) {
3577
+ async function execute(clients, args, subject) {
3465
3578
  const actions = toSubmittableActions(args.actions);
3466
3579
  const branch = fromInputMaybe(args.branch) ?? DEFAULT_BRANCH;
3467
- let result;
3580
+ let receipt;
3468
3581
  try {
3469
- result = await reactorClient.execute(args.documentIdOrSlug, branch, actions, void 0, subject);
3582
+ receipt = await (await clients.write.execute(args.documentIdOrSlug, branch, actions)).readable;
3470
3583
  } catch (error) {
3471
3584
  throw new GraphQLError(`Failed to execute actions: ${error instanceof Error ? error.message : "Unknown error"}`);
3472
3585
  }
3586
+ const result = await readAsCaller(clients.read, receipt, subject, branch);
3473
3587
  try {
3474
3588
  return toGqlPhDocument(result);
3475
3589
  } catch (error) {
@@ -3483,15 +3597,21 @@ async function execute(reactorClient, args, subject) {
3483
3597
  * `IReactorClient.executeAsync`. A job handed back from a submission has no
3484
3598
  * result yet, which is why `JobInfo.result` is nullable.
3485
3599
  */
3486
- async function executeAsync(reactorClient, args) {
3600
+ async function executeAsync(clients, args) {
3487
3601
  const actions = toSubmittableActions(args.actions);
3488
3602
  const branch = fromInputMaybe(args.branch) ?? DEFAULT_BRANCH;
3489
- let job;
3603
+ let jobId;
3490
3604
  try {
3491
- job = await reactorClient.executeAsync(args.documentIdOrSlug, branch, actions);
3605
+ jobId = (await clients.write.execute(args.documentIdOrSlug, branch, actions)).jobId;
3492
3606
  } catch (error) {
3493
3607
  throw new GraphQLError(`Failed to submit actions: ${error instanceof Error ? error.message : "Unknown error"}`);
3494
3608
  }
3609
+ let job;
3610
+ try {
3611
+ job = await clients.read.getJobStatus(jobId);
3612
+ } catch (error) {
3613
+ throw new GraphQLError(`Failed to read the submitted job: ${error instanceof Error ? error.message : "Unknown error"}`);
3614
+ }
3495
3615
  return toGqlJobInfo(job);
3496
3616
  }
3497
3617
  /** Authorized as a create, so only createDocument's own shape is accepted. */
@@ -3530,7 +3650,7 @@ function batchCreationOf(jobs) {
3530
3650
  * dependents, so a failure is reported per job as a FAILED entry rather than a
3531
3651
  * thrown error, which would lose what did commit.
3532
3652
  */
3533
- async function executeBatch(reactorClient, args) {
3653
+ async function executeBatch(write, args) {
3534
3654
  const jobs = args.jobs.map((job) => ({
3535
3655
  key: job.key,
3536
3656
  documentId: job.documentIdOrSlug,
@@ -3539,17 +3659,7 @@ async function executeBatch(reactorClient, args) {
3539
3659
  actions: toSubmittableActions(job.actions),
3540
3660
  dependsOn: [...job.dependsOn]
3541
3661
  }));
3542
- let outcome;
3543
- try {
3544
- outcome = await reactorClient.executeBatch({ jobs });
3545
- } catch (error) {
3546
- if (!BatchJobFailedError.isError(error)) {
3547
- const message = error instanceof Error ? error.message : "Unknown error";
3548
- throw new GraphQLError(`Failed to execute batch: ${message}. Jobs dispatched before the failure may have committed.`);
3549
- }
3550
- outcome = error;
3551
- }
3552
- const settled = BatchJobFailedError.isError(outcome) ? outcome.jobs : await readBackJobs(reactorClient, jobs, outcome);
3662
+ const settled = await settleBatch(write, jobs);
3553
3663
  try {
3554
3664
  return { jobs: jobs.map((job) => {
3555
3665
  if (!Object.hasOwn(settled, job.key)) throw new Error(`no job came back for plan key "${job.key}"`);
@@ -3563,20 +3673,38 @@ async function executeBatch(reactorClient, args) {
3563
3673
  throw new GraphQLError(`Failed to convert batch result to GraphQL: ${message}`);
3564
3674
  }
3565
3675
  }
3566
- /** The client hands back submission receipts; read each job's final state. */
3567
- async function readBackJobs(reactorClient, jobs, result) {
3568
- const entries = await Promise.all(jobs.map(async (job) => {
3569
- if (!Object.hasOwn(result.jobs, job.key)) throw new GraphQLError(`Batch result is missing plan key "${job.key}"; the reactor returned jobs for [${Object.keys(result.jobs).join(", ")}]`);
3570
- try {
3571
- return [job.key, await reactorClient.getJobStatus(result.jobs[job.key].id)];
3572
- } catch (error) {
3573
- const message = error instanceof Error ? error.message : "Unknown error";
3574
- throw new GraphQLError(`Failed to read batch job status: ${message}`);
3575
- }
3576
- }));
3577
- return Object.fromEntries(entries);
3676
+ /**
3677
+ * Submits the batch and waits for every job to settle, handing back each job's
3678
+ * final state by plan key: from the receipts when all reached READ_READY, from
3679
+ * the failure when one FAILED (which carries every job's state).
3680
+ */
3681
+ async function settleBatch(write, jobs) {
3682
+ const failed = (error) => {
3683
+ const message = error instanceof Error ? error.message : "Unknown error";
3684
+ throw new GraphQLError(`Failed to execute batch: ${message}. Jobs dispatched before the failure may have committed.`);
3685
+ };
3686
+ let batch;
3687
+ try {
3688
+ batch = await write.executeBatch({ jobs });
3689
+ } catch (error) {
3690
+ if (BatchJobFailedError.isError(error)) return error.jobs;
3691
+ return failed(error);
3692
+ }
3693
+ let receipts;
3694
+ try {
3695
+ receipts = await batch.readable;
3696
+ } catch (error) {
3697
+ if (BatchJobFailedError.isError(error)) return error.jobs;
3698
+ return failed(error);
3699
+ }
3700
+ const settled = {};
3701
+ for (const job of jobs) {
3702
+ if (!Object.hasOwn(receipts, job.key)) throw new GraphQLError(`Batch result is missing plan key "${job.key}"; the reactor returned jobs for [${Object.keys(receipts).join(", ")}]`);
3703
+ settled[job.key] = receipts[job.key].job;
3704
+ }
3705
+ return settled;
3578
3706
  }
3579
- async function mutateDocument(reactorClient, args, subject) {
3707
+ async function mutateDocument(clients, args, subject) {
3580
3708
  let validatedActions;
3581
3709
  try {
3582
3710
  validatedActions = validateActions(args.actions);
@@ -3585,19 +3713,20 @@ async function mutateDocument(reactorClient, args, subject) {
3585
3713
  throw new GraphQLError(`Action validation failed: ${error instanceof Error ? error.message : "Unknown error"}`);
3586
3714
  }
3587
3715
  const branch = args.view?.branch ?? "main";
3588
- let result;
3716
+ let receipt;
3589
3717
  try {
3590
- result = await reactorClient.execute(args.documentIdentifier, branch, validatedActions, void 0, subject);
3718
+ receipt = await (await clients.write.execute(args.documentIdentifier, branch, validatedActions)).readable;
3591
3719
  } catch (error) {
3592
3720
  throw new GraphQLError(`Failed to mutate document: ${error instanceof Error ? error.message : "Unknown error"}`);
3593
3721
  }
3722
+ const result = await readAsCaller(clients.read, receipt, subject, branch);
3594
3723
  try {
3595
3724
  return toGqlPhDocument(result);
3596
3725
  } catch (error) {
3597
3726
  throw new GraphQLError(`Failed to convert mutated document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3598
3727
  }
3599
3728
  }
3600
- async function mutateDocumentAsync(reactorClient, args) {
3729
+ async function mutateDocumentAsync(write, args) {
3601
3730
  let validatedActions;
3602
3731
  try {
3603
3732
  validatedActions = validateActions(args.actions);
@@ -3606,103 +3735,103 @@ async function mutateDocumentAsync(reactorClient, args) {
3606
3735
  throw new GraphQLError(`Action validation failed: ${error instanceof Error ? error.message : "Unknown error"}`);
3607
3736
  }
3608
3737
  const branch = args.view?.branch ?? "main";
3609
- let result;
3610
3738
  try {
3611
- result = await reactorClient.executeAsync(args.documentIdentifier, branch, validatedActions);
3739
+ return (await write.execute(args.documentIdentifier, branch, validatedActions)).jobId;
3612
3740
  } catch (error) {
3613
3741
  throw new GraphQLError(`Failed to submit document mutation: ${error instanceof Error ? error.message : "Unknown error"}`);
3614
3742
  }
3615
- return result.id;
3616
3743
  }
3617
- async function renameDocument(reactorClient, args, signal, subject) {
3744
+ async function renameDocument(clients, args, signal, subject) {
3618
3745
  const branch = fromInputMaybe(args.branch);
3619
- let result;
3746
+ let receipt;
3620
3747
  try {
3621
- result = await reactorClient.rename(args.documentIdOrSlug, args.name, branch, signal);
3748
+ receipt = await (await clients.write.rename(args.documentIdOrSlug, args.name, branch, signal)).readable;
3622
3749
  } catch (error) {
3623
3750
  throw new GraphQLError(`Failed to rename document: ${error instanceof Error ? error.message : "Unknown error"}`);
3624
3751
  }
3625
- result = await readAsCaller(reactorClient, result, subject, branch);
3752
+ const result = await readAsCaller(clients.read, receipt, subject, branch);
3626
3753
  try {
3627
3754
  return toGqlPhDocument(result);
3628
3755
  } catch (error) {
3629
3756
  throw new GraphQLError(`Failed to convert renamed document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3630
3757
  }
3631
3758
  }
3632
- async function setPreferredEditor(reactorClient, args, signal, subject) {
3759
+ async function setPreferredEditor(clients, args, signal, subject) {
3633
3760
  const branch = fromInputMaybe(args.branch);
3634
3761
  const preferredEditor = fromInputMaybe(args.preferredEditor) ?? null;
3635
- let result;
3762
+ let receipt;
3636
3763
  try {
3637
- result = await reactorClient.setPreferredEditor(args.documentIdOrSlug, preferredEditor, branch, signal);
3764
+ receipt = await (await clients.write.setPreferredEditor(args.documentIdOrSlug, preferredEditor, branch, signal)).readable;
3638
3765
  } catch (error) {
3639
3766
  throw new GraphQLError(`Failed to set preferred editor: ${error instanceof Error ? error.message : "Unknown error"}`);
3640
3767
  }
3641
- result = await readAsCaller(reactorClient, result, subject, branch);
3768
+ const result = await readAsCaller(clients.read, receipt, subject, branch);
3642
3769
  try {
3643
3770
  return toGqlPhDocument(result);
3644
3771
  } catch (error) {
3645
3772
  throw new GraphQLError(`Failed to convert updated document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3646
3773
  }
3647
3774
  }
3648
- async function addRelationship(reactorClient, args, subject) {
3775
+ async function addRelationship(clients, args, subject) {
3649
3776
  const branch = fromInputMaybe(args.branch);
3650
3777
  const metadata = fromInputMaybe(args.metadata);
3651
- let result;
3778
+ let receipt;
3652
3779
  try {
3653
- result = await reactorClient.addRelationship(args.sourceIdOrSlug, args.targetIdOrSlug, args.relationshipType, metadata, branch);
3780
+ receipt = await (await clients.write.addRelationship(args.sourceIdOrSlug, args.targetIdOrSlug, args.relationshipType, metadata, branch)).readable;
3654
3781
  } catch (error) {
3655
3782
  throw new GraphQLError(`Failed to add relationship: ${error instanceof Error ? error.message : "Unknown error"}`);
3656
3783
  }
3657
- result = await readAsCaller(reactorClient, result, subject, branch);
3784
+ const result = await readAsCaller(clients.read, receipt, subject, branch);
3658
3785
  try {
3659
3786
  return toGqlPhDocument(result);
3660
3787
  } catch (error) {
3661
3788
  throw new GraphQLError(`Failed to convert document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3662
3789
  }
3663
3790
  }
3664
- async function updateRelationship(reactorClient, args, subject) {
3791
+ async function updateRelationship(clients, args, subject) {
3665
3792
  const branch = fromInputMaybe(args.branch);
3666
3793
  const metadata = fromInputMaybe(args.metadata) ?? null;
3667
- let result;
3794
+ let receipt;
3668
3795
  try {
3669
- result = await reactorClient.updateRelationship(args.sourceIdOrSlug, args.targetIdOrSlug, args.relationshipType, metadata, branch);
3796
+ receipt = await (await clients.write.updateRelationship(args.sourceIdOrSlug, args.targetIdOrSlug, args.relationshipType, metadata, branch)).readable;
3670
3797
  } catch (error) {
3671
3798
  throw new GraphQLError(`Failed to update relationship: ${error instanceof Error ? error.message : "Unknown error"}`);
3672
3799
  }
3673
- result = await readAsCaller(reactorClient, result, subject, branch);
3800
+ const result = await readAsCaller(clients.read, receipt, subject, branch);
3674
3801
  try {
3675
3802
  return toGqlPhDocument(result);
3676
3803
  } catch (error) {
3677
3804
  throw new GraphQLError(`Failed to convert document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3678
3805
  }
3679
3806
  }
3680
- async function removeRelationship(reactorClient, args, subject) {
3807
+ async function removeRelationship(clients, args, subject) {
3681
3808
  const branch = fromInputMaybe(args.branch);
3682
- let result;
3809
+ let receipt;
3683
3810
  try {
3684
- result = await reactorClient.removeRelationship(args.sourceIdOrSlug, args.targetIdOrSlug, args.relationshipType, branch);
3811
+ receipt = await (await clients.write.removeRelationship(args.sourceIdOrSlug, args.targetIdOrSlug, args.relationshipType, branch)).readable;
3685
3812
  } catch (error) {
3686
3813
  throw new GraphQLError(`Failed to remove relationship: ${error instanceof Error ? error.message : "Unknown error"}`);
3687
3814
  }
3688
- result = await readAsCaller(reactorClient, result, subject, branch);
3815
+ const result = await readAsCaller(clients.read, receipt, subject, branch);
3689
3816
  try {
3690
3817
  return toGqlPhDocument(result);
3691
3818
  } catch (error) {
3692
3819
  throw new GraphQLError(`Failed to convert document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3693
3820
  }
3694
3821
  }
3695
- async function moveRelationship(reactorClient, args, subject) {
3822
+ async function moveRelationship(clients, args, subject) {
3696
3823
  const branch = fromInputMaybe(args.branch);
3697
- let result;
3824
+ let removed;
3825
+ let added;
3698
3826
  try {
3699
- result = await reactorClient.moveRelationship(args.sourceParentIdOrSlug, args.targetParentIdOrSlug, args.targetIdOrSlug, args.relationshipType, branch);
3827
+ const handles = await clients.write.moveRelationship(args.sourceParentIdOrSlug, args.targetParentIdOrSlug, args.targetIdOrSlug, args.relationshipType, branch);
3828
+ [removed, added] = await Promise.all([handles.removed.readable, handles.added.readable]);
3700
3829
  } catch (error) {
3701
3830
  throw new GraphQLError(`Failed to move relationship: ${error instanceof Error ? error.message : "Unknown error"}`);
3702
3831
  }
3703
- result = {
3704
- source: await readAsCaller(reactorClient, result.source, subject, branch),
3705
- target: await readAsCaller(reactorClient, result.target, subject, branch)
3832
+ const result = {
3833
+ source: await readAsCaller(clients.read, removed, subject, branch),
3834
+ target: await readAsCaller(clients.read, added, subject, branch)
3706
3835
  };
3707
3836
  try {
3708
3837
  return {
@@ -3713,25 +3842,25 @@ async function moveRelationship(reactorClient, args, subject) {
3713
3842
  throw new GraphQLError(`Failed to convert documents to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
3714
3843
  }
3715
3844
  }
3716
- async function deleteDocument(reactorClient, args, reactorDriveClient) {
3845
+ async function deleteDocument(clients, args, _reactorDriveClient) {
3717
3846
  const propagate = toReactorPropagationMode(args.propagate);
3718
3847
  try {
3719
- const driveParent = (await reactorClient.getIncomingRelationships(args.idOrSlug, "child")).results.find((p) => isDriveContainerType(p.header.documentType));
3848
+ const driveParent = (await clients.read.getIncomingRelationships(args.idOrSlug, "child")).results.find((p) => isDriveContainerType(p.header.documentType));
3720
3849
  if (driveParent) {
3721
- const driveClient = pickDriveClient(reactorClient, driveParent.header.documentType, reactorDriveClient);
3722
- const documentId = await reactorClient.resolveIdOrSlug(args.idOrSlug);
3723
- await driveClient.removeNode(driveParent.header.id, documentId);
3724
- } else await reactorClient.deleteDocument(args.idOrSlug, propagate);
3850
+ const documentId = await clients.read.resolveIdOrSlug(args.idOrSlug);
3851
+ await removeNodeFromDrive(clients, driveParent.header.id, documentId);
3852
+ } else await (await clients.write.deleteDocument(args.idOrSlug, propagate)).readable;
3725
3853
  return true;
3726
3854
  } catch (error) {
3727
3855
  throw new GraphQLError(`Failed to delete document: ${error instanceof Error ? error.message : "Unknown error"}`);
3728
3856
  }
3729
3857
  }
3730
- async function deleteDocuments(reactorClient, args) {
3858
+ async function deleteDocuments(write, args) {
3731
3859
  const propagate = toReactorPropagationMode(args.propagate);
3732
3860
  const idsOrSlugs = [...args.idsOrSlugs];
3733
3861
  try {
3734
- await reactorClient.deleteDocuments(idsOrSlugs, propagate);
3862
+ const handles = await write.deleteDocuments(idsOrSlugs, propagate);
3863
+ await Promise.all(handles.map((handle) => handle.readable));
3735
3864
  return true;
3736
3865
  } catch (error) {
3737
3866
  throw new GraphQLError(`Failed to delete documents: ${error instanceof Error ? error.message : "Unknown error"}`);
@@ -4086,8 +4215,9 @@ async function pushSyncEnvelopes(syncManager, args) {
4086
4215
  //#endregion
4087
4216
  //#region src/graphql/document-model-subgraph.ts
4088
4217
  /**
4089
- * New document model subgraph that uses reactorClient instead of legacy reactor.
4090
- * This class auto-generates GraphQL queries and mutations for a document model.
4218
+ * Auto-generates GraphQL queries and mutations for a document model. Queries
4219
+ * read through `ctx.clients.read`; mutations write through `ctx.clients.write`
4220
+ * and read their document back with the write's token.
4091
4221
  */
4092
4222
  var DocumentModelSubgraph = class extends BaseSubgraph {
4093
4223
  documentModel;
@@ -4112,6 +4242,19 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
4112
4242
  const documentName = getDocumentModelSchemaName(this.documentModel.documentModel.global);
4113
4243
  return this.resolvers[`${documentName}Mutations`];
4114
4244
  }
4245
+ /**
4246
+ * Refuses a model operation on a document of another type. Asked of the
4247
+ * write half (`describe`), which answers for what the write path sees.
4248
+ */
4249
+ async #assertDocumentType(clients, documentId, requested, documentType) {
4250
+ let target;
4251
+ try {
4252
+ target = await clients.write.describe(documentId);
4253
+ } catch (error) {
4254
+ throw new GraphQLError(error instanceof Error ? error.message : "Document not found");
4255
+ }
4256
+ if (target.documentType !== documentType) throw new GraphQLError(`Document with id ${requested} is not of type ${documentType}`);
4257
+ }
4115
4258
  /** Drops the items the host's own ACL refuses the caller. */
4116
4259
  async #readableItems(page, ctx) {
4117
4260
  return {
@@ -4177,7 +4320,7 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
4177
4320
  const idOrSlug = requireOneOf(args, "idOrSlug", "identifier");
4178
4321
  const { view } = args;
4179
4322
  if (!idOrSlug) throw new GraphQLError("Document identifier is required");
4180
- const result = await document(this.reactorClient, {
4323
+ const result = await document(this.clientsOf(ctx).read, {
4181
4324
  idOrSlug,
4182
4325
  view
4183
4326
  }, this.viewSubject(ctx));
@@ -4187,7 +4330,7 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
4187
4330
  },
4188
4331
  documents: async (_, args, ctx) => {
4189
4332
  const { paging } = args;
4190
- const result = await findDocuments(this.reactorClient, {
4333
+ const result = await findDocuments(this.clientsOf(ctx).read, {
4191
4334
  search: { type: documentType },
4192
4335
  paging
4193
4336
  }, this.viewSubject(ctx));
@@ -4195,7 +4338,7 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
4195
4338
  },
4196
4339
  findDocuments: async (_, args, ctx) => {
4197
4340
  const { search, view, paging } = args;
4198
- const result = await findDocuments(this.reactorClient, {
4341
+ const result = await findDocuments(this.clientsOf(ctx).read, {
4199
4342
  search: {
4200
4343
  type: documentType,
4201
4344
  parentId: search?.parentId
@@ -4209,7 +4352,7 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
4209
4352
  const sourceIdOrSlug = requireOneOf(args, "sourceIdOrSlug", "sourceIdentifier");
4210
4353
  const { relationshipType, view, paging } = args;
4211
4354
  const handle = await this.assertCanRead(sourceIdOrSlug, ctx);
4212
- const result = await documentOutgoingRelationships(this.reactorClient, {
4355
+ const result = await documentOutgoingRelationships(this.clientsOf(ctx).read, {
4213
4356
  sourceIdOrSlug: handle.fetchIdentifier,
4214
4357
  relationshipType,
4215
4358
  view,
@@ -4226,7 +4369,7 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
4226
4369
  const targetIdOrSlug = requireOneOf(args, "targetIdOrSlug", "targetIdentifier");
4227
4370
  const { relationshipType, view, paging } = args;
4228
4371
  const handle = await this.assertCanRead(targetIdOrSlug, ctx);
4229
- const result = await documentIncomingRelationships(this.reactorClient, {
4372
+ const result = await documentIncomingRelationships(this.clientsOf(ctx).read, {
4230
4373
  targetIdOrSlug: handle.fetchIdentifier,
4231
4374
  relationshipType,
4232
4375
  view,
@@ -4244,7 +4387,7 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
4244
4387
  else this.assertCanCreate(ctx);
4245
4388
  const withHeader = !!(initialState || preferredEditor || slug);
4246
4389
  let createdDoc;
4247
- if (withHeader) createdDoc = await createDocumentWithInitialState(this.reactorClient, {
4390
+ if (withHeader) createdDoc = await createDocumentWithInitialState(this.clientsOf(ctx), {
4248
4391
  documentType,
4249
4392
  parentIdOrSlug,
4250
4393
  name,
@@ -4252,20 +4395,24 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
4252
4395
  preferredEditor,
4253
4396
  initialState: initialState ?? {}
4254
4397
  }, this.graphqlManager.reactorDriveClient, this.viewSubject(ctx));
4255
- else createdDoc = await createEmptyDocument(this.reactorClient, {
4398
+ else createdDoc = await createEmptyDocument(this.clientsOf(ctx), {
4256
4399
  documentType,
4257
4400
  parentIdOrSlug,
4258
4401
  name
4259
4402
  }, this.graphqlManager.reactorDriveClient, this.viewSubject(ctx));
4260
4403
  if (ctx.user?.address && createdDoc?.id) await this.documentPermissionService?.initializeDocumentProtection(createdDoc.id, ctx.user.address, this.authorizationService.config.defaultProtection);
4261
- if (!withHeader && name && createdDoc.name !== name) return toGqlPhDocument(await this.reactorClient.execute(createdDoc.id, "main", [setName(name)], void 0, this.viewSubject(ctx)));
4404
+ if (!withHeader && name && createdDoc.name !== name) {
4405
+ const clients = this.clientsOf(ctx);
4406
+ const renamed = await clients.write.execute(createdDoc.id, "main", [setName(name)]);
4407
+ return toGqlPhDocument(await readAsCaller(clients.read, await renamed.readable, this.viewSubject(ctx)));
4408
+ }
4262
4409
  return createdDoc;
4263
4410
  },
4264
4411
  createEmptyDocument: async (_, args, ctx) => {
4265
4412
  let parentIdOrSlug = optionalOneOf(args, "parentIdOrSlug", "parentIdentifier");
4266
4413
  if (parentIdOrSlug) parentIdOrSlug = (await this.assertCanWrite(parentIdOrSlug, ctx)).fetchIdentifier;
4267
4414
  else this.assertCanCreate(ctx);
4268
- const result = await createEmptyDocument(this.reactorClient, {
4415
+ const result = await createEmptyDocument(this.clientsOf(ctx), {
4269
4416
  documentType,
4270
4417
  parentIdOrSlug
4271
4418
  }, this.graphqlManager.reactorDriveClient, this.viewSubject(ctx));
@@ -4277,24 +4424,28 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
4277
4424
  const documentIdOrSlug = requireOneOf(args, "documentIdOrSlug", "docId");
4278
4425
  const { input } = args;
4279
4426
  const effectiveDocId = (await this.assertCanExecuteOperation(documentIdOrSlug, op.name, ctx)).fetchIdentifier;
4280
- if ((await this.reactorClient.get(effectiveDocId, { subject: this.viewSubject(ctx) })).header.documentType !== documentType) throw new GraphQLError(`Document with id ${documentIdOrSlug} is not of type ${documentType}`);
4427
+ const clients = this.clientsOf(ctx);
4428
+ await this.#assertDocumentType(clients, effectiveDocId, documentIdOrSlug, documentType);
4281
4429
  const action = this.documentModel.actions[camelCase(op.name)];
4282
4430
  if (!action) throw new GraphQLError(`Action ${op.name} not found`);
4431
+ let receipt;
4283
4432
  try {
4284
- return toGqlPhDocument(await this.reactorClient.execute(effectiveDocId, "main", [action(input)], void 0, this.viewSubject(ctx)));
4433
+ receipt = await (await clients.write.execute(effectiveDocId, "main", [action(input)])).readable;
4285
4434
  } catch (error) {
4286
4435
  throw new GraphQLError(error instanceof Error ? error.message : `Failed to ${op.name}`);
4287
4436
  }
4437
+ return toGqlPhDocument(await readAsCaller(clients.read, receipt, this.viewSubject(ctx)));
4288
4438
  };
4289
4439
  mutations[`${camelCase(op.name)}Async`] = async (_, args, ctx) => {
4290
4440
  const documentIdOrSlug = requireOneOf(args, "documentIdOrSlug", "docId");
4291
4441
  const { input } = args;
4292
4442
  const effectiveDocId = (await this.assertCanExecuteOperation(documentIdOrSlug, op.name, ctx)).fetchIdentifier;
4293
- if ((await this.reactorClient.get(effectiveDocId, { subject: this.viewSubject(ctx) })).header.documentType !== documentType) throw new GraphQLError(`Document with id ${documentIdOrSlug} is not of type ${documentType}`);
4443
+ const clients = this.clientsOf(ctx);
4444
+ await this.#assertDocumentType(clients, effectiveDocId, documentIdOrSlug, documentType);
4294
4445
  const action = this.documentModel.actions[camelCase(op.name)];
4295
4446
  if (!action) throw new GraphQLError(`Action ${op.name} not found`);
4296
4447
  try {
4297
- return (await this.reactorClient.executeAsync(effectiveDocId, "main", [action(input)])).id;
4448
+ return (await clients.write.execute(effectiveDocId, "main", [action(input)])).jobId;
4298
4449
  } catch (error) {
4299
4450
  throw new GraphQLError(error instanceof Error ? error.message : `Failed to ${op.name}`);
4300
4451
  }
@@ -5298,13 +5449,19 @@ var GraphQLManager = class {
5298
5449
  * it for reactor-drive parents.
5299
5450
  */
5300
5451
  reactorDriveClient;
5452
+ /** See {@link GraphQLManagerOptions.driveNodes}. */
5453
+ driveNodes;
5301
5454
  authorizationService;
5302
5455
  /** Route service in use: the injected one, or one built on first need. */
5303
5456
  #fallbackRoutes;
5304
5457
  path;
5305
5458
  httpServer;
5306
5459
  wsServer;
5307
- reactorClient;
5460
+ #readClient;
5461
+ #facade;
5462
+ #clients;
5463
+ /** What a context carries before its operation is known: no write. */
5464
+ #unboundClients;
5308
5465
  relationalDb;
5309
5466
  analyticsStore;
5310
5467
  syncManager;
@@ -5325,7 +5482,11 @@ var GraphQLManager = class {
5325
5482
  this.path = options.path;
5326
5483
  this.httpServer = options.httpServer;
5327
5484
  this.wsServer = options.wsServer;
5328
- this.reactorClient = options.reactorClient;
5485
+ const { read, write } = resolveClientHalves(options);
5486
+ this.#readClient = read;
5487
+ this.#facade = options.reactorClient;
5488
+ this.#clients = new RequestClientBinder(read, write);
5489
+ this.#unboundClients = this.#clients.unboundClients();
5329
5490
  this.relationalDb = options.relationalDb;
5330
5491
  this.analyticsStore = options.analyticsStore;
5331
5492
  this.syncManager = options.syncManager;
@@ -5348,6 +5509,7 @@ var GraphQLManager = class {
5348
5509
  this.port = options.port ?? 4001;
5349
5510
  this.authorizationService = options.authorizationService;
5350
5511
  this.reactorDriveClient = options.reactorDriveClient;
5512
+ this.driveNodes = options.driveNodes;
5351
5513
  this.syncServingGate = options.syncServingGate;
5352
5514
  this.httpRoutes = options.httpRoutes;
5353
5515
  this.attachments = options.attachments;
@@ -5356,7 +5518,7 @@ var GraphQLManager = class {
5356
5518
  logger: options.logger,
5357
5519
  report: options.reportError
5358
5520
  };
5359
- this.driveOwnershipCache = new DriveOwnershipCache(options.driveStore ?? this.reactorClient);
5521
+ this.driveOwnershipCache = new DriveOwnershipCache(options.driveStore ?? this.#readClient);
5360
5522
  this.#wsRouter = new SubgraphWsRouter({
5361
5523
  order: (subgraphs) => this.#byClaimPriority(subgraphs),
5362
5524
  logger: this.logger
@@ -5369,7 +5531,7 @@ var GraphQLManager = class {
5369
5531
  await this.driveOwnershipCache.init();
5370
5532
  this.#driveMiddleware = createDriveFetchMiddleware(this.driveOwnershipCache);
5371
5533
  this.logger.debug(`Drive ownership cache populated with ${this.driveOwnershipCache.size()} drives`);
5372
- const models = (await this.reactorClient.getDocumentModelModules()).results;
5534
+ const models = (await this.#readClient.getDocumentModelModules()).results;
5373
5535
  if (!models.find((it) => it.documentModel.global.name === "DocumentDrive")) throw new Error("DocumentDrive model required");
5374
5536
  await this.gatewayAdapter.start(this.httpServer);
5375
5537
  this.httpAdapter.setupMiddleware({ bodyLimit: "50mb" });
@@ -5382,7 +5544,7 @@ var GraphQLManager = class {
5382
5544
  if (!driveIdOrSlug) return Response.json({ error: "Drive ID or slug is required" }, { status: 400 });
5383
5545
  const user = getAuthContext(request)?.user;
5384
5546
  try {
5385
- const driveDoc = await this.reactorClient.get(driveIdOrSlug, { subject: callerSubject(user) });
5547
+ const driveDoc = await this.#readClient.get(driveIdOrSlug, { subject: callerSubject(user) });
5386
5548
  if (!await this.authorizationService.canRead(driveDoc.header.id, user?.address)) {
5387
5549
  this.logger.debug(`Drive read refused: ${driveIdOrSlug}`);
5388
5550
  return Response.json({ error: "Drive not found" }, { status: 404 });
@@ -5420,7 +5582,7 @@ var GraphQLManager = class {
5420
5582
  }
5421
5583
  async #regenerateDocumentModelSubgraphs() {
5422
5584
  try {
5423
- const models = (await this.reactorClient.getDocumentModelModules()).results;
5585
+ const models = (await this.#readClient.getDocumentModelModules()).results;
5424
5586
  this.cachedDocumentModels = this.#admitModels(models);
5425
5587
  const registeredNames = await this.#setupDocumentModelSubgraphs("graphql", this.cachedDocumentModels);
5426
5588
  await this.#pruneOrigin(DOCUMENT_MODEL_ORIGIN, registeredNames);
@@ -5465,7 +5627,8 @@ var GraphQLManager = class {
5465
5627
  http: this.scopeForPackage(CORE_PACKAGE_NAME),
5466
5628
  relationalDb: this.relationalDb,
5467
5629
  analyticsStore: this.analyticsStore,
5468
- reactorClient: this.reactorClient,
5630
+ readClient: this.#readClient,
5631
+ reactorClient: this.#facade,
5469
5632
  graphqlManager: this,
5470
5633
  syncManager: this.syncManager,
5471
5634
  path: this.path,
@@ -5819,7 +5982,8 @@ var GraphQLManager = class {
5819
5982
  http: this.scopeForPackage(packageName ?? "@powerhousedao/reactor-api"),
5820
5983
  relationalDb: this.relationalDb,
5821
5984
  analyticsStore: this.analyticsStore,
5822
- reactorClient: this.reactorClient,
5985
+ readClient: this.#readClient,
5986
+ reactorClient: this.#facade,
5823
5987
  graphqlManager: this,
5824
5988
  syncManager: this.syncManager,
5825
5989
  path: this.path,
@@ -6000,7 +6164,8 @@ var GraphQLManager = class {
6000
6164
  db: this.relationalDb,
6001
6165
  ...this.getAdditionalContextFields(),
6002
6166
  driveId,
6003
- user: authCtx?.user
6167
+ user: authCtx?.user,
6168
+ clients: this.#unboundClients
6004
6169
  });
6005
6170
  };
6006
6171
  }
@@ -6014,7 +6179,8 @@ var GraphQLManager = class {
6014
6179
  headers: connectionParams,
6015
6180
  db: this.relationalDb,
6016
6181
  ...this.getAdditionalContextFields(),
6017
- user
6182
+ user,
6183
+ clients: this.#unboundClients
6018
6184
  })
6019
6185
  });
6020
6186
  }
@@ -6081,7 +6247,7 @@ var GraphQLManager = class {
6081
6247
  } else this.#unmountSubgraph(cached.subgraph, supergraph);
6082
6248
  }
6083
6249
  const generated = this.#generated();
6084
- const schema = createSchema(this.cachedDocumentModels, subgraph.resolvers, subgraph.typeDefs, this.#schemaOptions(subgraph));
6250
+ const schema = createSchema(this.cachedDocumentModels, this.#boundResolvers(subgraph), subgraph.typeDefs, this.#schemaOptions(subgraph));
6085
6251
  const rawHandler = await this.gatewayAdapter.createHandler(schema, this.#makeContextFactory());
6086
6252
  if (!subgraphsMap.get(supergraph)?.includes(subgraph)) continue;
6087
6253
  if (generated !== this.#generated()) continue;
@@ -6179,8 +6345,21 @@ var GraphQLManager = class {
6179
6345
  });
6180
6346
  return claims;
6181
6347
  }
6348
+ /**
6349
+ * The subgraph's resolvers, each handed the context for the operation it runs
6350
+ * in: `ctx.clients.write` only in a mutation, or in a query field a core
6351
+ * subgraph declares in `writeSideQueries`.
6352
+ */
6353
+ #boundResolvers(subgraph) {
6354
+ const writeSide = subgraph.writeSideQueries && this.#isCore(subgraph) ? new Set(subgraph.writeSideQueries) : void 0;
6355
+ return this.#clients.bindResolvers(subgraph.resolvers, writeSide);
6356
+ }
6357
+ #isCore(subgraph) {
6358
+ for (const subgraphs of this.coreSubgraphsMap.values()) if (subgraphs.includes(subgraph)) return true;
6359
+ return false;
6360
+ }
6182
6361
  #buildSubgraphSchemaModule(subgraph) {
6183
- return buildSubgraphSchemaModule(this.cachedDocumentModels, subgraph.resolvers, subgraph.typeDefs, this.#schemaOptions(subgraph));
6362
+ return buildSubgraphSchemaModule(this.cachedDocumentModels, this.#boundResolvers(subgraph), subgraph.typeDefs, this.#schemaOptions(subgraph));
6184
6363
  }
6185
6364
  #getSubgraphDefinitions() {
6186
6365
  const subgraphs = this.#getSupergraphSubgraphs();
@@ -6320,6 +6499,26 @@ function subscriptionOwners(subgraphs, schema) {
6320
6499
  return tags;
6321
6500
  };
6322
6501
  }
6502
+ /**
6503
+ * The client halves a manager runs on: the ones passed, or, from a deprecated
6504
+ * facade, its own halves. A facade without halves (an older implementation)
6505
+ * is itself the read half and is adapted for writes.
6506
+ */
6507
+ function resolveClientHalves(options) {
6508
+ if (options.readClient && options.writeClient) return {
6509
+ read: options.readClient,
6510
+ write: options.writeClient
6511
+ };
6512
+ const facade = options.reactorClient;
6513
+ if (!facade) throw new Error("GraphQLManager needs readClient and writeClient (or a reactorClient)");
6514
+ warnOnce("GraphQLManagerOptions.reactorClient", "Pass readClient and writeClient; the facade is kept for subgraphs only.");
6515
+ const read = facade.read;
6516
+ const write = facade.write;
6517
+ return {
6518
+ read: options.readClient ?? (typeof read?.get === "function" ? read : facade),
6519
+ write: options.writeClient ?? (typeof write?.execute === "function" ? write : new FacadeWriteClient(facade))
6520
+ };
6521
+ }
6323
6522
  //#endregion
6324
6523
  //#region src/graphql/inspection/resolvers.ts
6325
6524
  function operatorRequired() {
@@ -6509,11 +6708,11 @@ var InspectionSubgraph = class extends BaseSubgraph {
6509
6708
  readerFor(ctx) {
6510
6709
  const subject = this.viewSubject(ctx);
6511
6710
  return {
6512
- find: (search, view, paging) => this.reactorClient.find(search, {
6711
+ find: (search, view, paging) => this.clientsOf(ctx).read.find(search, {
6513
6712
  ...view,
6514
6713
  subject
6515
6714
  }, paging),
6516
- get: (id, view) => this.reactorClient.get(id, {
6715
+ get: (id, view) => this.clientsOf(ctx).read.get(id, {
6517
6716
  ...view,
6518
6717
  subject
6519
6718
  })
@@ -6526,12 +6725,12 @@ var InspectionSubgraph = class extends BaseSubgraph {
6526
6725
  };
6527
6726
  let served;
6528
6727
  try {
6529
- served = await this.reactorClient.isServed(identifier, view);
6728
+ served = await this.clientsOf(ctx).read.isServed(identifier, view);
6530
6729
  } catch {
6531
6730
  return;
6532
6731
  }
6533
6732
  if (!served) return;
6534
- const document = await this.reactorClient.get(identifier, view);
6733
+ const document = await this.clientsOf(ctx).read.get(identifier, view);
6535
6734
  return {
6536
6735
  id: document.header.id,
6537
6736
  scopes: new Set(Object.keys(document.state ?? {}))
@@ -7087,6 +7286,19 @@ const CreateDefaultsDTO = z.object({
7087
7286
  signaturePolicy: z.string(),
7088
7287
  protocolVersions: JSONObjectDTO
7089
7288
  }).strip();
7289
+ const DriveNodeDTO = z.object({
7290
+ id: z.string(),
7291
+ driveId: z.string(),
7292
+ name: z.string(),
7293
+ parentFolder: z.string().nullable().optional(),
7294
+ documentType: z.string().optional()
7295
+ }).strip();
7296
+ const DriveNodeListDTO = z.array(DriveNodeDTO);
7297
+ const DriveNodePageDTO = z.object({
7298
+ results: z.array(DriveNodeDTO),
7299
+ nextCursor: z.string().nullable().optional(),
7300
+ hasMore: z.boolean()
7301
+ }).strip();
7090
7302
  const ActionEvaluationDTO = z.object({
7091
7303
  decision: z.enum(["ALLOW", "DENY"]),
7092
7304
  reason: z.string().nullable().optional()
@@ -7141,6 +7353,15 @@ const operationValidators = {
7141
7353
  GetCreateDefaults: (data) => {
7142
7354
  if (data.createDefaults) CreateDefaultsDTO.parse(data.createDefaults);
7143
7355
  },
7356
+ GetDriveNodes: (data) => {
7357
+ if (data.driveNodes) DriveNodePageDTO.parse(data.driveNodes);
7358
+ },
7359
+ GetDriveNode: (data) => {
7360
+ if (data.driveNode) DriveNodeDTO.parse(data.driveNode);
7361
+ },
7362
+ GetDriveDescendants: (data) => {
7363
+ if (data.driveDescendants) DriveNodeListDTO.parse(data.driveDescendants);
7364
+ },
7144
7365
  EvaluateActions: (data) => {
7145
7366
  if (data.evaluateActions) ActionEvaluationsDTO.parse(data.evaluateActions);
7146
7367
  },
@@ -7211,6 +7432,49 @@ function createReactorGraphQLClient(url, fetchImpl = fetch, headers) {
7211
7432
  return getSdk(createValidatingRequester(url, fetchImpl, headers));
7212
7433
  }
7213
7434
  //#endregion
7435
+ //#region src/graphql/reactor/drive-nodes.ts
7436
+ const DEFAULT_LIMIT = 100;
7437
+ /** The node source, or the refusal a host without one answers with. */
7438
+ function requireDriveNodeSource(source) {
7439
+ if (!source) throw new GraphQLError("Drive node queries are unavailable: no drive node source is configured on this server", { extensions: { code: "DRIVE_NODE_SOURCE_NOT_CONFIGURED" } });
7440
+ return source;
7441
+ }
7442
+ /** The GraphQL type of a node record, for the `DriveNode` union. */
7443
+ function driveNodeTypeName(node) {
7444
+ const kind = node.kind;
7445
+ if (kind === "file" || kind === "folder") return kind === "file" ? "DriveFileNode" : "DriveFolderNode";
7446
+ return "documentType" in node ? "DriveFileNode" : "DriveFolderNode";
7447
+ }
7448
+ /** One node; undefined when absent or when the drive is withheld. */
7449
+ async function getServedNode(source, gate, driveId, nodeId) {
7450
+ if (!await gate.servesDrive(driveId)) return;
7451
+ return source.getNode(driveId, nodeId);
7452
+ }
7453
+ /** The descendants of `root`; empty when the drive is withheld. */
7454
+ async function getServedDescendants(source, gate, driveId, root) {
7455
+ if (!await gate.servesDrive(driveId)) return [];
7456
+ return source.getDescendants(driveId, root);
7457
+ }
7458
+ /** One page of nodes; empty when the drive is withheld. */
7459
+ async function listServedNodes(source, gate, driveId, parentFolder, paging, kind) {
7460
+ if (!await gate.servesDrive(driveId)) return {
7461
+ results: [],
7462
+ nextCursor: void 0,
7463
+ hasMore: false
7464
+ };
7465
+ const limit = paging?.limit ?? DEFAULT_LIMIT;
7466
+ const wanted = !kind ? void 0 : kind === "FILE" ? "file" : "folder";
7467
+ const page = await source.listChildren(driveId, parentFolder, {
7468
+ cursor: paging?.cursor ?? "",
7469
+ limit
7470
+ }, void 0, wanted);
7471
+ return {
7472
+ results: page.results,
7473
+ nextCursor: page.nextCursor,
7474
+ hasMore: page.nextCursor !== void 0
7475
+ };
7476
+ }
7477
+ //#endregion
7214
7478
  //#region src/graphql/reactor/pubsub.ts
7215
7479
  const pubSub = new PubSub();
7216
7480
  function getPubSub() {
@@ -7230,11 +7494,11 @@ function subjectKey(subject) {
7230
7494
  * would gate every subscriber as the host.
7231
7495
  */
7232
7496
  var DocumentChangeFeed = class {
7233
- reactorClient;
7497
+ read;
7234
7498
  #pubSub = new PubSub();
7235
7499
  #feeds = /* @__PURE__ */ new Map();
7236
- constructor(reactorClient) {
7237
- this.reactorClient = reactorClient;
7500
+ constructor(read) {
7501
+ this.read = read;
7238
7502
  }
7239
7503
  subscribe(subject) {
7240
7504
  const key = subjectKey(subject);
@@ -7270,7 +7534,7 @@ var DocumentChangeFeed = class {
7270
7534
  return;
7271
7535
  }
7272
7536
  const view = { subject };
7273
- const unsubscribe = this.reactorClient.subscribe({}, (event) => {
7537
+ const unsubscribe = this.read.subscribe({}, (event) => {
7274
7538
  const payload = {
7275
7539
  documentChanges: event,
7276
7540
  search: {},
@@ -7294,14 +7558,14 @@ var DocumentChangeFeed = class {
7294
7558
  }
7295
7559
  };
7296
7560
  const activeJobSubscriptions = /* @__PURE__ */ new Map();
7297
- function ensureJobSubscription(reactorClient, jobId) {
7561
+ function ensureJobSubscription(read, jobId) {
7298
7562
  let subscription = activeJobSubscriptions.get(jobId);
7299
7563
  if (!subscription) {
7300
7564
  let isCancelled = false;
7301
7565
  let timeoutId;
7302
7566
  const poll = async () => {
7303
7567
  if (isCancelled) return;
7304
- const jobInfo = await reactorClient.getJobStatus(jobId);
7568
+ const jobInfo = await read.getJobStatus(jobId);
7305
7569
  const payload = {
7306
7570
  jobChanges: {
7307
7571
  jobId: jobInfo.id,
@@ -7357,9 +7621,11 @@ var ReactorSubgraph = class extends BaseSubgraph {
7357
7621
  }
7358
7622
  name = "r";
7359
7623
  hasSubscriptions = true;
7624
+ /** See {@link resolvers.WRITE_SIDE_QUERIES}. */
7625
+ writeSideQueries = WRITE_CLIENT_QUERIES.map((field) => `Query.${field}`);
7360
7626
  #documentChanges;
7361
7627
  get documentChanges() {
7362
- this.#documentChanges ??= new DocumentChangeFeed(this.reactorClient);
7628
+ this.#documentChanges ??= new DocumentChangeFeed(this.readClient);
7363
7629
  return this.#documentChanges;
7364
7630
  }
7365
7631
  /**
@@ -7377,15 +7643,29 @@ var ReactorSubgraph = class extends BaseSubgraph {
7377
7643
  return handle;
7378
7644
  }
7379
7645
  /**
7646
+ * The read gate a drive node read passes, as the reactor-drive subgraph
7647
+ * applies it: the drive is listed to the caller (reactor read gate, then the
7648
+ * host's ACL); its nodes are then served as the legacy node list was.
7649
+ */
7650
+ #driveNodeGate(ctx) {
7651
+ return { servesDrive: async (driveId) => {
7652
+ try {
7653
+ return await this.listsDocument(driveId, ctx);
7654
+ } catch {
7655
+ return false;
7656
+ }
7657
+ } };
7658
+ }
7659
+ /**
7380
7660
  * Returns the drive id when the given identifier (id or slug) refers
7381
7661
  * to a drive document, otherwise undefined. Used by deleteDocument to
7382
7662
  * decide whether to invalidate the drive-ownership cache after a
7383
7663
  * successful delete.
7384
7664
  */
7385
- async #resolveDriveId(identifier) {
7665
+ async #resolveDriveId(identifier, ctx) {
7386
7666
  try {
7387
- const doc = await this.reactorClient.get(identifier);
7388
- if (isDriveContainerType(doc.header.documentType)) return doc.header.id;
7667
+ const target = await this.clientsOf(ctx).write.describe(identifier);
7668
+ if (isDriveContainerType(target.documentType)) return target.documentId;
7389
7669
  return;
7390
7670
  } catch {
7391
7671
  return;
@@ -7483,6 +7763,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7483
7763
  }
7484
7764
  typeDefs = gql(schema_default$2);
7485
7765
  resolvers = {
7766
+ DriveNode: { __resolveType: (node) => driveNodeTypeName(node) },
7486
7767
  PHDocument: { operations: async (parent, args, ctx) => {
7487
7768
  this.logger.debug("PHDocument.operations(@parent.id, @args)", parent.id, args);
7488
7769
  await this.assertCanReadCanonical(parent.id, ctx);
@@ -7496,7 +7777,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7496
7777
  timestampFrom: args.filter?.timestampFrom,
7497
7778
  timestampTo: args.filter?.timestampTo
7498
7779
  };
7499
- return await documentOperations(this.reactorClient, {
7780
+ return await documentOperations(this.clientsOf(ctx).read, {
7500
7781
  filter,
7501
7782
  paging: args.paging
7502
7783
  }, this.viewSubject(ctx));
@@ -7506,10 +7787,10 @@ var ReactorSubgraph = class extends BaseSubgraph {
7506
7787
  }
7507
7788
  } },
7508
7789
  Query: {
7509
- documentModels: async (_parent, args) => {
7790
+ documentModels: async (_parent, args, ctx) => {
7510
7791
  this.logger.debug("documentModels(@args)", args);
7511
7792
  try {
7512
- return await documentModels(this.reactorClient, args);
7793
+ return await documentModels(this.clientsOf(ctx).read, args);
7513
7794
  } catch (error) {
7514
7795
  this.logger.error("Error in documentModels: @Error", error);
7515
7796
  throw error;
@@ -7520,9 +7801,10 @@ var ReactorSubgraph = class extends BaseSubgraph {
7520
7801
  try {
7521
7802
  const idOrSlug = requireOneOf(args, "idOrSlug", "identifier");
7522
7803
  const handle = await this.assertCanRead(idOrSlug, ctx);
7523
- return await document(this.reactorClient, {
7804
+ return await document(this.clientsOf(ctx).read, {
7524
7805
  idOrSlug: handle.fetchIdentifier,
7525
- view: args.view
7806
+ view: args.view,
7807
+ consistency: args.consistency
7526
7808
  }, this.viewSubject(ctx));
7527
7809
  } catch (error) {
7528
7810
  this.logger.error("Error in document: @Error", error);
@@ -7534,11 +7816,12 @@ var ReactorSubgraph = class extends BaseSubgraph {
7534
7816
  try {
7535
7817
  const sourceIdOrSlug = requireOneOf(args, "sourceIdOrSlug", "sourceIdentifier");
7536
7818
  const handle = await this.assertCanRead(sourceIdOrSlug, ctx);
7537
- return await documentOutgoingRelationships(this.reactorClient, {
7819
+ return await documentOutgoingRelationships(this.clientsOf(ctx).read, {
7538
7820
  sourceIdOrSlug: handle.fetchIdentifier,
7539
7821
  relationshipType: args.relationshipType,
7540
7822
  view: args.view,
7541
- paging: args.paging
7823
+ paging: args.paging,
7824
+ consistency: args.consistency
7542
7825
  }, this.viewSubject(ctx));
7543
7826
  } catch (error) {
7544
7827
  this.logger.error("Error in documentOutgoingRelationships: @Error", error);
@@ -7550,11 +7833,12 @@ var ReactorSubgraph = class extends BaseSubgraph {
7550
7833
  try {
7551
7834
  const targetIdOrSlug = requireOneOf(args, "targetIdOrSlug", "targetIdentifier");
7552
7835
  const handle = await this.assertCanRead(targetIdOrSlug, ctx);
7553
- const result = await documentIncomingRelationships(this.reactorClient, {
7836
+ const result = await documentIncomingRelationships(this.clientsOf(ctx).read, {
7554
7837
  targetIdOrSlug: handle.fetchIdentifier,
7555
7838
  relationshipType: args.relationshipType,
7556
7839
  view: args.view,
7557
- paging: args.paging
7840
+ paging: args.paging,
7841
+ consistency: args.consistency
7558
7842
  }, this.viewSubject(ctx));
7559
7843
  return {
7560
7844
  ...result,
@@ -7570,11 +7854,12 @@ var ReactorSubgraph = class extends BaseSubgraph {
7570
7854
  try {
7571
7855
  const sourceIdOrSlug = requireOneOf(args, "sourceIdOrSlug", "sourceIdentifier");
7572
7856
  const handle = await this.assertCanRead(sourceIdOrSlug, ctx);
7573
- const result = await documentOutgoingRelationshipEdges(this.reactorClient, {
7857
+ const result = await documentOutgoingRelationshipEdges(this.clientsOf(ctx).read, {
7574
7858
  sourceIdOrSlug: handle.fetchIdentifier,
7575
7859
  relationshipType: args.relationshipType,
7576
7860
  view: args.view,
7577
- paging: args.paging
7861
+ paging: args.paging,
7862
+ consistency: args.consistency
7578
7863
  }, this.viewSubject(ctx));
7579
7864
  return await this.filterRelationshipEdges(result, "targetId", ctx);
7580
7865
  } catch (error) {
@@ -7587,11 +7872,12 @@ var ReactorSubgraph = class extends BaseSubgraph {
7587
7872
  try {
7588
7873
  const targetIdOrSlug = requireOneOf(args, "targetIdOrSlug", "targetIdentifier");
7589
7874
  const handle = await this.assertCanRead(targetIdOrSlug, ctx);
7590
- const result = await documentIncomingRelationshipEdges(this.reactorClient, {
7875
+ const result = await documentIncomingRelationshipEdges(this.clientsOf(ctx).read, {
7591
7876
  targetIdOrSlug: handle.fetchIdentifier,
7592
7877
  relationshipType: args.relationshipType,
7593
7878
  view: args.view,
7594
- paging: args.paging
7879
+ paging: args.paging,
7880
+ consistency: args.consistency
7595
7881
  }, this.viewSubject(ctx));
7596
7882
  return await this.filterRelationshipEdges(result, "sourceId", ctx);
7597
7883
  } catch (error) {
@@ -7602,7 +7888,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7602
7888
  findDocuments: async (_parent, args, ctx) => {
7603
7889
  this.logger.debug("findDocuments(@args)", args);
7604
7890
  try {
7605
- const result = await findDocuments(this.reactorClient, {
7891
+ const result = await findDocuments(this.clientsOf(ctx).read, {
7606
7892
  ...args,
7607
7893
  search: args.search ?? {}
7608
7894
  }, this.viewSubject(ctx));
@@ -7628,7 +7914,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7628
7914
  }
7629
7915
  return decision;
7630
7916
  };
7631
- return await jobStatus(this.reactorClient, args, readable, readable);
7917
+ return await jobStatus(this.clientsOf(ctx).read, args, readable, readable);
7632
7918
  } catch (error) {
7633
7919
  this.logger.error("Error in jobStatus: @Error", error);
7634
7920
  throw error;
@@ -7646,12 +7932,24 @@ var ReactorSubgraph = class extends BaseSubgraph {
7646
7932
  throw error;
7647
7933
  }
7648
7934
  },
7935
+ driveNodes: async (_parent, args, ctx) => {
7936
+ this.logger.debug("driveNodes(@args)", args);
7937
+ return listServedNodes(requireDriveNodeSource(this.graphqlManager.driveNodes), this.#driveNodeGate(ctx), args.driveId, "parentFolder" in args ? args.parentFolder ?? null : void 0, args.paging, args.kind);
7938
+ },
7939
+ driveNode: async (_parent, args, ctx) => {
7940
+ this.logger.debug("driveNode(@args)", args);
7941
+ return await getServedNode(requireDriveNodeSource(this.graphqlManager.driveNodes), this.#driveNodeGate(ctx), args.driveId, args.id) ?? null;
7942
+ },
7943
+ driveDescendants: async (_parent, args, ctx) => {
7944
+ this.logger.debug("driveDescendants(@args)", args);
7945
+ return getServedDescendants(requireDriveNodeSource(this.graphqlManager.driveNodes), this.#driveNodeGate(ctx), args.driveId, args.root);
7946
+ },
7649
7947
  createDefaults: async (_parent, args, ctx) => {
7650
7948
  this.logger.debug("createDefaults(@args)", args);
7651
7949
  try {
7652
7950
  const parentIdOrSlug = args.parentIdOrSlug ?? void 0;
7653
7951
  if (parentIdOrSlug !== void 0 && !await this.listsDocument(parentIdOrSlug, ctx)) throw new ForbiddenError("to read this document");
7654
- return await createDefaults(this.reactorClient, parentIdOrSlug);
7952
+ return await createDefaults(this.clientsOf(ctx).read, parentIdOrSlug);
7655
7953
  } catch (error) {
7656
7954
  this.logger.error("Error in createDefaults: @Error", error);
7657
7955
  throw error;
@@ -7665,7 +7963,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7665
7963
  documentIdOrSlug,
7666
7964
  documentId
7667
7965
  }, "documentIdOrSlug", "documentId"), ctx);
7668
- return await documentOperations(this.reactorClient, {
7966
+ return await documentOperations(this.clientsOf(ctx).read, {
7669
7967
  filter: {
7670
7968
  ...filter,
7671
7969
  documentIdOrSlug: handle.fetchIdentifier
@@ -7689,7 +7987,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7689
7987
  try {
7690
7988
  const documentIdOrSlug = requireOneOf(args, "documentIdOrSlug", "documentIdentifier");
7691
7989
  const handle = await this.assertCanRead(documentIdOrSlug, ctx);
7692
- return await evaluateActions(this.reactorClient, {
7990
+ return await evaluateActions(this.clientsOf(ctx).write, {
7693
7991
  documentIdOrSlug: handle.fetchIdentifier,
7694
7992
  branch: args.branch,
7695
7993
  candidates: args.candidates
@@ -7754,10 +8052,10 @@ var ReactorSubgraph = class extends BaseSubgraph {
7754
8052
  try {
7755
8053
  const parentIdOrSlug = optionalOneOf(args, "parentIdOrSlug", "parentIdentifier");
7756
8054
  if (parentIdOrSlug) {
7757
- const parent = await document(this.reactorClient, { idOrSlug: parentIdOrSlug });
8055
+ const parent = await document(this.clientsOf(ctx).read, { idOrSlug: parentIdOrSlug });
7758
8056
  await this.assertCanWriteCanonical(parent.document.id, ctx);
7759
8057
  } else this.assertCanCreate(ctx);
7760
- const result = await createDocument(this.reactorClient, {
8058
+ const result = await createDocument(this.clientsOf(ctx), {
7761
8059
  document: args.document,
7762
8060
  parentIdOrSlug
7763
8061
  }, this.graphqlManager.reactorDriveClient, this.viewSubject(ctx));
@@ -7774,10 +8072,10 @@ var ReactorSubgraph = class extends BaseSubgraph {
7774
8072
  try {
7775
8073
  const parentIdOrSlug = optionalOneOf(args, "parentIdOrSlug", "parentIdentifier");
7776
8074
  if (parentIdOrSlug) {
7777
- const parent = await document(this.reactorClient, { idOrSlug: parentIdOrSlug });
8075
+ const parent = await document(this.clientsOf(ctx).read, { idOrSlug: parentIdOrSlug });
7778
8076
  await this.assertCanWriteCanonical(parent.document.id, ctx);
7779
8077
  } else this.assertCanCreate(ctx);
7780
- const result = await createEmptyDocument(this.reactorClient, {
8078
+ const result = await createEmptyDocument(this.clientsOf(ctx), {
7781
8079
  documentType: args.documentType,
7782
8080
  parentIdOrSlug
7783
8081
  }, this.graphqlManager.reactorDriveClient, this.viewSubject(ctx));
@@ -7794,7 +8092,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7794
8092
  try {
7795
8093
  const documentIdOrSlug = requireOneOf(args, "documentIdOrSlug", "documentIdentifier");
7796
8094
  const handle = await this.assertCanExecuteOperations(documentIdOrSlug, args.actions, ctx);
7797
- return await execute(this.reactorClient, {
8095
+ return await execute(this.clientsOf(ctx), {
7798
8096
  documentIdOrSlug: handle.fetchIdentifier,
7799
8097
  actions: args.actions,
7800
8098
  branch: args.branch
@@ -7809,7 +8107,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7809
8107
  try {
7810
8108
  const documentIdOrSlug = requireOneOf(args, "documentIdOrSlug", "documentIdentifier");
7811
8109
  const handle = await this.assertCanExecuteOperations(documentIdOrSlug, args.actions, ctx);
7812
- return await executeAsync(this.reactorClient, {
8110
+ return await executeAsync(this.clientsOf(ctx), {
7813
8111
  documentIdOrSlug: handle.fetchIdentifier,
7814
8112
  actions: args.actions,
7815
8113
  branch: args.branch
@@ -7826,7 +8124,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7826
8124
  if (creation) {
7827
8125
  if (creation.linkedFrom.length > 0) for (const parent of creation.linkedFrom) await this.assertCanWrite(parent, ctx);
7828
8126
  else this.assertCanCreate(ctx);
7829
- const result = await executeBatch(this.reactorClient, { jobs: args.jobs });
8127
+ const result = await executeBatch(this.clientsOf(ctx).write, { jobs: args.jobs });
7830
8128
  if (result.jobs.some((entry) => entry.job.status !== "READ_READY")) return result;
7831
8129
  if (isDriveContainerType(creation.documentType)) this.graphqlManager.driveOwnershipCache.add(creation.documentId);
7832
8130
  if (ctx.user?.address) await this.documentPermissionService?.initializeDocumentProtection(creation.documentId, ctx.user.address, this.authorizationService.config.defaultProtection);
@@ -7840,7 +8138,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7840
8138
  documentIdOrSlug: handle.fetchIdentifier
7841
8139
  });
7842
8140
  }
7843
- return await executeBatch(this.reactorClient, { jobs });
8141
+ return await executeBatch(this.clientsOf(ctx).write, { jobs });
7844
8142
  } catch (error) {
7845
8143
  this.logger.error("Error in executeBatch(@args): @Error", args, error);
7846
8144
  throw error;
@@ -7850,7 +8148,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7850
8148
  this.logger.debug("mutateDocument(@args)", args);
7851
8149
  try {
7852
8150
  const handle = await this.assertCanExecuteOperations(args.documentIdentifier, args.actions, ctx);
7853
- return await mutateDocument(this.reactorClient, {
8151
+ return await mutateDocument(this.clientsOf(ctx), {
7854
8152
  ...args,
7855
8153
  documentIdentifier: handle.fetchIdentifier
7856
8154
  }, this.viewSubject(ctx));
@@ -7863,7 +8161,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7863
8161
  this.logger.debug("mutateDocumentAsync(@args)", args);
7864
8162
  try {
7865
8163
  const handle = await this.assertCanExecuteOperations(args.documentIdentifier, args.actions, ctx);
7866
- return await mutateDocumentAsync(this.reactorClient, {
8164
+ return await mutateDocumentAsync(this.clientsOf(ctx).write, {
7867
8165
  ...args,
7868
8166
  documentIdentifier: handle.fetchIdentifier
7869
8167
  });
@@ -7877,7 +8175,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7877
8175
  try {
7878
8176
  const documentIdOrSlug = requireOneOf(args, "documentIdOrSlug", "documentIdentifier");
7879
8177
  const handle = await this.assertCanWrite(documentIdOrSlug, ctx);
7880
- return await renameDocument(this.reactorClient, {
8178
+ return await renameDocument(this.clientsOf(ctx), {
7881
8179
  documentIdOrSlug: handle.fetchIdentifier,
7882
8180
  name: args.name,
7883
8181
  branch: args.branch
@@ -7892,7 +8190,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7892
8190
  try {
7893
8191
  const documentIdOrSlug = requireOneOf(args, "documentIdOrSlug", "documentIdentifier");
7894
8192
  const handle = await this.assertCanWrite(documentIdOrSlug, ctx);
7895
- return await setPreferredEditor(this.reactorClient, {
8193
+ return await setPreferredEditor(this.clientsOf(ctx), {
7896
8194
  documentIdOrSlug: handle.fetchIdentifier,
7897
8195
  preferredEditor: args.preferredEditor,
7898
8196
  branch: args.branch
@@ -7908,7 +8206,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7908
8206
  const sourceIdOrSlug = requireOneOf(args, "sourceIdOrSlug", "sourceIdentifier");
7909
8207
  const targetIdOrSlug = requireOneOf(args, "targetIdOrSlug", "targetIdentifier");
7910
8208
  const handle = await this.assertCanWrite(sourceIdOrSlug, ctx);
7911
- return await addRelationship(this.reactorClient, {
8209
+ return await addRelationship(this.clientsOf(ctx), {
7912
8210
  sourceIdOrSlug: handle.fetchIdentifier,
7913
8211
  targetIdOrSlug,
7914
8212
  relationshipType: args.relationshipType,
@@ -7926,7 +8224,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7926
8224
  const sourceIdOrSlug = requireOneOf(args, "sourceIdOrSlug", "sourceIdentifier");
7927
8225
  const targetIdOrSlug = requireOneOf(args, "targetIdOrSlug", "targetIdentifier");
7928
8226
  const handle = await this.assertCanWrite(sourceIdOrSlug, ctx);
7929
- return await updateRelationship(this.reactorClient, {
8227
+ return await updateRelationship(this.clientsOf(ctx), {
7930
8228
  sourceIdOrSlug: handle.fetchIdentifier,
7931
8229
  targetIdOrSlug,
7932
8230
  relationshipType: args.relationshipType,
@@ -7944,7 +8242,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7944
8242
  const sourceIdOrSlug = requireOneOf(args, "sourceIdOrSlug", "sourceIdentifier");
7945
8243
  const targetIdOrSlug = requireOneOf(args, "targetIdOrSlug", "targetIdentifier");
7946
8244
  const handle = await this.assertCanWrite(sourceIdOrSlug, ctx);
7947
- return await removeRelationship(this.reactorClient, {
8245
+ return await removeRelationship(this.clientsOf(ctx), {
7948
8246
  sourceIdOrSlug: handle.fetchIdentifier,
7949
8247
  targetIdOrSlug,
7950
8248
  relationshipType: args.relationshipType,
@@ -7963,7 +8261,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7963
8261
  const targetIdOrSlug = requireOneOf(args, "targetIdOrSlug", "targetIdentifier");
7964
8262
  const sourceHandle = await this.assertCanWrite(sourceParentIdOrSlug, ctx);
7965
8263
  const targetHandle = await this.assertCanWrite(targetParentIdOrSlug, ctx);
7966
- return await moveRelationship(this.reactorClient, {
8264
+ return await moveRelationship(this.clientsOf(ctx), {
7967
8265
  sourceParentIdOrSlug: sourceHandle.fetchIdentifier,
7968
8266
  targetParentIdOrSlug: targetHandle.fetchIdentifier,
7969
8267
  targetIdOrSlug,
@@ -7979,8 +8277,8 @@ var ReactorSubgraph = class extends BaseSubgraph {
7979
8277
  this.logger.debug("deleteDocument(@args)", args);
7980
8278
  try {
7981
8279
  const idOrSlug = (await this.assertCanWrite(requireOneOf(args, "idOrSlug", "identifier"), ctx)).fetchIdentifier;
7982
- const driveIdToInvalidate = await this.#resolveDriveId(idOrSlug);
7983
- const result = await deleteDocument(this.reactorClient, {
8280
+ const driveIdToInvalidate = await this.#resolveDriveId(idOrSlug, ctx);
8281
+ const result = await deleteDocument(this.clientsOf(ctx), {
7984
8282
  idOrSlug,
7985
8283
  propagate: args.propagate
7986
8284
  }, this.graphqlManager.reactorDriveClient);
@@ -7999,7 +8297,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7999
8297
  const handle = await this.assertCanWrite(idOrSlug, ctx);
8000
8298
  idsOrSlugs.push(handle.fetchIdentifier);
8001
8299
  }
8002
- return await deleteDocuments(this.reactorClient, {
8300
+ return await deleteDocuments(this.clientsOf(ctx).write, {
8003
8301
  idsOrSlugs,
8004
8302
  propagate: args.propagate
8005
8303
  });
@@ -8102,7 +8400,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8102
8400
  subscribe: (rootValue, args, ctx, info) => {
8103
8401
  this.logger.debug("jobChanges(@args) subscription started", args);
8104
8402
  return withFilter(() => {
8105
- ensureJobSubscription(this.reactorClient, args.jobId);
8403
+ ensureJobSubscription(this.clientsOf(ctx).read, args.jobId);
8106
8404
  return getPubSub().asyncIterableIterator(SUBSCRIPTION_TRIGGERS.JOB_CHANGES);
8107
8405
  }, async (payload, filterArgs, filterCtx) => {
8108
8406
  if (!payload || !filterArgs) return false;
@@ -8136,10 +8434,10 @@ const ADMIN_USERS = getAdminUsers();
8136
8434
  //#endregion
8137
8435
  //#region src/graphql/system/version.ts
8138
8436
  function getVersion() {
8139
- return "6.2.3-dev.76";
8437
+ return "6.2.3-dev.78";
8140
8438
  }
8141
8439
  function getGitHash() {
8142
- return "52fc80c50826101cd373d62ff0ce6f97a3565a44";
8440
+ return "1c899a137d71c6be7e24a23bbe2163e07f2cc5a1";
8143
8441
  }
8144
8442
  function getGitUrl() {
8145
8443
  return buildTreeUrl(getGitHash());
@@ -9911,12 +10209,22 @@ var StaticMigrationProvider = class {
9911
10209
  }
9912
10210
  };
9913
10211
  /**
10212
+ * The schema unqualified names resolve to, where these migrations have always
10213
+ * kept their bookkeeping tables. Named explicitly because Kysely, given no
10214
+ * schema, treats a lock table in any schema (the attachment store creates
10215
+ * one in its own) as present and then fails to find it unqualified.
10216
+ */
10217
+ async function currentSchema(db) {
10218
+ return (await sql`select current_schema() as schema`.execute(db)).rows[0]?.schema ?? "public";
10219
+ }
10220
+ /**
9914
10221
  * Run all pending migrations
9915
10222
  */
9916
10223
  async function runMigrations(db) {
9917
10224
  const { error, results } = await new Migrator({
9918
10225
  db,
9919
- provider: new StaticMigrationProvider()
10226
+ provider: new StaticMigrationProvider(),
10227
+ migrationTableSchema: await currentSchema(db)
9920
10228
  }).migrateToLatest();
9921
10229
  results?.forEach((result) => {
9922
10230
  if (result.status === "Error") console.error(`Failed to execute migration "${result.migrationName}"`);
@@ -10028,6 +10336,122 @@ async function createRenownCredentialVerifier(config = {}) {
10028
10336
  };
10029
10337
  }
10030
10338
  //#endregion
10339
+ //#region src/services/permission-cache.ts
10340
+ /**
10341
+ * Everything an authorization decision reads about one document: its
10342
+ * protection flag (the configured default when it has no protection row), its
10343
+ * owner, the users' grant levels and the users granted each operation.
10344
+ * Addresses are stored lowercase, as the permission service writes them.
10345
+ */
10346
+ var DocumentPermissionSnapshot = class {
10347
+ documentId;
10348
+ isProtected;
10349
+ ownerAddress;
10350
+ grants;
10351
+ operationGrants;
10352
+ constructor(documentId, isProtected, ownerAddress, grants, operationGrants) {
10353
+ this.documentId = documentId;
10354
+ this.isProtected = isProtected;
10355
+ this.ownerAddress = ownerAddress;
10356
+ this.grants = grants;
10357
+ this.operationGrants = operationGrants;
10358
+ }
10359
+ grantLevel(userAddress) {
10360
+ return this.grants.get(userAddress.toLowerCase()) ?? null;
10361
+ }
10362
+ isOperationRestricted(operationType) {
10363
+ return (this.operationGrants.get(operationType)?.size ?? 0) > 0;
10364
+ }
10365
+ hasOperationGrant(operationType, userAddress) {
10366
+ return this.operationGrants.get(operationType)?.has(userAddress.toLowerCase()) ?? false;
10367
+ }
10368
+ };
10369
+ const DEFAULT_PERMISSION_CACHE_TTL_MS = 3e4;
10370
+ const DEFAULT_PERMISSION_CACHE_OPTIONS = {
10371
+ ttlMs: DEFAULT_PERMISSION_CACHE_TTL_MS,
10372
+ maxEntries: 1e4,
10373
+ now: () => Date.now()
10374
+ };
10375
+ var PermissionCacheEntry = class {
10376
+ snapshot;
10377
+ expiresAt;
10378
+ constructor(snapshot, expiresAt) {
10379
+ this.snapshot = snapshot;
10380
+ this.expiresAt = expiresAt;
10381
+ }
10382
+ };
10383
+ /**
10384
+ * Per-process cache of document permission snapshots, keyed by document id.
10385
+ *
10386
+ * Filled on miss from the store, invalidated by the permission service after
10387
+ * each of its own writes, and expired after `ttlMs` as the safety net for
10388
+ * writes made by another process (another switchboard instance on the same
10389
+ * database) until cross-instance invalidation exists.
10390
+ *
10391
+ * A load that overlaps an invalidation still answers its caller but is not
10392
+ * stored, so a read that started before a write commits cannot repopulate
10393
+ * the cache with the pre-write rows.
10394
+ */
10395
+ var PermissionCache = class {
10396
+ #load;
10397
+ #options;
10398
+ #entries = /* @__PURE__ */ new Map();
10399
+ #epoch = 0;
10400
+ constructor(load, options = DEFAULT_PERMISSION_CACHE_OPTIONS) {
10401
+ this.#load = load;
10402
+ this.#options = options;
10403
+ }
10404
+ get size() {
10405
+ return this.#entries.size;
10406
+ }
10407
+ async get(documentId) {
10408
+ return (await this.getMany([documentId])).get(documentId);
10409
+ }
10410
+ /** Snapshots for every id, loading the missing and expired ones in one batch. */
10411
+ async getMany(documentIds) {
10412
+ const now = this.#options.now();
10413
+ const result = /* @__PURE__ */ new Map();
10414
+ const missing = [];
10415
+ for (const documentId of new Set(documentIds)) {
10416
+ const entry = this.#entries.get(documentId);
10417
+ if (entry && entry.expiresAt > now) {
10418
+ this.#entries.delete(documentId);
10419
+ this.#entries.set(documentId, entry);
10420
+ result.set(documentId, entry.snapshot);
10421
+ } else missing.push(documentId);
10422
+ }
10423
+ if (missing.length === 0) return result;
10424
+ const epoch = this.#epoch;
10425
+ const loaded = await this.#load(missing);
10426
+ const storable = this.#options.ttlMs > 0 && epoch === this.#epoch;
10427
+ const expiresAt = this.#options.now() + this.#options.ttlMs;
10428
+ for (const documentId of missing) {
10429
+ const snapshot = loaded.get(documentId);
10430
+ if (!snapshot) throw new Error(`Permission snapshot loader returned no snapshot for ${documentId}`);
10431
+ result.set(documentId, snapshot);
10432
+ if (storable) this.#store(documentId, new PermissionCacheEntry(snapshot, expiresAt));
10433
+ }
10434
+ return result;
10435
+ }
10436
+ invalidate(documentId) {
10437
+ this.#epoch++;
10438
+ this.#entries.delete(documentId);
10439
+ }
10440
+ clear() {
10441
+ this.#epoch++;
10442
+ this.#entries.clear();
10443
+ }
10444
+ #store(documentId, entry) {
10445
+ this.#entries.delete(documentId);
10446
+ while (this.#entries.size >= this.#options.maxEntries) {
10447
+ const oldest = this.#entries.keys().next();
10448
+ if (oldest.done) break;
10449
+ this.#entries.delete(oldest.value);
10450
+ }
10451
+ this.#entries.set(documentId, entry);
10452
+ }
10453
+ };
10454
+ //#endregion
10031
10455
  //#region src/services/document-permission.service.ts
10032
10456
  /**
10033
10457
  * Service for managing document-level permissions.
@@ -10043,16 +10467,23 @@ async function createRenownCredentialVerifier(config = {}) {
10043
10467
  var DocumentPermissionService = class {
10044
10468
  db;
10045
10469
  config;
10046
- constructor(db, config = { defaultProtection: false }) {
10470
+ /**
10471
+ * Serves the reads authorization decisions make (protection, owner, grant
10472
+ * level, operation grants). Every write through this service invalidates
10473
+ * the document it touched.
10474
+ */
10475
+ permissionCache;
10476
+ constructor(db, config = { defaultProtection: false }, cacheOptions = DEFAULT_PERMISSION_CACHE_OPTIONS) {
10047
10477
  this.db = db;
10048
10478
  this.config = config;
10479
+ this.permissionCache = new PermissionCache((documentIds) => this.loadPermissionSnapshots(documentIds), cacheOptions);
10049
10480
  }
10050
10481
  /**
10051
10482
  * Get the permission level for a user on a specific document.
10052
10483
  * Returns null if no permission is set.
10053
10484
  */
10054
10485
  async getUserPermission(documentId, userAddress) {
10055
- return (await this.db.selectFrom("DocumentPermission").select("permission").where("documentId", "=", documentId).where("userAddress", "=", userAddress.toLowerCase()).executeTakeFirst())?.permission ?? null;
10486
+ return (await this.permissionCache.get(documentId)).grantLevel(userAddress);
10056
10487
  }
10057
10488
  /**
10058
10489
  * Get all permissions for a document
@@ -10097,7 +10528,7 @@ var DocumentPermissionService = class {
10097
10528
  permission,
10098
10529
  grantedBy: grantedBy.toLowerCase(),
10099
10530
  updatedAt: now
10100
- })).execute();
10531
+ })).execute().finally(() => this.permissionCache.invalidate(documentId));
10101
10532
  return await this.db.selectFrom("DocumentPermission").select([
10102
10533
  "documentId",
10103
10534
  "userAddress",
@@ -10111,14 +10542,14 @@ var DocumentPermissionService = class {
10111
10542
  * Revoke a user's permission on a document
10112
10543
  */
10113
10544
  async revokePermission(documentId, userAddress) {
10114
- await this.db.deleteFrom("DocumentPermission").where("documentId", "=", documentId).where("userAddress", "=", userAddress.toLowerCase()).execute();
10545
+ await this.db.deleteFrom("DocumentPermission").where("documentId", "=", documentId).where("userAddress", "=", userAddress.toLowerCase()).execute().finally(() => this.permissionCache.invalidate(documentId));
10115
10546
  }
10116
10547
  /**
10117
10548
  * Delete all permissions for a document (used when deleting a document)
10118
10549
  */
10119
10550
  async deleteAllDocumentPermissions(documentId) {
10120
- const permissions = await this.db.deleteFrom("DocumentPermission").where("documentId", "=", documentId).returning("id").execute();
10121
- const operations = await this.db.deleteFrom("OperationUserPermission").where("documentId", "=", documentId).returning("id").execute();
10551
+ const permissions = await this.db.deleteFrom("DocumentPermission").where("documentId", "=", documentId).returning("id").execute().finally(() => this.permissionCache.invalidate(documentId));
10552
+ const operations = await this.db.deleteFrom("OperationUserPermission").where("documentId", "=", documentId).returning("id").execute().finally(() => this.permissionCache.invalidate(documentId));
10122
10553
  return {
10123
10554
  DocumentPermission: permissions.length,
10124
10555
  OperationUserPermission: operations.length
@@ -10126,7 +10557,7 @@ var DocumentPermissionService = class {
10126
10557
  }
10127
10558
  /** Delete a document's protection row, which names its owner. */
10128
10559
  async deleteDocumentProtection(documentId) {
10129
- return (await this.db.deleteFrom("DocumentProtection").where("documentId", "=", documentId).returning("documentId").execute()).length;
10560
+ return (await this.db.deleteFrom("DocumentProtection").where("documentId", "=", documentId).returning("documentId").execute().finally(() => this.permissionCache.invalidate(documentId))).length;
10130
10561
  }
10131
10562
  /** Every row that names the address, for a subject access request. */
10132
10563
  async rowsForAddress(address) {
@@ -10166,7 +10597,7 @@ var DocumentPermissionService = class {
10166
10597
  "documentId",
10167
10598
  "operationType",
10168
10599
  "userAddress"
10169
- ]).doNothing()).execute();
10600
+ ]).doNothing()).execute().finally(() => this.permissionCache.invalidate(documentId));
10170
10601
  return await this.db.selectFrom("OperationUserPermission").select([
10171
10602
  "documentId",
10172
10603
  "operationType",
@@ -10179,7 +10610,7 @@ var DocumentPermissionService = class {
10179
10610
  * Revoke a user's permission to execute an operation
10180
10611
  */
10181
10612
  async revokeOperationPermission(documentId, operationType, userAddress) {
10182
- await this.db.deleteFrom("OperationUserPermission").where("documentId", "=", documentId).where("operationType", "=", operationType).where("userAddress", "=", userAddress.toLowerCase()).execute();
10613
+ await this.db.deleteFrom("OperationUserPermission").where("documentId", "=", documentId).where("operationType", "=", operationType).where("userAddress", "=", userAddress.toLowerCase()).execute().finally(() => this.permissionCache.invalidate(documentId));
10183
10614
  }
10184
10615
  /**
10185
10616
  * Get all users with permission to execute an operation
@@ -10197,24 +10628,20 @@ var DocumentPermissionService = class {
10197
10628
  * Whether an operation-permission row exists for the user on this operation.
10198
10629
  */
10199
10630
  async hasOperationGrant(documentId, operationType, userAddress) {
10200
- const normalizedAddress = userAddress.toLowerCase();
10201
- return !!await this.db.selectFrom("OperationUserPermission").select("userAddress").where("documentId", "=", documentId).where("operationType", "=", operationType).where("userAddress", "=", normalizedAddress).executeTakeFirst();
10631
+ return (await this.permissionCache.get(documentId)).hasOperationGrant(operationType, userAddress);
10202
10632
  }
10203
10633
  /**
10204
10634
  * Check if an operation has any permissions set (is restricted)
10205
10635
  */
10206
10636
  async isOperationRestricted(documentId, operationType) {
10207
- const userPermCount = await this.db.selectFrom("OperationUserPermission").select(sql`count(*)`.as("count")).where("documentId", "=", documentId).where("operationType", "=", operationType).executeTakeFirst();
10208
- return userPermCount !== void 0 && Number(userPermCount.count) > 0;
10637
+ return (await this.permissionCache.get(documentId)).isOperationRestricted(operationType);
10209
10638
  }
10210
10639
  /**
10211
10640
  * Check if a specific document has a protection row set to true.
10212
10641
  * Falls back to `config.defaultProtection` if no row exists.
10213
10642
  */
10214
10643
  async isDocumentProtected(documentId) {
10215
- const row = await this.db.selectFrom("DocumentProtection").select("protected").where("documentId", "=", documentId).executeTakeFirst();
10216
- if (row === void 0) return this.config.defaultProtection;
10217
- return row.protected;
10644
+ return (await this.permissionCache.get(documentId)).isProtected;
10218
10645
  }
10219
10646
  /**
10220
10647
  * Walk the parent chain: if the document itself or any ancestor is protected, return true.
@@ -10223,12 +10650,62 @@ var DocumentPermissionService = class {
10223
10650
  async isProtectedWithAncestors(documentId, getParentIds) {
10224
10651
  const allIds = await this.collectAncestorIds(documentId, getParentIds);
10225
10652
  if (allIds.length === 0) return this.config.defaultProtection;
10226
- const rows = await this.db.selectFrom("DocumentProtection").select(["documentId", "protected"]).where("documentId", "in", allIds).execute();
10227
- const protectionMap = new Map(rows.map((r) => [r.documentId, r.protected]));
10228
- for (const id of allIds) if (protectionMap.get(id) ?? this.config.defaultProtection) return true;
10653
+ const snapshots = await this.permissionCache.getMany(allIds);
10654
+ for (const snapshot of snapshots.values()) if (snapshot.isProtected) return true;
10229
10655
  return false;
10230
10656
  }
10231
10657
  /**
10658
+ * Reads the permission rows of the given documents from the store, three
10659
+ * queries for the whole batch. The permission cache's loader.
10660
+ */
10661
+ async loadPermissionSnapshots(documentIds) {
10662
+ const protections = await this.db.selectFrom("DocumentProtection").select([
10663
+ "documentId",
10664
+ "protected",
10665
+ "ownerAddress"
10666
+ ]).where("documentId", "in", documentIds).execute();
10667
+ const grants = await this.db.selectFrom("DocumentPermission").select([
10668
+ "documentId",
10669
+ "userAddress",
10670
+ "permission"
10671
+ ]).where("documentId", "in", documentIds).execute();
10672
+ const operationGrants = await this.db.selectFrom("OperationUserPermission").select([
10673
+ "documentId",
10674
+ "operationType",
10675
+ "userAddress"
10676
+ ]).where("documentId", "in", documentIds).execute();
10677
+ const protectionById = new Map(protections.map((row) => [row.documentId, row]));
10678
+ const grantsById = /* @__PURE__ */ new Map();
10679
+ for (const row of grants) {
10680
+ let byUser = grantsById.get(row.documentId);
10681
+ if (!byUser) {
10682
+ byUser = /* @__PURE__ */ new Map();
10683
+ grantsById.set(row.documentId, byUser);
10684
+ }
10685
+ byUser.set(row.userAddress, row.permission);
10686
+ }
10687
+ const operationsById = /* @__PURE__ */ new Map();
10688
+ for (const row of operationGrants) {
10689
+ let byOperation = operationsById.get(row.documentId);
10690
+ if (!byOperation) {
10691
+ byOperation = /* @__PURE__ */ new Map();
10692
+ operationsById.set(row.documentId, byOperation);
10693
+ }
10694
+ let users = byOperation.get(row.operationType);
10695
+ if (!users) {
10696
+ users = /* @__PURE__ */ new Set();
10697
+ byOperation.set(row.operationType, users);
10698
+ }
10699
+ users.add(row.userAddress);
10700
+ }
10701
+ const snapshots = /* @__PURE__ */ new Map();
10702
+ for (const documentId of documentIds) {
10703
+ const protection = protectionById.get(documentId);
10704
+ snapshots.set(documentId, new DocumentPermissionSnapshot(documentId, protection?.protected ?? this.config.defaultProtection, protection?.ownerAddress ?? null, grantsById.get(documentId) ?? /* @__PURE__ */ new Map(), operationsById.get(documentId) ?? /* @__PURE__ */ new Map()));
10705
+ }
10706
+ return snapshots;
10707
+ }
10708
+ /**
10232
10709
  * Collect all ancestor IDs (including the document itself) with cycle detection.
10233
10710
  */
10234
10711
  async collectAncestorIds(documentId, getParentIds) {
@@ -10257,13 +10734,13 @@ var DocumentPermissionService = class {
10257
10734
  }).onConflict((oc) => oc.column("documentId").doUpdateSet({
10258
10735
  protected: isProtected,
10259
10736
  updatedAt: now
10260
- })).execute();
10737
+ })).execute().finally(() => this.permissionCache.invalidate(documentId));
10261
10738
  }
10262
10739
  /**
10263
10740
  * Get the owner address for a document, or null if not set.
10264
10741
  */
10265
10742
  async getDocumentOwner(documentId) {
10266
- return (await this.db.selectFrom("DocumentProtection").select("ownerAddress").where("documentId", "=", documentId).executeTakeFirst())?.ownerAddress ?? null;
10743
+ return (await this.permissionCache.get(documentId)).ownerAddress;
10267
10744
  }
10268
10745
  /**
10269
10746
  * Upsert owner address for a document.
@@ -10280,7 +10757,7 @@ var DocumentPermissionService = class {
10280
10757
  }).onConflict((oc) => oc.column("documentId").doUpdateSet({
10281
10758
  ownerAddress: normalizedAddress,
10282
10759
  updatedAt: now
10283
- })).execute();
10760
+ })).execute().finally(() => this.permissionCache.invalidate(documentId));
10284
10761
  }
10285
10762
  /**
10286
10763
  * Initialize protection for a newly created document.
@@ -10299,7 +10776,7 @@ var DocumentPermissionService = class {
10299
10776
  }).onConflict((oc) => oc.column("documentId").doUpdateSet({
10300
10777
  ownerAddress: normalizedAddress,
10301
10778
  updatedAt: now
10302
- })).execute();
10779
+ })).execute().finally(() => this.permissionCache.invalidate(documentId));
10303
10780
  await this.grantPermission(documentId, normalizedAddress, "ADMIN", normalizedAddress);
10304
10781
  }
10305
10782
  /**
@@ -10326,11 +10803,12 @@ var DocumentPermissionService = class {
10326
10803
  * a document's parents are the sources of its incoming "child"
10327
10804
  * relationships. Lookup failures resolve to "no parents" so a relationship
10328
10805
  * store outage degrades to no inherited permissions rather than an error.
10806
+ * Reads through the read half: the indexer it asks is post-commit, as it was.
10329
10807
  */
10330
- function createGetParentIdsFn(reactorClient) {
10808
+ function createGetParentIdsFn(read) {
10331
10809
  return async (documentId) => {
10332
10810
  try {
10333
- return (await reactorClient.getIncomingRelationships(documentId, "child")).results.map((doc) => doc.header.id);
10811
+ return (await read.getIncomingRelationships(documentId, "child")).results.map((doc) => doc.header.id);
10334
10812
  } catch {
10335
10813
  return [];
10336
10814
  }
@@ -10467,6 +10945,7 @@ function getDbClient(connectionString = void 0, pgliteFactory) {
10467
10945
  const pgliteInstance = isPg ? void 0 : pgliteFactory ? pgliteFactory(connectionString) : connectionString ? new PGlite({
10468
10946
  fs: createDurableNodeFs(NodeFS, connectionString, {
10469
10947
  fsync: resolvePgliteFsync(process.env),
10948
+ ...resolvePgliteMaintenance(process.env),
10470
10949
  logger
10471
10950
  }),
10472
10951
  parsers: PGLITE_UTC_PARSERS
@@ -10716,13 +11195,15 @@ function resolveGatewayAdapterType(logger) {
10716
11195
  /**
10717
11196
  * Sets up the subgraph manager and registers subgraphs
10718
11197
  */
10719
- async function setupGraphQLManager({ httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, httpServer, wsServer, client, relationalDb, analyticsStore, syncManager, subgraphs, logger, authorizationService, authService, documentPermissionService, enableDocumentModelSubgraphs, port, reactorDriveClient, syncServingGate, httpRoutes, attachments, inspection, driveStore, reportError }) {
11198
+ async function setupGraphQLManager({ httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, httpServer, wsServer, clients, relationalDb, analyticsStore, syncManager, subgraphs, logger, authorizationService, authService, documentPermissionService, enableDocumentModelSubgraphs, port, reactorDriveClient, driveNodes, syncServingGate, httpRoutes, attachments, inspection, driveStore, reportError }) {
10720
11199
  const graphqlManager = new GraphQLManager({
10721
11200
  wsCredentialRecheckIntervalMs: resolveWsCredentialRecheckIntervalMs(process.env.WS_CREDENTIAL_RECHECK_INTERVAL_MS, logger),
10722
11201
  path: config.basePath,
10723
11202
  httpServer,
10724
11203
  wsServer,
10725
- reactorClient: client,
11204
+ readClient: clients.read,
11205
+ writeClient: clients.write,
11206
+ reactorClient: clients.client,
10726
11207
  relationalDb,
10727
11208
  analyticsStore,
10728
11209
  syncManager,
@@ -10735,6 +11216,7 @@ async function setupGraphQLManager({ httpAdapter, authFetchMiddleware, requireAu
10735
11216
  port,
10736
11217
  authorizationService,
10737
11218
  reactorDriveClient,
11219
+ driveNodes,
10738
11220
  syncServingGate,
10739
11221
  httpRoutes,
10740
11222
  attachments,
@@ -10766,6 +11248,11 @@ async function startServer(httpAdapter, port, httpsOptions, logger) {
10766
11248
  wsServer
10767
11249
  };
10768
11250
  }
11251
+ function boundPortOf(httpServer) {
11252
+ const address = httpServer.address();
11253
+ if (address === null || typeof address === "string") throw new Error(`The HTTP server is not bound to a TCP port: ${String(address)}`);
11254
+ return address.port;
11255
+ }
10769
11256
  /**
10770
11257
  * Private helper function that sets up common infrastructure before API initialization.
10771
11258
  * This includes auth configuration, database setup, and package manager initialization.
@@ -10900,16 +11387,12 @@ async function _setupCommonInfrastructure(options) {
10900
11387
  const dbClosers = [];
10901
11388
  const { relationalDb, analyticsStore, closers: analyticsClosers } = await initializeDatabaseAndAnalytics(options.dbPath, options.pgliteFactory, logger);
10902
11389
  dbClosers.push(...analyticsClosers);
10903
- let documentPermissionService = options.documentPermissionService;
10904
- if (!documentPermissionService && DOCUMENT_PERMISSIONS_ENABLED === "true") {
10905
- const { db, knex, pglite } = getDbClient(options.dbPath, options.pgliteFactory);
10906
- dbClosers.push(...makeDbClosers(knex, pglite, logger));
10907
- await runMigrations(db);
10908
- logger.info("Document permission migrations completed");
10909
- documentPermissionService = new DocumentPermissionService(db, { defaultProtection });
10910
- logger.info("Document permission service initialized");
10911
- }
10912
- const policy = documentPermissionService ? AuthorizationPolicy.DOCUMENT_PERMISSIONS : authEnabled ? AuthorizationPolicy.ADMIN_ONLY : AuthorizationPolicy.OPEN;
11390
+ const documentPermissionService = options.documentPermissionService;
11391
+ const ownDocumentPermissions = !documentPermissionService && DOCUMENT_PERMISSIONS_ENABLED === "true" ? {
11392
+ defaultProtection,
11393
+ cacheTtlMs: resolvePermissionCacheTtlMs(process.env.DOCUMENT_PERMISSION_CACHE_TTL_MS, logger)
11394
+ } : null;
11395
+ const policy = documentPermissionService || ownDocumentPermissions ? AuthorizationPolicy.DOCUMENT_PERMISSIONS : authEnabled ? AuthorizationPolicy.ADMIN_ONLY : AuthorizationPolicy.OPEN;
10913
11396
  const authorizationConfig = {
10914
11397
  admins,
10915
11398
  defaultProtection,
@@ -10935,7 +11418,8 @@ async function _setupCommonInfrastructure(options) {
10935
11418
  packages: options.packages ?? [],
10936
11419
  reportError: options.reportError
10937
11420
  });
10938
- const publicUrl = resolvePublicOrigin(port);
11421
+ const listenPort = { current: port };
11422
+ const publicUrl = resolvePublicOrigin(listenPort);
10939
11423
  const webhooks = new WebhookService({
10940
11424
  store: new RelationalWebhookStore(relationalDb),
10941
11425
  basePath: config.basePath,
@@ -10951,7 +11435,7 @@ async function _setupCommonInfrastructure(options) {
10951
11435
  });
10952
11436
  webhooks.attach(httpRoutes.hostScope(CORE_PACKAGE_NAME, path.posix.join("/", config.basePath ?? "/", WEBHOOK_SEGMENT)));
10953
11437
  return {
10954
- port,
11438
+ listenPort,
10955
11439
  httpAdapter,
10956
11440
  httpRoutes,
10957
11441
  authFetchMiddleware,
@@ -10961,6 +11445,7 @@ async function _setupCommonInfrastructure(options) {
10961
11445
  relationalDb,
10962
11446
  analyticsStore,
10963
11447
  documentPermissionService,
11448
+ ownDocumentPermissions,
10964
11449
  authorizationConfig,
10965
11450
  attachments,
10966
11451
  attachmentReferenceIndex,
@@ -10973,10 +11458,12 @@ async function _setupCommonInfrastructure(options) {
10973
11458
  /**
10974
11459
  * Private helper function containing common setup logic for API initialization
10975
11460
  */
10976
- async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, port, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, processorApp, readModels, attachments, attachmentReferenceIndex, attachmentReferenceProjection, authorizationConfig, documentModelRegistry, dbClosers = [], reactorDriveClient, syncServingGate, httpRoutes, attachmentReadsFollowDocumentPolicy = false, inspection, driveStore) {
11461
+ async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, listenPort, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, processorApp, readModels, attachments, attachmentReferenceIndex, attachmentReferenceProjection, authorizationConfig, documentModelRegistry, dbClosers = [], reactorDriveClient, syncServingGate, httpRoutes, attachmentReadsFollowDocumentPolicy = false, inspection, driveStore, driveNodes) {
10977
11462
  const hostModuleBase = {
10978
11463
  ...createReactorHostModuleBase({
10979
- client: reactorClient,
11464
+ client: clients.client,
11465
+ read: clients.read,
11466
+ write: clients.write,
10980
11467
  readModels,
10981
11468
  relationalDb,
10982
11469
  analyticsStore,
@@ -11012,12 +11499,14 @@ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, ht
11012
11499
  }
11013
11500
  }))).flat());
11014
11501
  }
11015
- const { httpServer, wsServer } = await startServer(httpAdapter, port, options.https, logger);
11016
- const authorizationService = createAuthorizationService(authorizationConfig, documentPermissionService, createGetParentIdsFn(reactorClient));
11502
+ const { httpServer, wsServer } = await startServer(httpAdapter, listenPort.current, options.https, logger);
11503
+ const boundPort = boundPortOf(httpServer);
11504
+ listenPort.current = boundPort;
11505
+ const authorizationService = createAuthorizationService(authorizationConfig, documentPermissionService, createGetParentIdsFn(clients.read));
11017
11506
  logger.info(`Authorization service initialized (policy: ${authorizationConfig.policy})`);
11018
11507
  assertAttachmentPolicyReadsAllowed(attachmentReadsFollowDocumentPolicy, syncServingGate !== void 0);
11019
11508
  const floor = requireAuthFetchMiddleware !== void 0;
11020
- const attachmentAccess = new AttachmentAccessService(createCanonicalDocumentIdResolver(reactorClient), authorizationService, attachmentReferenceIndex.store, attachmentReferenceProjection, reactorClient, attachmentReadsFollowDocumentPolicy ? syncServingGate : void 0, {
11509
+ const attachmentAccess = new AttachmentAccessService(createCanonicalDocumentIdResolver({ read: clients.read }), authorizationService, attachmentReferenceIndex.store, attachmentReferenceProjection, clients.read, attachmentReadsFollowDocumentPolicy ? syncServingGate : void 0, {
11021
11510
  refuseAnonymousWrites: authEnabled || floor,
11022
11511
  refuseAnonymousReads: floor
11023
11512
  });
@@ -11034,7 +11523,7 @@ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, ht
11034
11523
  requireAuthFetchMiddleware,
11035
11524
  httpServer,
11036
11525
  wsServer,
11037
- client: reactorClient,
11526
+ clients,
11038
11527
  relationalDb,
11039
11528
  analyticsStore,
11040
11529
  syncManager,
@@ -11047,8 +11536,9 @@ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, ht
11047
11536
  authService,
11048
11537
  documentPermissionService,
11049
11538
  enableDocumentModelSubgraphs: options.enableDocumentModelSubgraphs,
11050
- port,
11539
+ port: boundPort,
11051
11540
  reactorDriveClient,
11541
+ driveNodes,
11052
11542
  syncServingGate,
11053
11543
  httpRoutes,
11054
11544
  attachments: attachmentClientProvider,
@@ -11062,11 +11552,11 @@ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, ht
11062
11552
  });
11063
11553
  if (mcpServerEnabled) {
11064
11554
  await setupMcpServer({
11065
- client: reactorClient,
11555
+ client: clients.client,
11066
11556
  syncManager,
11067
11557
  authorizeRequest: createMcpRequestAuthorizer(authService, authorizationService)
11068
11558
  }, httpAdapter);
11069
- logger.info(`MCP server available at http://localhost:${port}/mcp`);
11559
+ logger.info(`MCP server available at http://localhost:${boundPort}/mcp`);
11070
11560
  }
11071
11561
  const dispose = buildApiDispose({
11072
11562
  graphqlManager,
@@ -11078,6 +11568,7 @@ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, ht
11078
11568
  });
11079
11569
  return {
11080
11570
  httpAdapter,
11571
+ port: boundPort,
11081
11572
  httpServer,
11082
11573
  httpRoutes: httpRoutes ?? new HttpRouteService({ httpAdapter }),
11083
11574
  graphqlManager,
@@ -11136,16 +11627,54 @@ function buildApiDispose(args) {
11136
11627
  }
11137
11628
  };
11138
11629
  }
11630
+ /**
11631
+ * Builds the host's own permission service: on the reactor store when the
11632
+ * client initializer handed it over, otherwise on the read-model store after
11633
+ * running reactor-api's legacy permission migrations there.
11634
+ */
11635
+ async function createOwnDocumentPermissionService(settings, permissionsDb, options, dbClosers, logger) {
11636
+ const cacheOptions = {
11637
+ ...DEFAULT_PERMISSION_CACHE_OPTIONS,
11638
+ ttlMs: settings.cacheTtlMs
11639
+ };
11640
+ const config = { defaultProtection: settings.defaultProtection };
11641
+ if (permissionsDb) {
11642
+ logger.info(`Document permission service initialized on the reactor store (cache TTL ${settings.cacheTtlMs} ms)`);
11643
+ return new DocumentPermissionService(permissionsDb, config, cacheOptions);
11644
+ }
11645
+ const { db, knex, pglite } = getDbClient(options.dbPath, options.pgliteFactory);
11646
+ dbClosers.push(...makeDbClosers(knex, pglite, logger));
11647
+ await runMigrations(db);
11648
+ logger.info("Document permission migrations completed");
11649
+ logger.info(`Document permission service initialized on the read-model store (cache TTL ${settings.cacheTtlMs} ms)`);
11650
+ return new DocumentPermissionService(db, config, cacheOptions);
11651
+ }
11652
+ /**
11653
+ * The permission cache TTL from `DOCUMENT_PERMISSION_CACHE_TTL_MS`: a
11654
+ * non-negative integer of milliseconds, 0 disabling the cache. Anything else
11655
+ * falls back to the default with a warning.
11656
+ */
11657
+ function resolvePermissionCacheTtlMs(raw, logger) {
11658
+ if (raw === void 0 || raw.trim() === "") return DEFAULT_PERMISSION_CACHE_TTL_MS;
11659
+ const parsed = Number(raw);
11660
+ if (!Number.isInteger(parsed) || parsed < 0) {
11661
+ logger.warn(`Ignoring DOCUMENT_PERMISSION_CACHE_TTL_MS=${raw}: expected a non-negative integer; using ${DEFAULT_PERMISSION_CACHE_TTL_MS} ms`);
11662
+ return DEFAULT_PERMISSION_CACHE_TTL_MS;
11663
+ }
11664
+ return parsed;
11665
+ }
11139
11666
  async function initializeAndStartAPI(clientInitializer, options, processorApp) {
11140
- const { port, httpAdapter, httpRoutes, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, relationalDb, analyticsStore, documentPermissionService, authorizationConfig, attachments, attachmentReferenceIndex, packages, dbClosers, readiness, attachmentReadsFollowDocumentPolicy } = await _setupCommonInfrastructure(options);
11667
+ const { listenPort, httpAdapter, httpRoutes, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, relationalDb, analyticsStore, documentPermissionService: providedDocumentPermissionService, ownDocumentPermissions, authorizationConfig, attachments, attachmentReferenceIndex, packages, dbClosers, readiness, attachmentReadsFollowDocumentPolicy } = await _setupCommonInfrastructure(options);
11141
11668
  const { documentModels, upgradeManifests, processors, subgraphs } = await packages.init();
11142
- const { module: reactorClientModule, reactorDriveClient, attachmentReferenceProjection = {
11669
+ const { module: reactorClientModule, reactorDriveClient, driveNodes, attachmentReferenceProjection = {
11143
11670
  status: "unavailable",
11144
11671
  reason: "initializer-did-not-report"
11145
- } } = await clientInitializer(documentModels, {
11672
+ }, permissionsDb } = await clientInitializer(documentModels, {
11146
11673
  attachmentReferenceWriter: attachmentReferenceIndex.store,
11147
- upgradeManifests
11674
+ upgradeManifests,
11675
+ readModelDb: getDbClient(options.dbPath, options.pgliteFactory).db
11148
11676
  });
11677
+ const documentPermissionService = providedDocumentPermissionService ?? (ownDocumentPermissions ? await createOwnDocumentPermissionService(ownDocumentPermissions, permissionsDb, options, dbClosers, options.logger ?? defaultLogger) : void 0);
11149
11678
  const reactorClient = reactorClientModule.client;
11150
11679
  const syncManager = reactorClientModule.reactorModule?.syncModule?.syncManager;
11151
11680
  if (!syncManager) throw new Error("SyncManager not available from InProcessReactorClientModule");
@@ -11153,13 +11682,20 @@ async function initializeAndStartAPI(clientInitializer, options, processorApp) {
11153
11682
  if (!reactorProcessorManager) throw new Error("ProcessorManager not available from InProcessReactorClientModule");
11154
11683
  const documentModelRegistry = reactorClientModule.reactorModule?.documentModelRegistry;
11155
11684
  if (!documentModelRegistry) throw new Error("DocumentModelRegistry not available from InProcessReactorClientModule");
11685
+ const readModels = (reactorClientModule.reactorModule?.readModelCoordinator)?.readModels ?? [];
11156
11686
  return {
11157
- ...await _setupAPI(reactorClient, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, port, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, processorApp, (reactorClientModule.reactorModule?.readModelCoordinator)?.readModels ?? [], attachments, attachmentReferenceIndex, attachmentReferenceProjection, authorizationConfig, documentModelRegistry, dbClosers, reactorDriveClient, buildSyncServingGate(reactorClientModule.reactorModule, authorizationConfig, options.logger ?? defaultLogger), httpRoutes, attachmentReadsFollowDocumentPolicy, reactorClientModule.reactorModule && options.inspection !== false ? createReactorInspectionSource(reactorClientModule.reactorModule, {
11687
+ ...await _setupAPI({
11688
+ read: reactorClientModule.read,
11689
+ write: reactorClientModule.write,
11690
+ client: reactorClient
11691
+ }, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, listenPort, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, processorApp, readModels, attachments, attachmentReferenceIndex, attachmentReferenceProjection, authorizationConfig, documentModelRegistry, dbClosers, reactorDriveClient, buildSyncServingGate(reactorClientModule.reactorModule, authorizationConfig, options.logger ?? defaultLogger), httpRoutes, attachmentReadsFollowDocumentPolicy, reactorClientModule.reactorModule && options.inspection !== false ? createReactorInspectionSource(reactorClientModule.reactorModule, {
11158
11692
  admin: process.env.INSPECTION_ADMIN_ENABLED === "true",
11159
11693
  ...options.inspection,
11160
11694
  attachmentStore: attachmentInspectionStore(attachments)
11161
- }) : void 0, reactorClientModule.reactorModule?.reactor),
11695
+ }) : void 0, reactorClientModule.reactorModule?.reactor, driveNodes),
11162
11696
  client: reactorClient,
11697
+ read: reactorClientModule.read,
11698
+ write: reactorClientModule.write,
11163
11699
  syncManager,
11164
11700
  documentModelRegistry,
11165
11701
  readiness,
@@ -11177,12 +11713,12 @@ async function initializeAndStartAPI(clientInitializer, options, processorApp) {
11177
11713
  * dev` behind a tunnel and, at worst, obviously wrong rather than silently
11178
11714
  * unusable.
11179
11715
  */
11180
- function resolvePublicOrigin(port) {
11716
+ function resolvePublicOrigin(listenPort) {
11181
11717
  const explicit = process.env.PUBLIC_URL ?? process.env.RENDER_EXTERNAL_URL;
11182
11718
  if (explicit) return withScheme(explicit);
11183
11719
  const domain = process.env.HEROKU_APP_DEFAULT_DOMAIN_NAME;
11184
11720
  if (domain) return withScheme(domain);
11185
- return `http://localhost:${port}`;
11721
+ return () => `http://localhost:${listenPort.current}`;
11186
11722
  }
11187
11723
  function withScheme(origin) {
11188
11724
  const trimmed = origin.replace(/\/+$/, "");
@@ -11347,7 +11883,7 @@ var PackageManagementService = class {
11347
11883
  }
11348
11884
  };
11349
11885
  //#endregion
11350
- export { ADMIN_USERS, ActionCandidateInputSchema, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentAccessFailed, AttachmentAccessService, AttachmentAccessUnavailable, AttachmentClientProvider, AuthDecision, AuthDecisionSchema, AuthEvaluationUnsupportedError, AuthService, AuthSubgraph, AuthenticationRequiredError, AuthorizationPolicy, AuthorizedAttachmentService, AuthorizedDocumentHandle, BaseSubgraph, CORE_PACKAGE_NAME, CanonicalDocumentIdResolutionError, ChannelMetaInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DEFAULT_INSPECTION_THROTTLE, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentModelSchemaCache, DocumentOperationsFilterInputSchema, DocumentPermissionService, DocumentRelationshipFieldsFragmentDoc, EvaluateActionsDocument, ExecuteBatchDocument, ExecutionJobInputSchema, FindDocumentsDocument, ForbiddenError, GetCreateDefaultsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentServedDocument, GetDocumentWithOperationsDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, HttpRouteService, ImportPackageLoader, InMemoryPackageStorage, InspectionAdminSubgraph, InspectionSubgraph, InspectionThrottle, InspectionThrottledError, InvalidNamespaceError, JobChangesDocument, JobInfoFieldsFragmentDoc, MalformedStoredOperationError, MemoryWebhookStore, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, NodeEventLoopDelay, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PACKAGE_ROUTE_SEGMENT, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PrivacyPermissionAdapter, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RefusalNotRecordedError, RelationalWebhookStore, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, RequestLoadRecorder, SearchFilterInputSchema, SetPreferredEditorDocument, SubgraphTypeCollisionError, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SyncRefusalInputSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, UpdateRelationshipDocument, ViewFilterInputSchema, WEBHOOK_SEGMENT, WS_AUTH_CLOSE_REASONS, WS_CLOSE_REASON_AUTHENTICATION_REQUIRED, WS_CLOSE_REASON_BEARER_REJECTED, WS_CLOSE_REASON_CREDENTIAL_REVOKED, WebhookService, assembleSubgraphTypeDefs, assertAttachmentPolicyReadsAllowed, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertHostMountPath, assertRequireAuthenticatedCallerAllowed, assertSkipCredentialVerificationAllowed, baseDocumentModels, buildDocumentModelSchema, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, callerSubject, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createCredentialInvalidator, createGatewayAdapter, createHttpAdapter, createInspectionResolvers, createMergedSchema, createReactorGraphQLClient, createReactorInspectionSource, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, definedNonNullAnySchema, documentModelSubgraphTypes, driveIdFromUrl, extractSubgraphs, extractSubgraphsFromModule, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getExplorerPrefix, getGeneratedDocumentModelTypes, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, hasOperationSchemas, initAnalyticsStoreSql, initializeAndStartAPI, inspectionAdminTypeDefs, inspectionTypeDefs, isCountedRequest, isDefinedNonNullAny, isExpectedLoaderMiss, isListedAdmin, isPostgresConnectionString, isSubgraphClass, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, piecesBaseUrl, redactHeaders, renderGraphqlPlayground, reportFailure, reservedTypeNames, reservedTypeNamesTaken, resolveCredentialCacheTtlMs, resolvePackageName, resolveRenownConfig, runDetached, typeDefinitionNames, verifyWebhook };
11886
+ export { ADMIN_USERS, ActionCandidateInputSchema, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentAccessFailed, AttachmentAccessService, AttachmentAccessUnavailable, AttachmentClientProvider, AuthDecision, AuthDecisionSchema, AuthEvaluationUnsupportedError, AuthService, AuthSubgraph, AuthenticationRequiredError, AuthorizationPolicy, AuthorizedAttachmentService, AuthorizedDocumentHandle, BaseSubgraph, CORE_PACKAGE_NAME, CanonicalDocumentIdResolutionError, ChannelMetaInputSchema, ConsistencyCoordinateInputSchema, ConsistencyTokenInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DEFAULT_INSPECTION_THROTTLE, DEFAULT_PERMISSION_CACHE_OPTIONS, DEFAULT_PERMISSION_CACHE_TTL_MS, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentModelSchemaCache, DocumentOperationsFilterInputSchema, DocumentPermissionService, DocumentPermissionSnapshot, DocumentRelationshipFieldsFragmentDoc, DriveNodeFieldsFragmentDoc, DriveNodeKind, DriveNodeKindSchema, EvaluateActionsDocument, ExecuteBatchDocument, ExecutionJobInputSchema, FindDocumentsDocument, ForbiddenError, GetCreateDefaultsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentServedDocument, GetDocumentWithOperationsDocument, GetDriveDescendantsDocument, GetDriveNodeDocument, GetDriveNodesDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, HttpRouteService, ImportPackageLoader, InMemoryPackageStorage, InspectionAdminSubgraph, InspectionSubgraph, InspectionThrottle, InspectionThrottledError, InvalidNamespaceError, JobChangesDocument, JobInfoFieldsFragmentDoc, MalformedStoredOperationError, MemoryWebhookStore, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, NodeEventLoopDelay, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PACKAGE_ROUTE_SEGMENT, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PermissionCache, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PrivacyPermissionAdapter, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RefusalNotRecordedError, RelationalWebhookStore, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, RequestLoadRecorder, SearchFilterInputSchema, SetPreferredEditorDocument, SubgraphTypeCollisionError, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SyncRefusalInputSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, UpdateRelationshipDocument, ViewFilterInputSchema, WEBHOOK_SEGMENT, WS_AUTH_CLOSE_REASONS, WS_CLOSE_REASON_AUTHENTICATION_REQUIRED, WS_CLOSE_REASON_BEARER_REJECTED, WS_CLOSE_REASON_CREDENTIAL_REVOKED, WebhookService, assembleSubgraphTypeDefs, assertAttachmentPolicyReadsAllowed, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertHostMountPath, assertRequireAuthenticatedCallerAllowed, assertSkipCredentialVerificationAllowed, baseDocumentModels, buildDocumentModelSchema, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, callerSubject, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createCredentialInvalidator, createGatewayAdapter, createHttpAdapter, createInspectionResolvers, createMergedSchema, createReactorGraphQLClient, createReactorInspectionSource, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, definedNonNullAnySchema, documentModelSubgraphTypes, driveIdFromUrl, extractSubgraphs, extractSubgraphsFromModule, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getExplorerPrefix, getGeneratedDocumentModelTypes, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, hasOperationSchemas, initAnalyticsStoreSql, initializeAndStartAPI, inspectionAdminTypeDefs, inspectionTypeDefs, isCountedRequest, isDefinedNonNullAny, isExpectedLoaderMiss, isListedAdmin, isPostgresConnectionString, isSubgraphClass, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, piecesBaseUrl, redactHeaders, renderGraphqlPlayground, reportFailure, reservedTypeNames, reservedTypeNamesTaken, resolveCredentialCacheTtlMs, resolvePackageName, resolvePermissionCacheTtlMs, resolveRenownConfig, runDetached, typeDefinitionNames, verifyWebhook };
11351
11887
 
11352
11888
  //# sourceMappingURL=index.mjs.map
11353
- //# debugId=c2728328-5512-5f96-b156-4cad5d80f920
11889
+ //# debugId=d978d340-82ad-56d2-8827-0daf9ed3bf67