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

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.
@@ -1,11 +1,12 @@
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]="e49cb480-7b71-5bff-8aad-d8fe772df5e1")}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]="871fe81d-1f96-5056-99a5-af64f77ff138")}catch(e){}}();
3
3
  import { createRequire } from "node:module";
4
4
  import { gql } from "graphql-tag";
5
5
  import { GraphQLError } from "graphql";
6
6
  import { DRIVE_AUTH_ERROR_MESSAGES, RECOVERABLE_GRAPHQL_ERROR_CODES } from "@powerhousedao/reactor";
7
7
  import { PURGE_DOCUMENT } from "@powerhousedao/shared/document-model";
8
8
  import { verifyAuthBearerToken } from "@renown/sdk";
9
+ import { AsyncLocalStorage } from "node:async_hooks";
9
10
  import { childLogger } from "document-model";
10
11
  import path, { dirname, isAbsolute, join } from "node:path";
11
12
  import { existsSync, readFileSync } from "node:fs";
@@ -275,12 +276,22 @@ var CanonicalDocumentIdResolutionError = class extends Error {
275
276
  * The sanctioned string-to-CanonicalDocumentId cast: both the GraphQL layer
276
277
  * and server routes must resolve caller identifiers through this helper so
277
278
  * decision and data layers always agree on the subject document.
279
+ *
280
+ * Queries and subscriptions resolve on the read half (`resolveIdOrSlug`, the
281
+ * lookup their data fetch makes); mutations on the write half (`describe`, the
282
+ * lookup their write makes). A bare read client (or the facade, whose
283
+ * `write` is then used) is accepted as the read half.
278
284
  */
279
- function createCanonicalDocumentIdResolver(client) {
285
+ function createCanonicalDocumentIdResolver(clients, operationType = "query") {
286
+ const pair = "resolveIdOrSlug" in clients ? {
287
+ read: clients,
288
+ write: clients.write
289
+ } : clients;
290
+ if (operationType === "mutation" && !pair.write) throw new Error("A mutation resolves identifiers on the write half; none was given");
280
291
  return async (identifier) => {
281
292
  let resolved;
282
293
  try {
283
- resolved = await client.resolveIdOrSlug(identifier);
294
+ resolved = operationType === "mutation" ? (await pair.write.describe(identifier)).documentId : await pair.read.resolveIdOrSlug(identifier);
284
295
  } catch {
285
296
  throw new CanonicalDocumentIdResolutionError();
286
297
  }
@@ -488,8 +499,197 @@ var AuthService = class {
488
499
  }
489
500
  };
490
501
  //#endregion
502
+ //#region src/graphql/request-clients.ts
503
+ /** A resolver outside a mutation asked for the write client. */
504
+ var WriteClientUnavailableError = class extends Error {
505
+ operation;
506
+ field;
507
+ constructor(operation, field) {
508
+ const where = field ? `field ${field}` : "this resolver";
509
+ const running = operation === "unbound" ? "outside a mutation" : `in a ${operation}`;
510
+ super(`ctx.clients.write is only available to Mutation fields; ${where} runs ${running}. Read through ctx.clients.read.`);
511
+ this.name = "WriteClientUnavailableError";
512
+ this.operation = operation;
513
+ this.field = field;
514
+ }
515
+ static isError(error) {
516
+ return error instanceof Error && error.name === "WriteClientUnavailableError";
517
+ }
518
+ };
519
+ /** The field whose resolver is running, so a refusal can name it. */
520
+ const executingField = new AsyncLocalStorage();
521
+ const operations = /* @__PURE__ */ new WeakMap();
522
+ /**
523
+ * The clients for one operation: both halves for a mutation, the read half
524
+ * and a refusing `write` for anything else. The refusing property is not
525
+ * enumerable, so spreading or printing the clients does not trip it.
526
+ */
527
+ function createRequestClients(read, write, operation) {
528
+ let clients;
529
+ if (operation === "mutation") clients = Object.freeze({
530
+ read,
531
+ write
532
+ });
533
+ else {
534
+ const gated = { read };
535
+ Object.defineProperty(gated, "write", {
536
+ enumerable: false,
537
+ get() {
538
+ throw new WriteClientUnavailableError(operation, executingField.getStore());
539
+ }
540
+ });
541
+ clients = Object.freeze(gated);
542
+ }
543
+ operations.set(clients, operation);
544
+ return clients;
545
+ }
546
+ /**
547
+ * The read half alone, for a context nobody bound to an operation (a resolver
548
+ * called directly rather than through the GraphQL layer). `write` refuses.
549
+ */
550
+ function readOnlyClients(read) {
551
+ return createRequestClients(read, UNAVAILABLE_WRITE, "unbound");
552
+ }
553
+ /** Never reached: a non-mutation client set refuses before handing it out. */
554
+ const UNAVAILABLE_WRITE = {};
555
+ /**
556
+ * Both halves for a field that reads write-side state outside a mutation. The
557
+ * clients still report `operation`, so identifiers resolve on the read side.
558
+ */
559
+ function createWriteSideClients(read, write, operation) {
560
+ const clients = Object.freeze({
561
+ read,
562
+ write
563
+ });
564
+ operations.set(clients, operation);
565
+ return clients;
566
+ }
567
+ /**
568
+ * The operation the clients were built for, or undefined for clients that
569
+ * {@link createRequestClients} did not build (a hand-made pair in a test).
570
+ */
571
+ function operationOfClients(clients) {
572
+ return clients === void 0 ? void 0 : operations.get(clients);
573
+ }
574
+ /**
575
+ * A resolver map's own object, as opposed to a scalar or another class
576
+ * instance, which passes through. Checked by prototype rather than with
577
+ * `isScalarType`, which refuses a scalar from another copy of graphql.
578
+ */
579
+ function isPlainObject(value) {
580
+ if (value === null || typeof value !== "object") return false;
581
+ const prototype = Object.getPrototypeOf(value);
582
+ return prototype === Object.prototype || prototype === null;
583
+ }
584
+ /** Type-level resolvers that receive the context; each is `(value, ctx, info)`. */
585
+ const TYPE_LEVEL_RESOLVERS = /* @__PURE__ */ new Set([
586
+ "__resolveReference",
587
+ "__resolveType",
588
+ "__isTypeOf"
589
+ ]);
590
+ /**
591
+ * Puts the client halves on the GraphQL context per operation. The host builds
592
+ * one context per request (or per WebSocket operation) before it knows what
593
+ * the operation is; every resolver this binder wraps receives instead a
594
+ * context derived from that one for the operation it is running in, so a
595
+ * mutation gets `ctx.clients.write` and a query or subscription does not.
596
+ *
597
+ * The derived context is memoized per request context and operation, so every
598
+ * field of one operation sees the same object, which per-request memos key on.
599
+ */
600
+ var RequestClientBinder = class {
601
+ #read;
602
+ #write;
603
+ #contexts = /* @__PURE__ */ new WeakMap();
604
+ #derived = /* @__PURE__ */ new WeakSet();
605
+ #wrapped = /* @__PURE__ */ new WeakMap();
606
+ constructor(read, write) {
607
+ this.#read = read;
608
+ this.#write = write;
609
+ }
610
+ /** The clients for a context the host builds before the operation is known. */
611
+ unboundClients() {
612
+ return createRequestClients(this.#read, this.#write, "unbound");
613
+ }
614
+ /**
615
+ * The context a resolver of `operation` receives for request context `base`.
616
+ * `writeSide` hands a query field the write client too: a field declared to
617
+ * read write-side state.
618
+ */
619
+ contextFor(base, operation, writeSide = false) {
620
+ if (this.#derived.has(base)) return base;
621
+ let byOperation = this.#contexts.get(base);
622
+ if (!byOperation) {
623
+ byOperation = /* @__PURE__ */ new Map();
624
+ this.#contexts.set(base, byOperation);
625
+ }
626
+ const key = writeSide ? `${operation}:write-side` : operation;
627
+ let derived = byOperation.get(key);
628
+ if (!derived) {
629
+ derived = {
630
+ ...base,
631
+ clients: writeSide ? createWriteSideClients(this.#read, this.#write, operation) : createRequestClients(this.#read, this.#write, operation)
632
+ };
633
+ this.#derived.add(derived);
634
+ byOperation.set(key, derived);
635
+ }
636
+ return derived;
637
+ }
638
+ /**
639
+ * A copy of a subgraph's resolver map whose resolvers receive the context
640
+ * for their operation. Scalars, enums and non-function members pass through.
641
+ * `writeSideFields` names the fields (`Type.field`) handed the write client
642
+ * whatever their operation. The copy is memoized per map.
643
+ */
644
+ bindResolvers(resolvers, writeSideFields = /* @__PURE__ */ new Set()) {
645
+ const cached = this.#wrapped.get(resolvers);
646
+ if (cached) return cached;
647
+ const bound = {};
648
+ for (const [typeName, typeResolvers] of Object.entries(resolvers)) bound[typeName] = this.#bindType(typeName, typeResolvers, writeSideFields);
649
+ this.#wrapped.set(resolvers, bound);
650
+ return bound;
651
+ }
652
+ #bindType(typeName, typeResolvers, writeSideFields) {
653
+ if (!isPlainObject(typeResolvers)) return typeResolvers;
654
+ const bound = {};
655
+ for (const [field, value] of Object.entries(typeResolvers)) {
656
+ const writeSide = writeSideFields.has(`${typeName}.${field}`);
657
+ if (typeof value === "function") bound[field] = TYPE_LEVEL_RESOLVERS.has(field) ? this.#bindTypeResolver(value) : field.startsWith("__") ? value : this.#bindFieldResolver(value, writeSide);
658
+ else if (isPlainObject(value)) {
659
+ const config = { ...value };
660
+ for (const key of ["resolve", "subscribe"]) if (typeof config[key] === "function") config[key] = this.#bindFieldResolver(config[key], writeSide);
661
+ bound[field] = config;
662
+ } else bound[field] = value;
663
+ }
664
+ return bound;
665
+ }
666
+ #bindFieldResolver(resolver, writeSide) {
667
+ return (parent, args, context, info) => {
668
+ if (!info?.operation) return resolver(parent, args, context, info);
669
+ const derived = this.contextFor(context ?? {}, info.operation.operation, writeSide);
670
+ return executingField.run(`${info.parentType.name}.${info.fieldName}`, () => resolver(parent, args, derived, info));
671
+ };
672
+ }
673
+ #bindTypeResolver(resolver) {
674
+ return (value, context, info) => {
675
+ if (!info?.operation) return resolver(value, context, info);
676
+ return resolver(value, this.contextFor(context ?? {}, info.operation.operation), info);
677
+ };
678
+ }
679
+ };
680
+ //#endregion
491
681
  //#region src/graphql/base-subgraph.ts
492
682
  /**
683
+ * Stands in for a client the subgraph was not given: any use names what to
684
+ * use instead rather than failing on `undefined`.
685
+ */
686
+ function missingClient(name, hint) {
687
+ return new Proxy({}, { get(_target, property) {
688
+ if (property === "then" || typeof property === "symbol") return;
689
+ throw new Error(`${name}.${String(property)}: ${hint}`);
690
+ } });
691
+ }
692
+ /**
493
693
  * The subject a request reads as: its address and the app key its token
494
694
  * carries. Anonymous is an empty subject, never the host's signer.
495
695
  */
@@ -508,6 +708,16 @@ var BaseSubgraph = class {
508
708
  hello: String
509
709
  }
510
710
  `;
711
+ /**
712
+ * The read half, for setup-time use (schema building, model lookup).
713
+ * Resolvers read through `ctx.clients.read` instead.
714
+ */
715
+ readClient;
716
+ /**
717
+ * @deprecated The facade over both halves, for subgraphs that have not
718
+ * moved. Resolvers use `ctx.clients.read` and, in a mutation,
719
+ * `ctx.clients.write`; setup-time code uses {@link readClient}.
720
+ */
511
721
  reactorClient;
512
722
  /** This package's namespaced slice of the HTTP surface. */
513
723
  http;
@@ -531,13 +741,15 @@ var BaseSubgraph = class {
531
741
  * batch resolvers resolve each distinct identifier at most once.
532
742
  */
533
743
  #canonicalIdMemo = /* @__PURE__ */ new WeakMap();
534
- #resolveCanonical;
744
+ #unboundClients;
535
745
  #attachments;
536
746
  #attachmentClientMemo = /* @__PURE__ */ new WeakMap();
537
747
  constructor(args) {
538
- this.#resolveCanonical = createCanonicalDocumentIdResolver(args.reactorClient);
748
+ const facadeRead = args.reactorClient?.read;
749
+ this.readClient = args.readClient ?? (typeof facadeRead?.get === "function" ? facadeRead : args.reactorClient) ?? missingClient("BaseSubgraph.readClient", "this subgraph was constructed without a readClient.");
750
+ this.reactorClient = args.reactorClient ?? missingClient("BaseSubgraph.reactorClient", "this host passes no reactorClient facade. Read through ctx.clients.read (or this.readClient at setup) and write through ctx.clients.write in a mutation.");
751
+ this.#unboundClients = readOnlyClients(this.readClient);
539
752
  this.http = args.http;
540
- this.reactorClient = args.reactorClient;
541
753
  this.graphqlManager = args.graphqlManager;
542
754
  this.relationalDb = args.relationalDb;
543
755
  this.syncManager = args.syncManager;
@@ -562,13 +774,22 @@ var BaseSubgraph = class {
562
774
  }
563
775
  return client;
564
776
  }
777
+ /**
778
+ * The clients this request's operation may use: those the GraphQL layer put
779
+ * on the context. A context it never saw (a resolver called directly) reads
780
+ * through {@link readClient} and may not write.
781
+ */
782
+ clientsOf(ctx) {
783
+ return ctx?.clients ?? this.#unboundClients;
784
+ }
565
785
  async onSetup() {}
566
786
  async onDisconnect() {}
567
787
  /**
568
788
  * Resolves a caller-supplied identifier (id or slug) to its canonical
569
789
  * document id, memoized per request. Both the decision layer and the data
570
- * layer must agree on the subject, so this runs the same resolveIdOrSlug
571
- * lookup the data path uses. A resolution failure (not found, ambiguous, or
790
+ * layer must agree on the subject, so this runs the lookup the data path
791
+ * uses: `resolveIdOrSlug` on the read half for a query, `describe` on the
792
+ * write half for a mutation. A resolution failure (not found, ambiguous, or
572
793
  * transient) surfaces as a generic Forbidden, fail-closed, so a bad
573
794
  * identifier cannot be used as a document-existence oracle.
574
795
  */
@@ -580,9 +801,14 @@ var BaseSubgraph = class {
580
801
  }
581
802
  const cached = cache.get(identifier);
582
803
  if (cached !== void 0) return cached;
804
+ const clients = this.clientsOf(requestKey);
805
+ const resolve = operationOfClients(clients) === "mutation" ? createCanonicalDocumentIdResolver({
806
+ read: clients.read,
807
+ write: clients.write
808
+ }, "mutation") : createCanonicalDocumentIdResolver({ read: clients.read }, "query");
583
809
  let canonical;
584
810
  try {
585
- canonical = await this.#resolveCanonical(identifier);
811
+ canonical = await resolve(identifier);
586
812
  } catch {
587
813
  throw new ForbiddenError();
588
814
  }
@@ -649,7 +875,7 @@ var BaseSubgraph = class {
649
875
  }
650
876
  /** {@link servesDocument}, but a reactor that cannot answer throws. */
651
877
  servesDocumentOrThrows(identifier, ctx, view) {
652
- return this.reactorClient.isServed(identifier, {
878
+ return this.clientsOf(ctx).read.isServed(identifier, {
653
879
  ...view,
654
880
  subject: this.viewSubject(ctx)
655
881
  });
@@ -1171,7 +1397,7 @@ function extractSubgraphs(namespace) {
1171
1397
  return found;
1172
1398
  }
1173
1399
  //#endregion
1174
- export { createCanonicalDocumentIdResolver as A, loadSubgraphs as C, AuthService as D, callerSubject as E, AuthenticationRequiredError as F, ForbiddenError as I, MalformedStoredOperationError as L, AuthorizedDocumentHandle as M, createAuthorizationService as N, createCredentialInvalidator as O, AuthEvaluationUnsupportedError as P, RefusalNotRecordedError as R, loadProcessors as S, BaseSubgraph as T, PACKAGE_MODULE_FAILED as _, packageRootOf as a, isSubpath as b, piecesFromListModule as c, buildGraphQlDriveDocument as d, buildGraphqlOperation as f, runDetached as g, reportFailure as h, PIECE_SOURCE_LIST as i, AuthorizationPolicy as j, CanonicalDocumentIdResolutionError as k, extractDocumentModels as l, isSubgraphClass as m, BUILT_PIECE_LIST as n, pieceListLocation as o, buildGraphqlOperations as p, PIECES_SUBPATH as r, piecesFromCdnList as s, extractSubgraphs as t, buildGraphQlDocument as u, debounce as v, manifestDeclaredSubgraphs as w, loadDocumentModels as x, extractUpgradeManifests as y };
1400
+ export { CanonicalDocumentIdResolutionError as A, loadSubgraphs as C, RequestClientBinder as D, callerSubject as E, AuthEvaluationUnsupportedError as F, AuthenticationRequiredError as I, ForbiddenError as L, AuthorizationPolicy as M, AuthorizedDocumentHandle as N, AuthService as O, createAuthorizationService as P, MalformedStoredOperationError as R, loadProcessors as S, BaseSubgraph as T, PACKAGE_MODULE_FAILED as _, packageRootOf as a, isSubpath as b, piecesFromListModule as c, buildGraphQlDriveDocument as d, buildGraphqlOperation as f, runDetached as g, reportFailure as h, PIECE_SOURCE_LIST as i, createCanonicalDocumentIdResolver as j, createCredentialInvalidator as k, extractDocumentModels as l, isSubgraphClass as m, BUILT_PIECE_LIST as n, pieceListLocation as o, buildGraphqlOperations as p, PIECES_SUBPATH as r, piecesFromCdnList as s, extractSubgraphs as t, buildGraphQlDocument as u, debounce as v, manifestDeclaredSubgraphs as w, loadDocumentModels as x, extractUpgradeManifests as y, RefusalNotRecordedError as z };
1175
1401
 
1176
- //# sourceMappingURL=subgraph-extraction-cSpPp3Hq.mjs.map
1177
- //# debugId=e49cb480-7b71-5bff-8aad-d8fe772df5e1
1402
+ //# sourceMappingURL=subgraph-extraction-zUDn2zX_.mjs.map
1403
+ //# debugId=871fe81d-1f96-5056-99a5-af64f77ff138
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subgraph-extraction-zUDn2zX_.mjs","sources":["../src/graphql/errors.ts","../src/services/authorization.service.ts","../src/services/canonical-document-id.ts","../src/services/auth.service.ts","../src/graphql/request-clients.ts","../src/graphql/base-subgraph.ts","../src/packages/import-resolver.ts","../src/packages/util.ts","../src/utils/detached.ts","../src/graphql/utils.ts","../src/packages/document-model-detection.ts","../src/packages/pieces.ts","../src/packages/subgraph-extraction.ts"],"sourcesContent":["import { GraphQLError } from \"graphql\";\nimport {\n DRIVE_AUTH_ERROR_MESSAGES,\n RECOVERABLE_GRAPHQL_ERROR_CODES,\n} from \"@powerhousedao/reactor\";\n\n/** Caller (authenticated or anonymous) lacks permission for the document. */\nexport class ForbiddenError extends GraphQLError {\n constructor(detail = \"\") {\n const base = DRIVE_AUTH_ERROR_MESSAGES.forbidden;\n super(`${base}${detail ? ` ${detail}` : \"\"}`, {\n extensions: { code: \"FORBIDDEN\" },\n });\n }\n}\n\n/** Anonymous caller on an action that requires logging in. */\nexport class AuthenticationRequiredError extends GraphQLError {\n constructor(detail = \"\") {\n const base = DRIVE_AUTH_ERROR_MESSAGES.authenticationRequired;\n super(`${base}${detail ? ` ${detail}` : \"\"}`, {\n extensions: { code: \"UNAUTHENTICATED\" },\n });\n }\n}\n\n/**\n * The reactor holds no decision model, so no authorization preflight can be\n * answered.\n *\n * Distinct from a denial, and deliberately so: a caller that cannot get a\n * prediction should render its controls as it did before it asked and let the\n * submit path refuse. Reading this as a denial would disable every control on a\n * switchboard running without authEnforcement. The code is what a client\n * branches on, since the message is not a contract.\n */\nexport class AuthEvaluationUnsupportedError extends GraphQLError {\n constructor() {\n super(\n \"Authorization evaluation is unavailable: this reactor runs without the \" +\n \"authEnforcement feature flag, so it holds no decision model\",\n { extensions: { code: \"AUTH_EVALUATION_UNSUPPORTED\" } },\n );\n }\n}\n\n/**\n * A stored operation cannot be represented in the schema, so it is reported\n * rather than served.\n *\n * The schema declares an action's id, type, timestamp, input and scope\n * non-null; an operation written before the API rejected an action without an\n * id violates that. Left to the executor, the missing value nullifies the\n * action, which bubbles up through the non-null chain until it nullifies the\n * envelope's whole operation list, and the caller receives a partial response\n * beside \"Cannot return null for non-nullable field Action.id\" - which says\n * nothing about which operation, and which a sync client can only read as a\n * permanent GraphQL rejection, stopping its poll timer for good.\n *\n * Thrown instead, with a code that says the failure is worth polling through:\n * the document holding the operation needs repairing, but the channel serves\n * every other document, and a peer that stopped polling would stop receiving\n * those too. The code is what a client branches on, since the message is not a\n * contract.\n */\nexport class MalformedStoredOperationError extends GraphQLError {\n constructor(detail: string) {\n super(`Stored operation cannot be served: ${detail}`, {\n extensions: {\n code: RECOVERABLE_GRAPHQL_ERROR_CODES.malformedStoredOperation,\n },\n });\n }\n}\n\n/**\n * The marker refusals a poll carried were not recorded, so the poll fails.\n * The code is recoverable: the client keeps polling and reports them again.\n */\nexport class RefusalNotRecordedError extends GraphQLError {\n constructor(cause: unknown) {\n super(\"A reported marker refusal was not recorded; report it again\", {\n originalError: cause instanceof Error ? cause : new Error(String(cause)),\n extensions: {\n code: RECOVERABLE_GRAPHQL_ERROR_CODES.refusalNotRecorded,\n },\n });\n }\n}\n","import { PURGE_DOCUMENT } from \"@powerhousedao/shared/document-model\";\nimport type { DocumentPermissionLevel } from \"../utils/db.js\";\nimport type {\n DocumentPermissionService,\n GetParentIdsFn,\n} from \"./document-permission.service.js\";\n\n/**\n * A document id that has been resolved to its canonical form, never a slug.\n *\n * Protection and grant rows are written under the canonical id, while the\n * read/operation data paths accept an id-or-slug identifier. The decision layer\n * must key on the canonical id, so branding it forces every caller to resolve a\n * slug to its id before consulting this service, closing the slug-aliasing\n * bypass (S-C1). The only sanctioned cast from string to CanonicalDocumentId\n * lives in createCanonicalDocumentIdResolver, immediately after the shared\n * resolveIdOrSlug lookup returns.\n */\nexport type CanonicalDocumentId = string & {\n readonly __canonicalDocumentId: unique symbol;\n};\n\n/**\n * Result of a passed per-document authorization check. `fetchIdentifier` is\n * always safe for the data fetch: the canonical id when resolved, or the raw\n * identifier when the check was skipped for a policy-wide caller.\n */\nexport class AuthorizedDocumentHandle {\n private constructor(\n readonly fetchIdentifier: string,\n readonly isResolved: boolean,\n ) {}\n\n static resolved(documentId: CanonicalDocumentId): AuthorizedDocumentHandle {\n return new AuthorizedDocumentHandle(documentId, true);\n }\n\n static skipped(identifier: string): AuthorizedDocumentHandle {\n return new AuthorizedDocumentHandle(identifier, false);\n }\n\n /** The verified canonical id; throws when resolution was skipped. */\n canonicalId(): CanonicalDocumentId {\n if (!this.isResolved) {\n throw new Error(\n \"Canonical document id is unavailable: the authorization check was skipped for a policy-wide caller\",\n );\n }\n return this.fetchIdentifier as CanonicalDocumentId;\n }\n}\n\nexport const AuthorizationPolicy = {\n OPEN: \"OPEN\",\n ADMIN_ONLY: \"ADMIN_ONLY\",\n DOCUMENT_PERMISSIONS: \"DOCUMENT_PERMISSIONS\",\n} as const;\n\nexport type AuthorizationPolicy =\n (typeof AuthorizationPolicy)[keyof typeof AuthorizationPolicy];\n\nexport interface AuthorizationConfig {\n admins: string[];\n defaultProtection: boolean;\n policy: AuthorizationPolicy;\n}\n\n/**\n * Single source of truth for every permission decision. Always present (never\n * null) so callers branch on data, not on the existence of a service.\n *\n * The policy selects an implementation once at boot:\n * - OPEN: authentication disabled — everyone (incl. anonymous) is allowed.\n * - ADMIN_ONLY: authentication on, document permissions off — only ADMINS.\n * - DOCUMENT_PERMISSIONS: the full per-document protection + grant model.\n *\n * Permission inheritance walks the parent-document hierarchy through a\n * parent resolver injected at construction; callers never supply one.\n */\nexport interface IAuthorizationService {\n readonly config: AuthorizationConfig;\n\n /**\n * Whether the user has unrestricted, policy-wide access. Under OPEN this is\n * true for everyone (including anonymous callers) by design: OPEN means \"no\n * restrictions\", and consumers use this check to skip per-document\n * filtering. It does NOT mean the caller is in the ADMINS list.\n */\n isSupremeAdmin(userAddress?: string): boolean;\n\n /**\n * Whether the user may create new documents under the current policy:\n * everyone in OPEN, only admins in ADMIN_ONLY, any authenticated user in\n * DOCUMENT_PERMISSIONS.\n */\n canCreate(userAddress?: string): boolean;\n\n canRead(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean>;\n\n canWrite(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean>;\n\n /**\n * Whether the user administers the document: supreme admin, document\n * owner, or holder of an ADMIN grant.\n */\n canManage(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean>;\n\n canMutate(\n documentId: CanonicalDocumentId,\n operationType: string,\n userAddress?: string,\n ): Promise<boolean>;\n}\n\n/** Shared config holder and admin-list check for the policy strategies. */\nabstract class BaseAuthorizationService implements IAuthorizationService {\n constructor(readonly config: AuthorizationConfig) {}\n\n isSupremeAdmin(userAddress?: string): boolean {\n if (!userAddress) return false;\n return this.config.admins.includes(userAddress.toLowerCase());\n }\n\n abstract canCreate(userAddress?: string): boolean;\n\n abstract canRead(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean>;\n\n abstract canWrite(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean>;\n\n abstract canManage(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean>;\n\n abstract canMutate(\n documentId: CanonicalDocumentId,\n operationType: string,\n userAddress?: string,\n ): Promise<boolean>;\n}\n\n/** OPEN: authentication disabled — everyone (incl. anonymous) is allowed. */\nclass OpenAuthorizationService extends BaseAuthorizationService {\n isSupremeAdmin(): boolean {\n return true;\n }\n\n canCreate(): boolean {\n return true;\n }\n\n canRead(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n canWrite(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n canManage(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n canMutate(): Promise<boolean> {\n return Promise.resolve(true);\n }\n}\n\n/** ADMIN_ONLY: authentication on, document permissions off — only ADMINS. */\nclass AdminOnlyAuthorizationService extends BaseAuthorizationService {\n canCreate(userAddress?: string): boolean {\n return this.isSupremeAdmin(userAddress);\n }\n\n canRead(\n _documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean> {\n return Promise.resolve(this.isSupremeAdmin(userAddress));\n }\n\n canWrite(\n _documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean> {\n return Promise.resolve(this.isSupremeAdmin(userAddress));\n }\n\n canManage(\n _documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean> {\n return Promise.resolve(this.isSupremeAdmin(userAddress));\n }\n\n canMutate(\n _documentId: CanonicalDocumentId,\n _operationType: string,\n userAddress?: string,\n ): Promise<boolean> {\n return Promise.resolve(this.isSupremeAdmin(userAddress));\n }\n}\n\nconst PERMISSION_RANK: Record<DocumentPermissionLevel, number> = {\n READ: 1,\n WRITE: 2,\n ADMIN: 3,\n};\n\nfunction satisfies(\n level: DocumentPermissionLevel | null,\n required: DocumentPermissionLevel,\n): boolean {\n return level !== null && PERMISSION_RANK[level] >= PERMISSION_RANK[required];\n}\n\n/**\n * DOCUMENT_PERMISSIONS: the full per-document protection + grant model.\n *\n * All decisions live here; DocumentPermissionService is the data-access\n * layer underneath (grants, protection rows, owners).\n */\nclass DocumentPermissionsAuthorizationService extends BaseAuthorizationService {\n readonly #permissions: DocumentPermissionService;\n readonly #getParentIds: GetParentIdsFn;\n\n constructor(\n permissions: DocumentPermissionService,\n getParentIds: GetParentIdsFn,\n config: AuthorizationConfig,\n ) {\n super(config);\n this.#permissions = permissions;\n this.#getParentIds = getParentIds;\n }\n\n canCreate(userAddress?: string): boolean {\n return this.isSupremeAdmin(userAddress) || !!userAddress;\n }\n\n canRead(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean> {\n return this.#canAccess(documentId, \"READ\", userAddress);\n }\n\n canWrite(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean> {\n return this.#canAccess(documentId, \"WRITE\", userAddress);\n }\n\n canManage(\n documentId: CanonicalDocumentId,\n userAddress?: string,\n ): Promise<boolean> {\n return this.#isDocumentAdmin(documentId, userAddress);\n }\n\n async canMutate(\n documentId: CanonicalDocumentId,\n operationType: string,\n userAddress?: string,\n ): Promise<boolean> {\n if (this.isSupremeAdmin(userAddress)) return true;\n // A purge marker needs a document admin whatever the operation rows say.\n if (operationType === PURGE_DOCUMENT) {\n return this.#isDocumentAdmin(documentId, userAddress);\n }\n\n const isRestricted = await this.#permissions.isOperationRestricted(\n documentId,\n operationType,\n );\n if (isRestricted) {\n if (!userAddress) return false;\n if (await this.#isDocumentAdmin(documentId, userAddress)) return true;\n return this.#permissions.hasOperationGrant(\n documentId,\n operationType,\n userAddress,\n );\n }\n\n return this.#canAccess(documentId, \"WRITE\", userAddress);\n }\n\n /**\n * The one \"administers this document\" predicate: supreme admin, document\n * owner, or ADMIN grant on the document itself.\n */\n async #isDocumentAdmin(\n documentId: string,\n userAddress?: string,\n ): Promise<boolean> {\n if (this.isSupremeAdmin(userAddress)) return true;\n if (!userAddress) return false;\n\n const owner = await this.#permissions.getDocumentOwner(documentId);\n if (owner && owner === userAddress.toLowerCase()) return true;\n\n return satisfies(await this.#grantLevel(documentId, userAddress), \"ADMIN\");\n }\n\n /**\n * The one read/write decision shape: supreme admin → unprotected (self or\n * ancestor) → owner → inherited grant of at least the required level.\n */\n async #canAccess(\n documentId: string,\n required: DocumentPermissionLevel,\n userAddress?: string,\n ): Promise<boolean> {\n if (this.isSupremeAdmin(userAddress)) return true;\n\n const isProtected = await this.#permissions.isProtectedWithAncestors(\n documentId,\n this.#getParentIds,\n );\n if (!isProtected) return true;\n if (!userAddress) return false;\n\n const owner = await this.#permissions.getDocumentOwner(documentId);\n if (owner && owner === userAddress.toLowerCase()) return true;\n\n return this.#hasGrantInHierarchy(documentId, userAddress, required);\n }\n\n /** Best grant the user holds on the document. */\n async #grantLevel(\n documentId: string,\n userAddress: string,\n ): Promise<DocumentPermissionLevel | null> {\n return this.#permissions.getUserPermission(documentId, userAddress);\n }\n\n /**\n * Walks the parent hierarchy (with cycle protection) looking for a grant of\n * at least the required level on the document or any ancestor.\n */\n async #hasGrantInHierarchy(\n documentId: string,\n userAddress: string,\n required: DocumentPermissionLevel,\n ): Promise<boolean> {\n const visited = new Set<string>();\n const queue = [documentId];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (visited.has(current)) continue;\n visited.add(current);\n\n const level = await this.#grantLevel(current, userAddress);\n if (satisfies(level, required)) return true;\n\n for (const parentId of await this.#getParentIds(current)) {\n if (!visited.has(parentId)) queue.push(parentId);\n }\n }\n\n return false;\n }\n}\n\n/**\n * Selects the strategy for the configured policy. The strategy classes are\n * not exported, so this guard is the only construction path.\n */\nexport function createAuthorizationService(\n config: AuthorizationConfig,\n documentPermissionService?: DocumentPermissionService,\n getParentIds?: GetParentIdsFn,\n): IAuthorizationService {\n if (config.policy === AuthorizationPolicy.OPEN) {\n return new OpenAuthorizationService(config);\n }\n if (config.policy === AuthorizationPolicy.ADMIN_ONLY) {\n return new AdminOnlyAuthorizationService(config);\n }\n if (!documentPermissionService) {\n throw new Error(\n \"DocumentPermissionService is required for the DOCUMENT_PERMISSIONS policy\",\n );\n }\n if (!getParentIds) {\n throw new Error(\n \"A getParentIds resolver is required for the DOCUMENT_PERMISSIONS policy\",\n );\n }\n return new DocumentPermissionsAuthorizationService(\n documentPermissionService,\n getParentIds,\n config,\n );\n}\n","import type {\n IReactorReadClient,\n IReactorWriteClient,\n} from \"@powerhousedao/reactor\";\nimport type { CanonicalDocumentId } from \"./authorization.service.js\";\n\n/**\n * Raised when a caller-supplied identifier cannot be resolved to a canonical\n * document id. Carries no detail on purpose: resolution failures must not act\n * as a document-existence oracle, so consumers map this to their generic\n * fail-closed response.\n */\nexport class CanonicalDocumentIdResolutionError extends Error {\n constructor() {\n super(\"Document identifier could not be resolved\");\n this.name = \"CanonicalDocumentIdResolutionError\";\n }\n}\n\nexport type CanonicalDocumentIdResolver = (\n identifier: string,\n) => Promise<CanonicalDocumentId>;\n\n/** Resolves an identifier the way the read side's data paths do. */\nexport type ReadSideIdentity = Pick<IReactorReadClient, \"resolveIdOrSlug\">;\n\n/** Resolves an identifier the way a mutation resolves its target. */\nexport type WriteSideIdentity = Pick<IReactorWriteClient, \"describe\">;\n\n/** The halves an identifier can be resolved on; mutations need `write`. */\nexport type CanonicalIdClients = {\n read: ReadSideIdentity;\n write?: WriteSideIdentity;\n};\n\n/** Which side resolves: a mutation resolves on the write side. */\nexport type CanonicalIdOperation = \"query\" | \"mutation\" | \"subscription\";\n\n/**\n * The sanctioned string-to-CanonicalDocumentId cast: both the GraphQL layer\n * and server routes must resolve caller identifiers through this helper so\n * decision and data layers always agree on the subject document.\n *\n * Queries and subscriptions resolve on the read half (`resolveIdOrSlug`, the\n * lookup their data fetch makes); mutations on the write half (`describe`, the\n * lookup their write makes). A bare read client (or the facade, whose\n * `write` is then used) is accepted as the read half.\n */\nexport function createCanonicalDocumentIdResolver(\n clients: CanonicalIdClients | ReadSideIdentity,\n operationType: CanonicalIdOperation = \"query\",\n): CanonicalDocumentIdResolver {\n const pair: CanonicalIdClients =\n \"resolveIdOrSlug\" in clients\n ? {\n read: clients,\n write: (clients as { write?: WriteSideIdentity }).write,\n }\n : clients;\n if (operationType === \"mutation\" && !pair.write) {\n throw new Error(\n \"A mutation resolves identifiers on the write half; none was given\",\n );\n }\n return async (identifier: string) => {\n let resolved: string;\n try {\n resolved =\n operationType === \"mutation\"\n ? (await pair.write!.describe(identifier)).documentId\n : await pair.read.resolveIdOrSlug(identifier);\n } catch {\n throw new CanonicalDocumentIdResolutionError();\n }\n return resolved as CanonicalDocumentId;\n };\n}\n","import type { RouteUser } from \"@powerhousedao/shared/processors\";\nimport { verifyAuthBearerToken } from \"@renown/sdk\";\n\ntype VerifiedCredential =\n Awaited<ReturnType<typeof verifyAuthBearerToken>> extends false | (infer T)\n ? T\n : never;\n\n// Confirms an authenticated signer's credential is still valid. Injected so\n// AuthService stays agnostic to how/where credentials are verified.\nexport type CredentialVerifier = (params: {\n address: string;\n chainId: number;\n appId: string;\n}) => Promise<boolean>;\n\nexport interface AuthConfig {\n /**\n * Whether the authorization policy enforces anything: it selects `ADMIN_ONLY`\n * over `OPEN`, and it is what `AuthContext.auth_enabled` reports to callers\n * that gate on \"is authentication being enforced\" (the attachment routes do).\n *\n * It does NOT decide whether the bearer is read — see {@link resolveIdentity}.\n */\n enabled: boolean;\n /**\n * Whether the bearer is verified and `AuthContext.user` populated at all.\n *\n * Defaults to {@link enabled}, which is the behaviour every deployment had\n * before this option existed. Setting it independently is what lets a server\n * know who is calling while leaving the policy `OPEN` — resolving an identity\n * and enforcing one are different concerns, and welding them together left\n * consumers choosing between an unauthenticated caller and locking every\n * non-admin out.\n *\n * It resolves an identity and enforces nothing: a request with no token is\n * still admitted, with no user.\n */\n resolveIdentity?: boolean;\n admins: string[];\n skipCredentialVerification?: boolean; // DANGER: removes identity verification; boot-gated to test/dev\n credentialVerificationCacheTtlMs?: number; // How long successful Renown credential checks are cached; 0 disables caching\n verifyCredential?: CredentialVerifier; // Injected credential check; required when verification is on\n}\n\nconst DEFAULT_CREDENTIAL_CACHE_TTL_MS = 60_000;\nconst CREDENTIAL_CACHE_MAX_ENTRIES = 1_000;\n\ninterface CredentialCacheEntry {\n exists: Promise<boolean>;\n expiresAt: number;\n address: string;\n chainId: number;\n appId: string;\n}\n\n/** What `invalidateCredential` was called with; `address` is lower-cased. */\nexport interface CredentialInvalidation {\n address: string;\n chainId?: number;\n appDid?: string;\n}\n\nexport type CredentialInvalidationListener = (\n invalidation: CredentialInvalidation,\n) => void;\n\n/**\n * The slice of {@link AuthService} handed to packages (as\n * `SubgraphArgs.credentials` / `BaseSubgraph.credentials`): a package that\n * revokes a credential calls this so the host stops honouring it at once\n * instead of after the credential cache TTL.\n */\nexport interface ICredentialInvalidator {\n /**\n * Evict cached credential checks for `address` (case-insensitive), narrowed\n * by `chainId` and the app DID (`did:key` of the app the credential\n * delegates to) when given, and re-verify open WebSocket connections of that\n * identity. Returns the number of cache entries evicted. Synchronous and\n * local to this process: other replicas still honour their cache until\n * their TTL lapses.\n */\n invalidateCredential(\n address: string,\n chainId?: number,\n appDid?: string,\n ): number;\n}\n\n/** The invalidator a subgraph receives: forwards to `authService`, or does\n * nothing when the host runs without one. */\nexport function createCredentialInvalidator(\n authService: AuthService | undefined,\n): ICredentialInvalidator {\n return {\n invalidateCredential: (address, chainId, appDid) =>\n authService?.invalidateCredential(address, chainId, appDid) ?? 0,\n };\n}\n\n/**\n * The authenticated principal. The shape is declared once in\n * `@powerhousedao/shared/processors` as `RouteUser`, so a route handler and a\n * resolver agree on it without either package redeclaring it.\n */\nexport type User = RouteUser;\n\nexport interface AuthContext {\n user?: User;\n admins: string[];\n auth_enabled: boolean;\n}\n\nexport class AuthService implements ICredentialInvalidator {\n private readonly config: AuthConfig;\n private readonly credentialCache = new Map<string, CredentialCacheEntry>();\n private readonly invalidationListeners =\n new Set<CredentialInvalidationListener>();\n\n constructor(config: AuthConfig) {\n this.config = config;\n }\n\n /**\n * Whether this service reads the bearer at all. Defaults to `enabled`, so a\n * config written before `resolveIdentity` existed behaves exactly as it did.\n */\n private get resolvesIdentity(): boolean {\n return this.config.resolveIdentity ?? this.config.enabled;\n }\n\n /** The context an unresolved request gets: no user, and no admin list to match against. */\n private anonymousContext(): AuthContext {\n return { user: undefined, admins: [], auth_enabled: this.config.enabled };\n }\n\n async authenticateRequest(\n request: globalThis.Request,\n ): Promise<AuthContext | globalThis.Response> {\n if (!this.resolvesIdentity) {\n return this.anonymousContext();\n }\n // OPTIONS is a CORS preflight: it never carries application auth. Every\n // other method verifies whatever token it carries -- a GET query's payload\n // can be an authorization verdict, so discarding its token would silently\n // answer for the anonymous subject instead of the authenticated caller.\n // A GET without a token stays anonymous, as verifyBearer already allows.\n if (request.method === \"OPTIONS\") {\n return {\n user: undefined,\n admins: this.config.admins,\n auth_enabled: this.config.enabled,\n };\n }\n return this.verifyBearer(request.headers.get(\"authorization\") ?? undefined);\n }\n\n /**\n * Verify a Bearer token regardless of HTTP method. Use this from non-GraphQL\n * middleware that must enforce authentication on every request.\n */\n async verifyBearer(\n authorization: string | undefined,\n ): Promise<AuthContext | globalThis.Response> {\n if (!this.resolvesIdentity) {\n return this.anonymousContext();\n }\n const token = authorization?.split(\" \")[1];\n if (!token) {\n return {\n user: undefined,\n admins: this.config.admins,\n auth_enabled: this.config.enabled,\n };\n }\n try {\n const verified = await this.verifyToken(token);\n if (!verified) {\n return new Response(JSON.stringify({ error: \"Verification failed\" }), {\n status: 401,\n });\n }\n const user = this.extractUserFromVerification(verified);\n if (!user) {\n return new Response(JSON.stringify({ error: \"Missing credentials\" }), {\n status: 401,\n });\n }\n if (!this.config.skipCredentialVerification) {\n const credentialExists = await this.verifyCredentialExists(\n user.address,\n user.chainId,\n verified.issuer,\n );\n if (!credentialExists) {\n return new Response(\n JSON.stringify({ error: \"Credentials no longer valid\" }),\n { status: 401 },\n );\n }\n }\n return {\n user,\n admins: this.config.admins,\n auth_enabled: this.config.enabled,\n };\n } catch {\n return new Response(JSON.stringify({ error: \"Authentication failed\" }), {\n status: 401,\n });\n }\n }\n\n // `null` when there is nobody to resolve: resolution off, or no bearer sent.\n\n /** Throws only for a bearer that is present and unusable, as HTTP 401s it. */\n async authenticateWebSocketConnection(\n connectionParams: Record<string, unknown>,\n ): Promise<User | null> {\n if (!this.resolvesIdentity) {\n return null;\n }\n\n const authHeader = connectionParams.authorization as string | undefined;\n if (!authHeader) {\n // Resolution, not enforcement: `verifyBearer` answers the same.\n\n // Refusing anonymous is onConnect's, keyed on REQUIRE_AUTHENTICATED_CALLER.\n\n // Subscriptions themselves authorize per document.\n return null;\n }\n\n const token = authHeader.split(\" \")[1];\n if (!token) {\n throw new Error(\"Invalid authorization format\");\n }\n\n const verified = await this.verifyToken(token);\n if (!verified) {\n throw new Error(\"Token verification failed\");\n }\n\n const user = this.extractUserFromVerification(verified);\n if (!user) {\n throw new Error(\"Invalid credentials\");\n }\n\n if (!this.config.skipCredentialVerification) {\n const credentialExists = await this.verifyCredentialExists(\n user.address,\n user.chainId,\n verified.issuer,\n );\n if (!credentialExists) {\n throw new Error(\"Credentials no longer valid\");\n }\n }\n\n // Note: We no longer block based on global allowed lists.\n // Authorization is handled at the resolver level based on document permissions.\n\n return user;\n }\n\n /** {@inheritDoc ICredentialInvalidator.invalidateCredential} */\n invalidateCredential(\n address: string,\n chainId?: number,\n appDid?: string,\n ): number {\n const normalized = address.toLowerCase();\n let evicted = 0;\n for (const [key, entry] of this.credentialCache) {\n if (\n entry.address === normalized &&\n (chainId === undefined || entry.chainId === chainId) &&\n (appDid === undefined || entry.appId === appDid)\n ) {\n this.credentialCache.delete(key);\n evicted++;\n }\n }\n const invalidation: CredentialInvalidation = { address: normalized };\n if (chainId !== undefined) invalidation.chainId = chainId;\n if (appDid !== undefined) invalidation.appDid = appDid;\n for (const listener of this.invalidationListeners) {\n try {\n listener(invalidation);\n } catch {\n // A listener's failure must not stop the eviction reaching the rest.\n }\n }\n return evicted;\n }\n\n /** Called after every `invalidateCredential`; returns an unsubscribe. */\n onCredentialInvalidated(\n listener: CredentialInvalidationListener,\n ): () => void {\n this.invalidationListeners.add(listener);\n return () => {\n this.invalidationListeners.delete(listener);\n };\n }\n\n /**\n * Whether an already-authenticated principal's credential still holds, for\n * re-checking long-lived connections. Goes through the same cache as\n * admission, so it costs at most one verifier call per identity per TTL.\n */\n async isCredentialValid(user: User): Promise<boolean> {\n if (this.config.skipCredentialVerification) {\n return true;\n }\n return this.verifyCredentialExists(user.address, user.chainId, user.appKey);\n }\n\n /**\n * Verify the auth bearer token\n */\n private async verifyToken(token: string) {\n return await verifyAuthBearerToken(token);\n }\n\n /**\n * Extract user information from verification result.\n *\n * The issuer is required along with the credential subject. A credential that\n * verified must carry one -- resolving it is how the signature was checked --\n * so this rejects a shape that cannot have come from verification rather than\n * admitting a keyless principal.\n */\n private extractUserFromVerification(\n verified: VerifiedCredential,\n ): User | null {\n try {\n const { address, chainId, networkId } =\n verified.verifiableCredential.credentialSubject;\n const appKey = verified.issuer;\n\n if (!address || !chainId || !networkId || !appKey) {\n return null;\n }\n\n return {\n address,\n chainId,\n networkId,\n appKey,\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Verify that the credential still exists on the Renown API.\n *\n * Results are cached per (address, chainId, issuer) for a short TTL so the\n * blocking external round-trip is not paid on every request. Concurrent\n * checks for the same key share a single in-flight request, and entries\n * that resolve to false are evicted immediately so failed or revoked\n * credentials are re-checked on the next request.\n */\n private verifyCredentialExists(\n address: string,\n chainId: number,\n appId: string,\n ): Promise<boolean> {\n const ttlMs =\n this.config.credentialVerificationCacheTtlMs ??\n DEFAULT_CREDENTIAL_CACHE_TTL_MS;\n if (ttlMs <= 0) {\n return this.fetchCredentialExists(address, chainId, appId);\n }\n\n const key = `${address.toLowerCase()}:${chainId}:${appId}`;\n const now = Date.now();\n const cached = this.credentialCache.get(key);\n if (cached && cached.expiresAt > now) {\n return cached.exists;\n }\n\n this.pruneCredentialCache(now);\n const entry: CredentialCacheEntry = {\n exists: this.fetchCredentialExists(address, chainId, appId).then(\n (exists) => {\n if (!exists && this.credentialCache.get(key) === entry) {\n this.credentialCache.delete(key);\n }\n return exists;\n },\n ),\n expiresAt: now + ttlMs,\n address: address.toLowerCase(),\n chainId,\n appId,\n };\n this.credentialCache.set(key, entry);\n return entry.exists;\n }\n\n /**\n * Enforce the cache size cap before inserting a new entry: drop expired\n * entries first, then evict oldest-inserted entries (insertion order\n * matches expiry order since the TTL is constant) until under the cap, so\n * a flood of distinct keys cannot grow the map without bound.\n */\n private pruneCredentialCache(now: number): void {\n if (this.credentialCache.size < CREDENTIAL_CACHE_MAX_ENTRIES) {\n return;\n }\n for (const [key, entry] of this.credentialCache) {\n if (entry.expiresAt <= now) {\n this.credentialCache.delete(key);\n }\n }\n while (this.credentialCache.size >= CREDENTIAL_CACHE_MAX_ENTRIES) {\n const oldestKey = this.credentialCache.keys().next().value;\n if (oldestKey === undefined) {\n break;\n }\n this.credentialCache.delete(oldestKey);\n }\n }\n\n // Confirm the signer's credential is still valid via the injected verifier.\n // Reached only when verification is on, so a missing verifier is misconfig.\n private async fetchCredentialExists(\n address: string,\n chainId: number,\n appId: string,\n ): Promise<boolean> {\n if (!this.config.verifyCredential) {\n throw new Error(\n \"AuthService: credential verification is enabled but no verifyCredential was provided\",\n );\n }\n return this.config.verifyCredential({ address, chainId, appId });\n }\n}\n","import type {\n IReactorReadClient,\n IReactorWriteClient,\n} from \"@powerhousedao/reactor\";\nimport type { GraphQLResolveInfo } from \"graphql\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\n/**\n * The reactor client halves a resolver may use, carried on the GraphQL\n * context as `ctx.clients`.\n */\nexport interface RequestClients {\n /** Answers from read models; always present. */\n readonly read: IReactorReadClient;\n /**\n * Enqueues writes. Present while a mutation executes; reading it in a query\n * or a subscription throws {@link WriteClientUnavailableError}.\n */\n readonly write: IReactorWriteClient;\n}\n\n/**\n * The operation a context was built for. `unbound` is a context the host\n * built before it knew the operation, which may not write either.\n */\nexport type ClientOperation = \"query\" | \"mutation\" | \"subscription\" | \"unbound\";\n\n/** A resolver outside a mutation asked for the write client. */\nexport class WriteClientUnavailableError extends Error {\n readonly operation: ClientOperation;\n readonly field: string | undefined;\n\n constructor(operation: ClientOperation, field: string | undefined) {\n const where = field ? `field ${field}` : \"this resolver\";\n const running =\n operation === \"unbound\" ? \"outside a mutation\" : `in a ${operation}`;\n super(\n `ctx.clients.write is only available to Mutation fields; ${where} runs ${running}. Read through ctx.clients.read.`,\n );\n this.name = \"WriteClientUnavailableError\";\n this.operation = operation;\n this.field = field;\n }\n\n static isError(error: unknown): error is WriteClientUnavailableError {\n return (\n error instanceof Error && error.name === \"WriteClientUnavailableError\"\n );\n }\n}\n\n/** The field whose resolver is running, so a refusal can name it. */\nconst executingField = new AsyncLocalStorage<string>();\n\nconst operations = new WeakMap<RequestClients, ClientOperation>();\n\n/**\n * The clients for one operation: both halves for a mutation, the read half\n * and a refusing `write` for anything else. The refusing property is not\n * enumerable, so spreading or printing the clients does not trip it.\n */\nexport function createRequestClients(\n read: IReactorReadClient,\n write: IReactorWriteClient,\n operation: ClientOperation,\n): RequestClients {\n let clients: RequestClients;\n if (operation === \"mutation\") {\n clients = Object.freeze({ read, write });\n } else {\n const gated = { read } as { read: IReactorReadClient };\n Object.defineProperty(gated, \"write\", {\n enumerable: false,\n get(): never {\n throw new WriteClientUnavailableError(\n operation,\n executingField.getStore(),\n );\n },\n });\n clients = Object.freeze(gated) as RequestClients;\n }\n operations.set(clients, operation);\n return clients;\n}\n\n/**\n * The read half alone, for a context nobody bound to an operation (a resolver\n * called directly rather than through the GraphQL layer). `write` refuses.\n */\nexport function readOnlyClients(read: IReactorReadClient): RequestClients {\n return createRequestClients(read, UNAVAILABLE_WRITE, \"unbound\");\n}\n\n/** Never reached: a non-mutation client set refuses before handing it out. */\nconst UNAVAILABLE_WRITE = {} as IReactorWriteClient;\n\n/**\n * Both halves for a field that reads write-side state outside a mutation. The\n * clients still report `operation`, so identifiers resolve on the read side.\n */\nfunction createWriteSideClients(\n read: IReactorReadClient,\n write: IReactorWriteClient,\n operation: ClientOperation,\n): RequestClients {\n const clients: RequestClients = Object.freeze({ read, write });\n operations.set(clients, operation);\n return clients;\n}\n\n/**\n * The operation the clients were built for, or undefined for clients that\n * {@link createRequestClients} did not build (a hand-made pair in a test).\n */\nexport function operationOfClients(\n clients: RequestClients | undefined,\n): ClientOperation | undefined {\n return clients === undefined ? undefined : operations.get(clients);\n}\n\ntype ClientsContext = { clients: RequestClients };\n\ntype FieldResolver = (\n parent: unknown,\n args: unknown,\n context: unknown,\n info: GraphQLResolveInfo,\n) => unknown;\n\ntype TypeResolver = (\n value: unknown,\n context: unknown,\n info: GraphQLResolveInfo,\n) => unknown;\n\n/**\n * A resolver map's own object, as opposed to a scalar or another class\n * instance, which passes through. Checked by prototype rather than with\n * `isScalarType`, which refuses a scalar from another copy of graphql.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/** Type-level resolvers that receive the context; each is `(value, ctx, info)`. */\nconst TYPE_LEVEL_RESOLVERS = new Set([\n \"__resolveReference\",\n \"__resolveType\",\n \"__isTypeOf\",\n]);\n\n/**\n * Puts the client halves on the GraphQL context per operation. The host builds\n * one context per request (or per WebSocket operation) before it knows what\n * the operation is; every resolver this binder wraps receives instead a\n * context derived from that one for the operation it is running in, so a\n * mutation gets `ctx.clients.write` and a query or subscription does not.\n *\n * The derived context is memoized per request context and operation, so every\n * field of one operation sees the same object, which per-request memos key on.\n */\nexport class RequestClientBinder {\n readonly #read: IReactorReadClient;\n readonly #write: IReactorWriteClient;\n readonly #contexts = new WeakMap<object, Map<string, ClientsContext>>();\n readonly #derived = new WeakSet<object>();\n readonly #wrapped = new WeakMap<object, Record<string, unknown>>();\n\n constructor(read: IReactorReadClient, write: IReactorWriteClient) {\n this.#read = read;\n this.#write = write;\n }\n\n /** The clients for a context the host builds before the operation is known. */\n unboundClients(): RequestClients {\n return createRequestClients(this.#read, this.#write, \"unbound\");\n }\n\n /**\n * The context a resolver of `operation` receives for request context `base`.\n * `writeSide` hands a query field the write client too: a field declared to\n * read write-side state.\n */\n contextFor<TContext extends object>(\n base: TContext,\n operation: ClientOperation,\n writeSide = false,\n ): TContext & ClientsContext {\n if (this.#derived.has(base)) {\n return base as TContext & ClientsContext;\n }\n let byOperation = this.#contexts.get(base);\n if (!byOperation) {\n byOperation = new Map();\n this.#contexts.set(base, byOperation);\n }\n const key = writeSide ? `${operation}:write-side` : operation;\n let derived = byOperation.get(key);\n if (!derived) {\n derived = {\n ...base,\n clients: writeSide\n ? createWriteSideClients(this.#read, this.#write, operation)\n : createRequestClients(this.#read, this.#write, operation),\n };\n this.#derived.add(derived);\n byOperation.set(key, derived);\n }\n return derived as TContext & ClientsContext;\n }\n\n /**\n * A copy of a subgraph's resolver map whose resolvers receive the context\n * for their operation. Scalars, enums and non-function members pass through.\n * `writeSideFields` names the fields (`Type.field`) handed the write client\n * whatever their operation. The copy is memoized per map.\n */\n bindResolvers<TResolvers extends Record<string, unknown>>(\n resolvers: TResolvers,\n writeSideFields: ReadonlySet<string> = new Set(),\n ): TResolvers {\n const cached = this.#wrapped.get(resolvers);\n if (cached) {\n return cached as TResolvers;\n }\n const bound: Record<string, unknown> = {};\n for (const [typeName, typeResolvers] of Object.entries(resolvers)) {\n bound[typeName] = this.#bindType(\n typeName,\n typeResolvers,\n writeSideFields,\n );\n }\n this.#wrapped.set(resolvers, bound);\n return bound as TResolvers;\n }\n\n #bindType(\n typeName: string,\n typeResolvers: unknown,\n writeSideFields: ReadonlySet<string>,\n ): unknown {\n if (!isPlainObject(typeResolvers)) {\n return typeResolvers;\n }\n const bound: Record<string, unknown> = {};\n for (const [field, value] of Object.entries(typeResolvers)) {\n const writeSide = writeSideFields.has(`${typeName}.${field}`);\n if (typeof value === \"function\") {\n bound[field] = TYPE_LEVEL_RESOLVERS.has(field)\n ? this.#bindTypeResolver(value as TypeResolver)\n : field.startsWith(\"__\")\n ? value\n : this.#bindFieldResolver(value as FieldResolver, writeSide);\n } else if (isPlainObject(value)) {\n const config = { ...(value as Record<string, unknown>) };\n for (const key of [\"resolve\", \"subscribe\"]) {\n if (typeof config[key] === \"function\") {\n config[key] = this.#bindFieldResolver(\n config[key] as FieldResolver,\n writeSide,\n );\n }\n }\n bound[field] = config;\n } else {\n bound[field] = value;\n }\n }\n return bound;\n }\n\n #bindFieldResolver(\n resolver: FieldResolver,\n writeSide: boolean,\n ): FieldResolver {\n return (parent, args, context, info) => {\n if (!info?.operation) {\n return resolver(parent, args, context, info);\n }\n const derived = this.contextFor(\n (context ?? {}) as object,\n info.operation.operation as ClientOperation,\n writeSide,\n );\n return executingField.run(\n `${info.parentType.name}.${info.fieldName}`,\n () => resolver(parent, args, derived, info),\n );\n };\n }\n\n #bindTypeResolver(resolver: TypeResolver): TypeResolver {\n return (value, context, info) => {\n if (!info?.operation) {\n return resolver(value, context, info);\n }\n return resolver(\n value,\n this.contextFor(\n (context ?? {}) as object,\n info.operation.operation as ClientOperation,\n ),\n info,\n );\n };\n }\n}\n","import type {\n IReactorClient,\n IReactorReadClient,\n IRelationalDb,\n ISyncManager,\n SyncScopeGate,\n ViewFilter,\n} from \"@powerhousedao/reactor\";\nimport type { IAttachmentClient } from \"@powerhousedao/reactor-attachments/client\";\nimport type { AuthSubject } from \"@powerhousedao/shared/document-model\";\nimport type {\n GraphQLManager,\n ISubgraph,\n SubgraphArgs,\n} from \"@powerhousedao/reactor-api\";\nimport type { DocumentNode } from \"graphql\";\nimport { ForbiddenError, AuthenticationRequiredError } from \"./errors.js\";\nimport { gql } from \"graphql-tag\";\nimport {\n AuthorizationPolicy,\n AuthorizedDocumentHandle,\n type CanonicalDocumentId,\n type IAuthorizationService,\n} from \"../services/authorization.service.js\";\nimport { createCanonicalDocumentIdResolver } from \"../services/canonical-document-id.js\";\nimport type { IAttachmentClientProvider } from \"../services/authorized-attachment.service.js\";\nimport type { DocumentPermissionService } from \"../services/document-permission.service.js\";\nimport {\n createCredentialInvalidator,\n type ICredentialInvalidator,\n} from \"../services/auth.service.js\";\nimport {\n operationOfClients,\n readOnlyClients,\n type RequestClients,\n} from \"./request-clients.js\";\nimport type { Context } from \"./types.js\";\n\n/**\n * Stands in for a client the subgraph was not given: any use names what to\n * use instead rather than failing on `undefined`.\n */\nfunction missingClient<TClient extends object>(\n name: string,\n hint: string,\n): TClient {\n return new Proxy({} as TClient, {\n get(_target, property) {\n if (property === \"then\" || typeof property === \"symbol\") {\n return undefined;\n }\n throw new Error(`${name}.${String(property)}: ${hint}`);\n },\n });\n}\n\n/**\n * The subject a request reads as: its address and the app key its token\n * carries. Anonymous is an empty subject, never the host's signer.\n */\nexport function callerSubject(user: Context[\"user\"]): AuthSubject {\n return { address: user?.address, key: user?.appKey };\n}\n\nexport class BaseSubgraph implements ISubgraph {\n name = \"example\";\n // The host's base path as injected by the GraphQL manager. Routing\n // ignores it: the manager mounts every subgraph under its own base path.\n path = \"\";\n resolvers: Record<string, any> = {\n Query: {\n hello: () => this.name,\n },\n };\n typeDefs: DocumentNode = gql`\n type Query {\n hello: String\n }\n `;\n /**\n * The read half, for setup-time use (schema building, model lookup).\n * Resolvers read through `ctx.clients.read` instead.\n */\n readonly readClient: IReactorReadClient;\n /**\n * @deprecated The facade over both halves, for subgraphs that have not\n * moved. Resolvers use `ctx.clients.read` and, in a mutation,\n * `ctx.clients.write`; setup-time code uses {@link readClient}.\n */\n reactorClient: IReactorClient;\n /** This package's namespaced slice of the HTTP surface. */\n readonly http: SubgraphArgs[\"http\"];\n graphqlManager: GraphQLManager;\n relationalDb: IRelationalDb;\n syncManager: ISyncManager;\n documentPermissionService?: DocumentPermissionService;\n authorizationService: IAuthorizationService;\n syncServingGate?: SyncScopeGate;\n /**\n * The host's credential cache, for a package that revokes credentials:\n * call `this.credentials.invalidateCredential(address, chainId?, appDid?)`\n * right after the revocation is stored, so this host refuses the credential\n * on the next request and closes WebSocket connections that rely on it.\n * A no-op on a host without authentication.\n */\n readonly credentials: ICredentialInvalidator;\n\n /**\n * Per-request memo of raw identifier to canonical document id, keyed on the\n * request context object so entries are released when the request ends. Lets\n * batch resolvers resolve each distinct identifier at most once.\n */\n readonly #canonicalIdMemo = new WeakMap<\n object,\n Map<string, CanonicalDocumentId>\n >();\n\n readonly #unboundClients: RequestClients;\n\n readonly #attachments?: IAttachmentClientProvider;\n\n readonly #attachmentClientMemo = new WeakMap<object, IAttachmentClient>();\n\n constructor(args: SubgraphArgs) {\n // A facade without halves (an older implementation, a mock) is itself a\n // read client.\n const facadeRead = args.reactorClient?.read as\n | Partial<IReactorReadClient>\n | undefined;\n this.readClient =\n args.readClient ??\n (typeof facadeRead?.get === \"function\"\n ? (facadeRead as IReactorReadClient)\n : args.reactorClient) ??\n missingClient<IReactorReadClient>(\n \"BaseSubgraph.readClient\",\n \"this subgraph was constructed without a readClient.\",\n );\n this.reactorClient =\n args.reactorClient ??\n missingClient<IReactorClient>(\n \"BaseSubgraph.reactorClient\",\n \"this host passes no reactorClient facade. Read through ctx.clients.read (or this.readClient at setup) and write through ctx.clients.write in a mutation.\",\n );\n this.#unboundClients = readOnlyClients(this.readClient);\n this.http = args.http;\n this.graphqlManager = args.graphqlManager;\n this.relationalDb = args.relationalDb;\n this.syncManager = args.syncManager;\n this.documentPermissionService = args.documentPermissionService;\n this.authorizationService = args.authorizationService;\n this.syncServingGate = args.syncServingGate;\n this.path = args.path ?? \"\";\n this.#attachments = args.attachments;\n this.credentials =\n args.credentials ?? createCredentialInvalidator(undefined);\n }\n\n /**\n * An attachment client bound to this request's caller, memoized per request.\n *\n * @throws Error when the host provides no attachment client to subgraphs.\n */\n attachmentsFor(ctx: Context): IAttachmentClient {\n if (!this.#attachments) {\n throw new Error(\"This host provides no attachment client to subgraphs\");\n }\n let client = this.#attachmentClientMemo.get(ctx);\n if (!client) {\n client = this.#attachments.forSubject(callerSubject(ctx.user));\n this.#attachmentClientMemo.set(ctx, client);\n }\n return client;\n }\n\n /**\n * The clients this request's operation may use: those the GraphQL layer put\n * on the context. A context it never saw (a resolver called directly) reads\n * through {@link readClient} and may not write.\n */\n clientsOf(ctx: Context | undefined): RequestClients {\n return ctx?.clients ?? this.#unboundClients;\n }\n\n async onSetup() {\n // noop\n }\n\n async onDisconnect(): Promise<void> {\n // noop\n }\n\n // ============================================\n // Shared permission helpers\n // ============================================\n\n /**\n * Resolves a caller-supplied identifier (id or slug) to its canonical\n * document id, memoized per request. Both the decision layer and the data\n * layer must agree on the subject, so this runs the lookup the data path\n * uses: `resolveIdOrSlug` on the read half for a query, `describe` on the\n * write half for a mutation. A resolution failure (not found, ambiguous, or\n * transient) surfaces as a generic Forbidden, fail-closed, so a bad\n * identifier cannot be used as a document-existence oracle.\n */\n async resolveCanonicalDocumentId(\n identifier: string,\n requestKey: object,\n ): Promise<CanonicalDocumentId> {\n let cache = this.#canonicalIdMemo.get(requestKey);\n if (!cache) {\n cache = new Map<string, CanonicalDocumentId>();\n this.#canonicalIdMemo.set(requestKey, cache);\n }\n\n const cached = cache.get(identifier);\n if (cached !== undefined) return cached;\n\n const clients = this.clientsOf(requestKey as Context);\n const resolve =\n operationOfClients(clients) === \"mutation\"\n ? createCanonicalDocumentIdResolver(\n { read: clients.read, write: clients.write },\n \"mutation\",\n )\n : createCanonicalDocumentIdResolver({ read: clients.read }, \"query\");\n let canonical: CanonicalDocumentId;\n try {\n canonical = await resolve(identifier);\n } catch {\n throw new ForbiddenError();\n }\n\n cache.set(identifier, canonical);\n return canonical;\n }\n\n /**\n * Resolves the args' `documentId` to canonical form. Unconditional (unlike the\n * assertCan* helpers, no admin skip): ACL rows are keyed on the canonical id.\n */\n async withCanonicalDocumentId<T extends { documentId: string }>(\n args: T,\n requestKey: object,\n ): Promise<T & { documentId: CanonicalDocumentId }> {\n const documentId = await this.resolveCanonicalDocumentId(\n args.documentId,\n requestKey,\n );\n return { ...args, documentId };\n }\n\n /**\n * Resolves an identifier for a per-document check, or null when the caller has\n * policy-wide access (OPEN or supreme admin) and the check can be skipped.\n * Only DOCUMENT_PERMISSIONS keys on the document id, so other policies fail\n * closed without resolving.\n */\n async #resolveForCheck(\n identifier: string,\n ctx: Context,\n ): Promise<CanonicalDocumentId | null> {\n if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) {\n return null;\n }\n if (\n this.authorizationService.config.policy !==\n AuthorizationPolicy.DOCUMENT_PERMISSIONS\n ) {\n throw new ForbiddenError();\n }\n return this.resolveCanonicalDocumentId(identifier, ctx);\n }\n\n /**\n * Read filter for an already-canonical document id (one sourced from the data\n * layer, such as a fetched document's id). Performs no slug resolution.\n */\n async canReadDocument(\n documentId: CanonicalDocumentId,\n ctx: Context,\n ): Promise<boolean> {\n return this.authorizationService.canRead(documentId, ctx.user?.address);\n }\n\n /** Drops the items the host's own ACL refuses the caller. */\n async readableByHost<T extends { id: string }>(\n items: readonly T[],\n ctx: Context,\n ): Promise<T[]> {\n if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) {\n return [...items];\n }\n const readable: T[] = [];\n for (const item of items) {\n if (await this.canReadDocument(item.id as CanonicalDocumentId, ctx)) {\n readable.push(item);\n }\n }\n return readable;\n }\n\n /**\n * The principal a request decides as: the authenticated caller's address, and\n * the did:key of the app instance whose token authenticated it.\n *\n * Both, because a policy can name either. The key is what a document records\n * as its creator, so a subject built without one cannot match the creator's\n * standing permission over the auth scope -- the document's own creator would\n * be refused an operation the write path accepts, since a signed action\n * carries the same key. Anonymous callers supply neither.\n */\n protected viewSubject(ctx: Context): AuthSubject {\n return callerSubject(ctx.user);\n }\n\n /** Whether a listing would serve the document to the caller; fails closed. */\n protected async servesDocument(\n documentId: string,\n ctx: Context,\n ): Promise<boolean> {\n if (!documentId) {\n return false;\n }\n try {\n return await this.servesDocumentOrThrows(documentId, ctx);\n } catch {\n return false;\n }\n }\n\n /** {@link servesDocument}, but a reactor that cannot answer throws. */\n protected servesDocumentOrThrows(\n identifier: string,\n ctx: Context,\n view?: Pick<ViewFilter, \"branch\" | \"scopes\">,\n ): Promise<boolean> {\n return this.clientsOf(ctx).read.isServed(identifier, {\n ...view,\n subject: this.viewSubject(ctx),\n });\n }\n\n /**\n * Whether a listing would serve the document to the caller: the reactor read\n * gate, then the host's legacy layer, as `findDocuments` applies them. Absent\n * or withheld is `false`; a failure to decide throws.\n */\n protected async listsDocument(\n identifier: string,\n ctx: Context,\n view?: Pick<ViewFilter, \"branch\" | \"scopes\">,\n ): Promise<boolean> {\n if (!(await this.servesDocumentOrThrows(identifier, ctx, view))) {\n return false;\n }\n if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) {\n return true;\n }\n return this.canReadDocument(\n await this.resolveCanonicalDocumentId(identifier, ctx),\n ctx,\n );\n }\n\n /**\n * Asserts read access, resolving a slug first. Returns a handle whose\n * `fetchIdentifier` the caller reuses for the data fetch; a denial throws.\n */\n async assertCanRead(\n identifier: string,\n ctx: Context,\n ): Promise<AuthorizedDocumentHandle> {\n const documentId = await this.#resolveForCheck(identifier, ctx);\n if (documentId === null)\n return AuthorizedDocumentHandle.skipped(identifier);\n await this.assertCanReadCanonical(documentId, ctx);\n return AuthorizedDocumentHandle.resolved(documentId);\n }\n\n async assertCanWrite(\n identifier: string,\n ctx: Context,\n ): Promise<AuthorizedDocumentHandle> {\n const documentId = await this.#resolveForCheck(identifier, ctx);\n if (documentId === null)\n return AuthorizedDocumentHandle.skipped(identifier);\n await this.assertCanWriteCanonical(documentId, ctx);\n return AuthorizedDocumentHandle.resolved(documentId);\n }\n\n async assertCanExecuteOperation(\n identifier: string,\n operationType: string,\n ctx: Context,\n ): Promise<AuthorizedDocumentHandle> {\n const documentId = await this.#resolveForCheck(identifier, ctx);\n if (documentId === null)\n return AuthorizedDocumentHandle.skipped(identifier);\n await this.assertCanExecuteOperationCanonical(\n documentId,\n operationType,\n ctx,\n );\n return AuthorizedDocumentHandle.resolved(documentId);\n }\n\n /**\n * Read assertion for an already-canonical document id. No slug resolution;\n * use only with ids sourced from the data layer or already resolved.\n */\n async assertCanReadCanonical(\n documentId: CanonicalDocumentId,\n ctx: Context,\n ): Promise<void> {\n const canRead = await this.authorizationService.canRead(\n documentId,\n ctx.user?.address,\n );\n if (!canRead) {\n throw new ForbiddenError(\"to read this document\");\n }\n }\n\n async assertCanWriteCanonical(\n documentId: CanonicalDocumentId,\n ctx: Context,\n ): Promise<void> {\n const canWrite = await this.authorizationService.canWrite(\n documentId,\n ctx.user?.address,\n );\n if (!canWrite) {\n throw new ForbiddenError(\"to write to this document\");\n }\n }\n\n async assertCanExecuteOperationCanonical(\n documentId: CanonicalDocumentId,\n operationType: string,\n ctx: Context,\n ): Promise<void> {\n const canMutate = await this.authorizationService.canMutate(\n documentId,\n operationType,\n ctx.user?.address,\n );\n if (!canMutate) {\n throw new ForbiddenError(\n `to execute operation \"${operationType}\" on this document`,\n );\n }\n }\n\n assertCanCreate(ctx: Context): void {\n if (this.authorizationService.canCreate(ctx.user?.address)) return;\n if (ctx.user?.address) {\n throw new ForbiddenError(\"to create documents\");\n }\n throw new AuthenticationRequiredError(\"to create documents\");\n }\n}\n","import path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\n/**\n * Imports a specifier that may be either a bare package specifier or a\n * filesystem path. Absolute paths are converted to file:// URLs, because the\n * ESM loader reads the drive letter in a Windows path as a URL scheme\n * (`import('D:\\\\...')` fails with ERR_UNSUPPORTED_ESM_URL_SCHEME).\n */\nasync function importSpecifier<T>(target: string): Promise<T> {\n const specifier = path.isAbsolute(target)\n ? pathToFileURL(target).href\n : target;\n return (await import(/* @vite-ignore */ specifier)) as T;\n}\n\n/**\n * Attempts to import from suggested Node.js paths\n */\nasync function tryNodeSuggestedPaths<T>(\n packageName: string,\n subPath: string,\n): Promise<T | null> {\n const suggestedPaths = [\n `${packageName}/dist/node/${subPath}/index.mjs`,\n `${packageName}/dist/node/${subPath}.mjs`,\n `${packageName}/dist/${subPath}/index.js`,\n `${packageName}/dist/${subPath}.js`,\n ];\n\n for (const suggestedPath of suggestedPaths) {\n try {\n return await importSpecifier<T>(suggestedPath);\n } catch {\n // Continue to next attempt\n }\n }\n\n return null;\n}\n\n/**\n * Attempts to resolve package using import.meta.resolve\n */\nasync function tryImportMetaResolve<T>(\n packageName: string,\n subPath: string,\n): Promise<T | null> {\n try {\n const resolvedUrl = import.meta.resolve?.(`${packageName}/package.json`);\n if (!resolvedUrl) return null;\n\n // fileURLToPath, not URL.pathname: the latter yields \"/D:/...\" on Windows.\n const packageRoot = path.dirname(fileURLToPath(resolvedUrl));\n const pathsToTry = [\n path.join(packageRoot, \"dist\", \"node\", subPath, \"index.mjs\"),\n path.join(packageRoot, \"dist\", \"node\", `${subPath}.mjs`),\n path.join(packageRoot, \"dist\", subPath, \"index.js\"),\n path.join(packageRoot, \"dist\", `${subPath}.js`),\n path.join(packageRoot, subPath, \"index.js\"),\n path.join(packageRoot, `${subPath}.js`),\n ];\n\n for (const attemptPath of pathsToTry) {\n try {\n return await importSpecifier<T>(attemptPath);\n } catch {\n // Continue to next attempt\n }\n }\n } catch {\n // import.meta.resolve failed\n }\n\n return null;\n}\n\n/**\n * Resolves symlinks in node_modules to find the real package location\n */\nasync function resolveSymlinkedPaths(\n packageName: string,\n subPath: string,\n): Promise<string[]> {\n const packageBaseName = packageName.includes(\"/\")\n ? packageName.split(\"/\").pop()\n : packageName;\n const nodeModulesPatterns = [\n path.join(process.cwd(), \"node_modules\", packageName),\n path.join(process.cwd(), \"node_modules\", packageBaseName || packageName),\n ];\n\n const workspacePatterns: string[] = [];\n\n for (const nodeModulesPath of nodeModulesPatterns) {\n try {\n const fs = await import(\"node:fs\");\n if (fs.existsSync(nodeModulesPath)) {\n const realPath = fs.realpathSync(nodeModulesPath);\n\n workspacePatterns.push(\n path.join(realPath, \"dist\", \"node\", subPath, \"index.mjs\"),\n path.join(realPath, \"dist\", \"node\", `${subPath}.mjs`),\n path.join(realPath, \"dist\", subPath, \"index.js\"),\n path.join(realPath, \"dist\", `${subPath}.js`),\n path.join(realPath, subPath, \"index.js\"),\n path.join(realPath, `${subPath}.js`),\n );\n }\n } catch {\n // Continue to next attempt\n }\n }\n\n return workspacePatterns;\n}\n\n/**\n * Generates common workspace pattern paths\n */\nfunction getCommonWorkspacePaths(\n packageName: string,\n subPath: string,\n): string[] {\n const packageBaseName = packageName.includes(\"/\")\n ? packageName.split(\"/\").pop()\n : packageName;\n const commonRoots = [process.cwd(), path.dirname(process.cwd())];\n\n const workspacePatterns: string[] = [];\n for (const root of commonRoots) {\n workspacePatterns.push(\n path.join(\n root,\n \"packages\",\n packageBaseName || packageName,\n \"dist\",\n \"node\",\n subPath,\n \"index.mjs\",\n ),\n path.join(\n root,\n \"packages\",\n packageBaseName || packageName,\n \"dist\",\n \"node\",\n `${subPath}.mjs`,\n ),\n path.join(\n root,\n \"packages\",\n packageBaseName || packageName,\n \"dist\",\n subPath,\n \"index.js\",\n ),\n path.join(\n root,\n \"packages\",\n packageBaseName || packageName,\n \"dist\",\n `${subPath}.js`,\n ),\n );\n }\n\n return workspacePatterns;\n}\n\n/**\n * Attempts to import from a list of workspace patterns\n */\nasync function tryWorkspacePatterns<T>(patterns: string[]): Promise<T | null> {\n for (const workspacePath of patterns) {\n try {\n return await importSpecifier<T>(workspacePath);\n } catch {\n // Continue to next attempt\n }\n }\n\n return null;\n}\n\n/**\n * Attempts to resolve linked packages using various fallback strategies\n */\nexport async function resolveLinkedPackage<T>(\n packageName: string,\n subPath: string,\n): Promise<T | null> {\n // Try Node.js suggested paths first\n let result = await tryNodeSuggestedPaths<T>(packageName, subPath);\n if (result) return result;\n\n // Try import.meta.resolve\n result = await tryImportMetaResolve<T>(packageName, subPath);\n if (result) return result;\n\n // Try symlink resolution\n const symlinkPaths = await resolveSymlinkedPaths(packageName, subPath);\n result = await tryWorkspacePatterns<T>(symlinkPaths);\n if (result) return result;\n\n // Try common workspace patterns as final fallback\n const commonPaths = getCommonWorkspacePaths(packageName, subPath);\n result = await tryWorkspacePatterns<T>(commonPaths);\n if (result) return result;\n\n return null;\n}\n","import type {\n ProcessorFactoryBuilder,\n SubgraphClass,\n} from \"@powerhousedao/reactor-api\";\nimport type {\n DocumentModelModule,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { childLogger } from \"document-model\";\nimport { execSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { resolveLinkedPackage } from \"./import-resolver.js\";\n\n// Define the expected module export structures\ntype DocumentModelsExport = Record<string, DocumentModelModule>;\ntype SubgraphsExport = Record<string, Record<string, SubgraphClass>>;\ntype ProcessorsExport = {\n processorFactory?: ProcessorFactoryBuilder;\n processorFactoryLegacy?: ProcessorFactoryBuilder;\n};\n\nconst _logger = childLogger([\"reactor-api\", \"packages/util\"]);\n\n// Error code for a package module that exists and failed to load; already logged.\nexport const PACKAGE_MODULE_FAILED = \"ERR_PACKAGE_MODULE_FAILED\";\n\nexport const installPackages = (packages: string[]): Promise<void> => {\n for (const packageName of packages) {\n execSync(`ph install ${packageName}`);\n }\n return Promise.resolve();\n};\n\nexport const readManifest = () => {\n const manifest = execSync(`ph manifest`).toString();\n return manifest;\n};\n\n/**\n * Tries to import document models from a package. This function cannot throw.\n */\nexport async function loadDocumentModels(\n packageName: string,\n): Promise<DocumentModelsExport | null> {\n return loadDependency(packageName, \"document-models\");\n}\n\n/**\n * Tries to import subgraphs from a package. This function cannot throw.\n */\nexport async function loadSubgraphs(\n packageName: string,\n): Promise<SubgraphsExport | null> {\n return loadDependency(packageName, \"subgraphs\");\n}\n\n/**\n * Tries to import processors from a package. This function cannot throw.\n */\nexport async function loadProcessors(\n packageName: string,\n): Promise<ProcessorsExport | null> {\n return loadDependency(packageName, \"processors\");\n}\n\n/**\n * Generic dependency loader - tries to import a dependency from a package. This function cannot throw.\n * Returns null if the dependency cannot be loaded.\n */\nasync function loadDependency<T = unknown>(\n packageName: string,\n subPath: string,\n): Promise<T> {\n // A local package is identified by an absolute path, which has to become a\n // file:// URL: the ESM loader reads the drive letter in a Windows path as a\n // URL scheme.\n const fullPath = path.isAbsolute(packageName)\n ? pathToFileURL(path.join(packageName, subPath)).href\n : `${packageName}/${subPath}`;\n\n // Try the standard import first\n try {\n // vite does not support this, but that's okay as we have provided the\n // vite-loader for this purpose\n\n const module = (await import(/* @vite-ignore */ fullPath)) as T;\n return module;\n } catch (e) {\n // Handle module not found errors with fallback resolution.\n // ERR_UNSUPPORTED_ESM_URL_SCHEME joins the list because a directory\n // specifier that is a plain path fails with it on Windows where POSIX\n // reports ERR_UNSUPPORTED_DIR_IMPORT.\n if (\n e instanceof Error &&\n \"code\" in e &&\n (e.code === \"ERR_MODULE_NOT_FOUND\" ||\n e.code === \"ERR_UNSUPPORTED_DIR_IMPORT\" ||\n e.code === \"ERR_UNSUPPORTED_ESM_URL_SCHEME\")\n ) {\n const result = await resolveLinkedPackage<T>(packageName, subPath);\n if (result) return result;\n }\n throw e;\n }\n}\n\n/**\n * The subgraphs a package's `powerhouse.manifest.json` declares, when the\n * manifest is reachable — which it is for a package identified by an\n * absolute path (how every local project reaches the loaders). Lets the\n * package manager warn when a manifest promises subgraphs and the loaders\n * deliver none, instead of failing silently. For a bare package name the\n * manifest would have to be resolved through the module system; until a\n * caller needs that, a bare name answers [] rather than guessing.\n */\nexport function manifestDeclaredSubgraphs(identifier: string): string[] {\n if (!path.isAbsolute(identifier)) return [];\n try {\n const raw = readFileSync(\n path.join(identifier, \"powerhouse.manifest.json\"),\n \"utf-8\",\n );\n const manifest = JSON.parse(raw) as { subgraphs?: unknown };\n if (!Array.isArray(manifest.subgraphs)) return [];\n return manifest.subgraphs\n .map((subgraph: unknown) => {\n if (typeof subgraph !== \"object\" || subgraph === null) {\n return undefined;\n }\n const { id, name } = subgraph as { id?: unknown; name?: unknown };\n return id ?? name;\n })\n .filter(\n (value): value is string =>\n typeof value === \"string\" && value.length > 0,\n );\n } catch {\n // No manifest, or an unreadable one: nothing was promised, so nothing\n // to warn about.\n return [];\n }\n}\n\nfunction isUpgradeManifest(\n value: unknown,\n): value is UpgradeManifest<readonly number[]> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"documentType\" in value &&\n \"supportedVersions\" in value &&\n \"upgrades\" in value\n );\n}\n\n/**\n * Collects upgrade manifests from a package's document-models namespace.\n * Handles both the aggregate `upgradeManifests` array export and individual\n * manifest exports; dedupes by documentType.\n */\nexport function extractUpgradeManifests(\n namespace: Record<string, unknown>,\n): UpgradeManifest<readonly number[]>[] {\n const manifests = new Map<string, UpgradeManifest<readonly number[]>>();\n const add = (value: unknown) => {\n if (isUpgradeManifest(value)) {\n manifests.set(value.documentType, value);\n }\n };\n for (const value of Object.values(namespace)) {\n if (Array.isArray(value)) {\n value.forEach(add);\n } else {\n add(value);\n }\n }\n return Array.from(manifests.values());\n}\n\n/** Calls superseded before the timer fires settle with the run that follows. */\nexport function debounce<R>(func: () => Promise<R>, delay = 250) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let waiting: {\n resolve: (value: R) => void;\n reject: (error: unknown) => void;\n }[] = [];\n\n const run = async () => {\n timer = undefined;\n const callers = waiting;\n waiting = [];\n try {\n const value = await func();\n callers.forEach((caller) => caller.resolve(value));\n } catch (error) {\n callers.forEach((caller) => caller.reject(error));\n }\n };\n\n return (immediate = false): Promise<R> => {\n clearTimeout(timer);\n return new Promise<R>((resolve, reject) => {\n waiting.push({ resolve, reject });\n if (immediate) {\n void run();\n } else {\n timer = setTimeout(() => void run(), delay);\n }\n });\n };\n}\n\nexport function isSubpath(parent: string, dir: string) {\n const relative = path.relative(parent, dir);\n return relative && !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n}\n","import type { ILogger } from \"document-model\";\n\nexport type ReportError = (error: unknown) => void;\n\nexport type RunDetachedOptions = {\n logger: ILogger;\n report?: ReportError;\n};\n\n/** Logs `error` as the message's last replacement and reports it. */\nexport function reportFailure(\n { logger, report }: RunDetachedOptions,\n error: unknown,\n message: string,\n ...args: unknown[]\n): void {\n logger.error(message, ...args, error);\n try {\n report?.(error);\n } catch (reportError) {\n logger.error(\"Reporting a failure failed: @error\", reportError);\n }\n}\n\n/** Runs work nobody awaits: a failure is logged and reported, never thrown. */\nexport async function runDetached(\n label: string,\n task: () => unknown,\n options: RunDetachedOptions,\n): Promise<void> {\n try {\n await task();\n } catch (error) {\n reportFailure(options, error, \"@label failed: @error\", label);\n }\n}\n","import type {\n GqlDocument,\n GqlDriveDocument,\n GqlOperation,\n SubgraphClass,\n} from \"@powerhousedao/reactor-api\";\nimport type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport type {\n Operation,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { BaseSubgraph } from \"./base-subgraph.js\";\n\nexport function isSubgraphClass(\n candidate: unknown,\n): candidate is SubgraphClass {\n if (typeof candidate !== \"function\") return false;\n\n // Walk the candidate's constructor chain. Identity first: package builds\n // keep `@powerhousedao/reactor-api` external precisely so every subgraph\n // extends this very BaseSubgraph (see nodeNeverBundle in\n // packages/shared/clis/build-config.mts). The name check is the fallback\n // for a module graph that carries its own copy — a project served by the\n // vite dev server resolves reactor-api from its own node_modules, which\n // need not be the host's instance.\n //\n // The previous version asked `isPrototypeOf` in the wrong direction\n // (whether the candidate's proto was in BaseSubgraph's chain), which\n // `Function.prototype` always satisfies — so every function passed, and\n // junk exports registered as subgraphs.\n let proto: unknown = Object.getPrototypeOf(candidate);\n while (typeof proto === \"function\") {\n if (proto === BaseSubgraph) return true;\n if (proto.name === \"BaseSubgraph\") return true;\n\n proto = Object.getPrototypeOf(proto);\n }\n\n return false;\n}\n\nexport function buildGraphqlOperations(\n operations: Operation[],\n skip: number,\n first: number,\n): GqlOperation[] {\n return operations.slice(skip, skip + first).map(buildGraphqlOperation);\n}\n\nexport function buildGraphqlOperation(operation: Operation): GqlOperation {\n const signer = operation.action.context?.signer;\n return {\n id: operation.id ?? \"\",\n type: operation.action.type,\n index: operation.index,\n timestampUtcMs: operation.timestampUtcMs,\n hash: operation.hash,\n skip: operation.skip,\n inputText:\n typeof operation.action.input === \"string\"\n ? operation.action.input\n : JSON.stringify(operation.action.input),\n error: operation.error,\n context: {\n signer: signer\n ? {\n user: signer.user,\n app: signer.app,\n signatures: signer.signatures.map((sig) =>\n Array.isArray(sig) ? sig.join(\", \") : sig,\n ),\n }\n : undefined,\n },\n };\n}\n\nexport function buildGraphQlDocument(doc: PHDocument): GqlDocument {\n // Return full state with all scopes (auth, document, global, local)\n // This matches the ReactorSubgraph pattern in adapters.ts\n const state = doc.state;\n const initialState = doc.initialState;\n // For stateJSON, use global state for backward compatibility\n const globalState = \"global\" in doc.state ? doc.state.global : {};\n return {\n id: doc.header.id,\n name: doc.header.name,\n documentType: doc.header.documentType,\n revision: doc.header.revision.global || 0,\n createdAtUtcIso: doc.header.createdAtUtcIso,\n lastModifiedAtUtcIso: doc.header.lastModifiedAtUtcIso,\n operations: [],\n stateJSON: globalState as JSON,\n state,\n initialState,\n };\n}\n\nexport function buildGraphQlDriveDocument(\n doc: DocumentDriveDocument,\n): GqlDriveDocument {\n const gqlDoc = buildGraphQlDocument(doc);\n return {\n ...gqlDoc,\n meta: {\n preferredEditor: doc.header.meta?.preferredEditor,\n },\n slug: doc.header.slug,\n state: doc.state.global,\n initialState: doc.state.global,\n };\n}\n","import type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\n\n/**\n * The one acceptance rule for a package's `document-models` module.\n *\n * The three package loaders duck-typed this independently and disagreed on\n * one case: the http loader required `documentModel` to be non-null, while\n * the import and vite loaders accepted any object merely carrying the key,\n * so an export shaped `{ documentModel: null }` registered as a model under\n * two loaders and vanished under the third. The strict rule is the correct\n * one — a module without its documentModel cannot define a document type —\n * and this predicate is now the single rule all three share, the same way\n * extractSubgraphs unified the subgraph rule.\n */\nexport function isDocumentModelModule(\n candidate: unknown,\n): candidate is DocumentModelModule {\n if (candidate === null || typeof candidate !== \"object\") return false;\n if (!(\"documentModel\" in candidate)) return false;\n const model = (candidate as { documentModel: unknown }).documentModel;\n return model !== null && model !== undefined;\n}\n\n/** Collects the document-model modules among a namespace's exports. */\nexport function extractDocumentModels(\n namespace: Record<string, unknown>,\n): DocumentModelModule[] {\n return Object.values(namespace).filter(isDocumentModelModule);\n}\n","// The pieces a package ships, located on disk for a host that never runs them.\n\n// Only the list module is ever imported here: it holds no piece code, and a\n// piece itself runs in a forked worker, handed the path this reports.\nimport { packageJsonExports } from \"@powerhousedao/shared/clis/constants\";\nimport type { ILogger } from \"document-model\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, isAbsolute, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { PackagePiece, PackagePieceEntry } from \"./types.js\";\n\n/** The sub-entry every loader asks a package for its pieces through. */\nexport const PIECES_SUBPATH = \"pieces\";\n\n// Where the node build leaves the list, read from the export map a generated\n// package ships so the build and the host cannot disagree about the path.\nexport const BUILT_PIECE_LIST = packageJsonExports[\"./pieces\"].node;\n\n/** Where a package keeps its piece sources, for telling unbuilt from absent. */\nexport const PIECE_SOURCE_LIST = join(PIECES_SUBPATH, \"index.ts\");\n\n/** The nearest enclosing package.json, which `exports` usually hides. */\nexport function packageRootOf(dir: string): string | undefined {\n let current = dir;\n while (!existsSync(join(current, \"package.json\"))) {\n const parent = dirname(current);\n if (parent === current) return undefined;\n current = parent;\n }\n return current;\n}\n\nexport interface PieceListLocation {\n /** Absolute; a declared entry is relative to it. */\n root: string;\n /** Absolute path of the list module, built or not. */\n listPath: string;\n}\n\n// Resolved from this module first, then from the host's own dependencies,\n// which is where document models are found too; the first error is the one kept.\nfunction resolvePieceList(specifier: string, hostDir: string): string {\n try {\n return fileURLToPath(import.meta.resolve(specifier));\n } catch (error) {\n try {\n return createRequire(join(hostDir, \"package.json\")).resolve(specifier);\n } catch {\n throw error;\n }\n }\n}\n\n// Where a package's piece list sits and what its entries are relative to. A\n// path identifier is its own root; a name resolves as a host would import it.\nexport function pieceListLocation(\n identifier: string,\n hostDir = process.cwd(),\n): PieceListLocation {\n if (isAbsolute(identifier)) {\n return { root: identifier, listPath: join(identifier, BUILT_PIECE_LIST) };\n }\n // Left to throw, with the ESM resolver's error codes: they're what the\n // package manager reads a miss from.\n const listPath = resolvePieceList(`${identifier}/${PIECES_SUBPATH}`, hostDir);\n const root = packageRootOf(dirname(listPath));\n if (!root) {\n throw new Error(`No package.json above ${listPath}`);\n }\n return { root, listPath };\n}\n\n// A piece's version is its package's, so it is read from the package root.\nexport function packageVersionAt(root: string): string | undefined {\n try {\n const pkg = JSON.parse(\n readFileSync(join(root, \"package.json\"), \"utf8\"),\n ) as { version?: unknown };\n return typeof pkg.version === \"string\" && pkg.version !== \"\"\n ? pkg.version\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n// A declared piece counts only once its code is on disk: one nobody built is\n// reported rather than dropped, because a block type names it either way.\nexport function locatePieces(\n declared: readonly PackagePiece[],\n context: {\n root: string;\n identifier: string;\n logger: ILogger;\n version: string;\n },\n): PackagePieceEntry[] {\n const { root, identifier, logger, version } = context;\n const located: PackagePieceEntry[] = [];\n for (const piece of declared) {\n const where = piece.entry ?? piece.bundle;\n if (typeof where !== \"string\" || where === \"\") {\n // Every name goes through a logger value: `@`-prefixed tokens are\n // substituted, so a scoped one printed inline comes out as null/pack.\n logger.warn(\n \"Piece @piece of @pkg declares neither a bundle nor an entry\",\n piece.name,\n identifier,\n );\n continue;\n }\n const path = isAbsolute(where) ? where : join(root, where);\n const present = piece.entry\n ? existsSync(path)\n : existsSync(join(path, \"package.json\"));\n if (!present) {\n logger.warn(\n \"Piece @piece of @pkg is declared but not built at @path\",\n piece.name,\n identifier,\n path,\n );\n continue;\n }\n located.push({\n name: piece.name,\n version,\n ...(piece.entry ? { entryPath: path } : { bundleDir: path }),\n });\n }\n return located;\n}\n\n// A package's `pieces` array, however the list module was obtained.\nfunction declaredPieces(\n module: unknown,\n identifier: string,\n logger: ILogger,\n): PackagePiece[] | undefined {\n const namespace = (module ?? {}) as { pieces?: unknown; default?: unknown };\n const declared = namespace.pieces ?? namespace.default;\n if (!Array.isArray(declared)) {\n logger.warn(\n 'The pieces list of @pkg exports no \"pieces\" array; it contributes none',\n identifier,\n );\n return undefined;\n }\n return declared as PackagePiece[];\n}\n\n// The same list, served by a registry rather than read off a disk. Nothing is\n// checked for existence here: the CDN is asked when the piece is run.\n\n// `entry` is relative to the package root while the CDN serves beneath\n// `dist/`, so that prefix comes off before the base is applied.\nexport function piecesFromCdnList(\n module: unknown,\n baseUrl: string,\n identifier: string,\n logger: ILogger,\n version: string,\n): PackagePieceEntry[] {\n const declared = declaredPieces(module, identifier, logger);\n if (!declared) return [];\n const located: PackagePieceEntry[] = [];\n for (const piece of declared) {\n const where = piece.entry ?? piece.bundle;\n if (typeof where !== \"string\" || where === \"\") {\n logger.warn(\n \"Piece @piece of @pkg declares neither a bundle nor an entry\",\n piece.name,\n identifier,\n );\n continue;\n }\n located.push({\n name: piece.name,\n version,\n entryUrl: `${baseUrl}${where.replace(/^dist\\/node\\/pieces\\//, \"\")}`,\n });\n }\n return located;\n}\n\n// What a loaded list module contributes. A module without a `pieces` array is\n// not a list, and saying so beats reporting the package as shipping none.\nexport function piecesFromListModule(\n module: unknown,\n context: { root: string; identifier: string; logger: ILogger },\n): PackagePieceEntry[] {\n const namespace = (module ?? {}) as { pieces?: unknown; default?: unknown };\n const declared = namespace.pieces ?? namespace.default;\n if (!Array.isArray(declared)) {\n context.logger.warn(\n 'The pieces list of @pkg exports no \"pieces\" array; it contributes none',\n context.identifier,\n );\n return [];\n }\n const version = packageVersionAt(context.root);\n if (!version) {\n context.logger.warn(\n \"@pkg has no version in @root/package.json, and a piece takes its package's version; its pieces contribute none\",\n context.identifier,\n context.root,\n );\n return [];\n }\n return locatePieces(declared as PackagePiece[], { ...context, version });\n}\n","import type { SubgraphClass } from \"@powerhousedao/reactor-api\";\nimport { isSubgraphClass } from \"../graphql/utils.js\";\n\n/**\n * The one acceptance rule for a package's `subgraphs` module.\n *\n * All three package loaders (vite, import, http) consume the same generated\n * `subgraphs/index` file, and each used to apply its own rule — the vite\n * loader required a namespace whose alias equalled the class name inside it,\n * the http loader took any function one level deep, and the import loader\n * took every nested value. An export that registered under one loader could\n * silently vanish under another (the codegen-does-not-register-subgraphs\n * report). This is now the single rule they all share:\n *\n * - an export that is itself a subgraph class is accepted (named or default\n * export of the class);\n * - any subgraph class among the values of an exported object is accepted\n * (a `export * as Alias from ...` namespace under any alias, or a\n * default-exported object of classes);\n * - everything else — constants, configs, functions and classes that do not\n * extend BaseSubgraph — is dropped.\n *\n * Codegen emits `export * as <ClassName> from \"./<dir>/index.js\"`\n * (makeSubgraphsIndexFile in packages/codegen), which the namespace branch\n * accepts regardless of the alias; hand-written packages may re-export a\n * class directly, which the direct branch accepts. A class reached through\n * both branches is returned once.\n */\nexport function extractSubgraphs(\n namespace: Record<string, unknown>,\n): SubgraphClass[] {\n const found: SubgraphClass[] = [];\n const add = (candidate: unknown) => {\n if (isSubgraphClass(candidate) && !found.includes(candidate)) {\n found.push(candidate);\n }\n };\n for (const value of Object.values(namespace)) {\n add(value);\n if (value !== null && typeof value === \"object\") {\n for (const inner of Object.values(value)) {\n add(inner);\n }\n }\n }\n return found;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAOA,IAAa,iBAAb,cAAoC,aAAa;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