@powerhousedao/reactor-api 6.2.3-dev.64 → 6.2.3-dev.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/{adapter-gateway-apollo-DwAmdCYz.mjs → adapter-gateway-apollo-D-EdZ4e-.mjs} +10 -12
  2. package/dist/adapter-gateway-apollo-D-EdZ4e-.mjs.map +1 -0
  3. package/dist/{adapter-gateway-mercurius-BhO0nwH_.mjs → adapter-gateway-mercurius-CdxLge5p.mjs} +3 -11
  4. package/dist/adapter-gateway-mercurius-CdxLge5p.mjs.map +1 -0
  5. package/dist/{base-document-models-69WRTSfH.mjs → base-document-models-uUQKgXcf.mjs} +176 -4
  6. package/dist/base-document-models-uUQKgXcf.mjs.map +1 -0
  7. package/dist/{create-schema-DLTPkNpK.d.mts → create-schema-BUk-IQCT.d.mts} +16 -10
  8. package/dist/create-schema-BUk-IQCT.d.mts.map +1 -0
  9. package/dist/index.d.mts +15 -14
  10. package/dist/index.d.mts.map +1 -1
  11. package/dist/index.mjs +832 -361
  12. package/dist/index.mjs.map +1 -1
  13. package/dist/package-subgraph-check-CsTPajAN.mjs +137 -0
  14. package/dist/package-subgraph-check-CsTPajAN.mjs.map +1 -0
  15. package/dist/{pglite-node-Ow9i5Rb4.mjs → pglite-node-C-UQXrjU.mjs} +8 -5
  16. package/dist/{pglite-node-Ow9i5Rb4.mjs.map → pglite-node-C-UQXrjU.mjs.map} +1 -1
  17. package/dist/src/graphql/subgraph-types.d.mts +17 -11
  18. package/dist/src/graphql/subgraph-types.d.mts.map +1 -1
  19. package/dist/src/graphql/subgraph-types.mjs +8 -99
  20. package/dist/src/graphql/subgraph-types.mjs.map +1 -1
  21. package/dist/src/packages/vite-loader.d.mts +1 -1
  22. package/dist/src/packages/vite-loader.d.mts.map +1 -1
  23. package/dist/src/packages/vite-loader.mjs +34 -44
  24. package/dist/src/packages/vite-loader.mjs.map +1 -1
  25. package/dist/src/pglite/pglite-node.d.mts.map +1 -1
  26. package/dist/src/pglite/pglite-node.mjs +3 -3
  27. package/dist/{subgraph-extraction-CcgWd0De.mjs → subgraph-extraction-cSpPp3Hq.mjs} +5 -4
  28. package/dist/{subgraph-extraction-CcgWd0De.mjs.map → subgraph-extraction-cSpPp3Hq.mjs.map} +1 -1
  29. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs +10 -0
  30. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs.map +1 -0
  31. package/dist/{types-D3pD6fvQ.d.mts → types-CCI5IDgT.d.mts} +4 -5
  32. package/dist/{types-D3pD6fvQ.d.mts.map → types-CCI5IDgT.d.mts.map} +1 -1
  33. package/package.json +13 -13
  34. package/dist/adapter-gateway-apollo-DTcAJpfN.mjs +0 -4
  35. package/dist/adapter-gateway-apollo-DwAmdCYz.mjs.map +0 -1
  36. package/dist/adapter-gateway-mercurius-BhO0nwH_.mjs.map +0 -1
  37. package/dist/adapter-gateway-stitching-969ZPot-.mjs +0 -4
  38. package/dist/adapter-gateway-stitching-ClVkjojb.mjs +0 -333
  39. package/dist/adapter-gateway-stitching-ClVkjojb.mjs.map +0 -1
  40. package/dist/base-document-models-69WRTSfH.mjs.map +0 -1
  41. package/dist/create-schema-DLTPkNpK.d.mts.map +0 -1
  42. package/dist/websocket-_SH5aBcy.mjs +0 -18
  43. package/dist/websocket-_SH5aBcy.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,15 +1,15 @@
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]="061cb7f9-bbbc-55da-a218-225c0b3c993d")}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]="15ac44c0-1e9f-5725-b675-7e5e00ca51a4")}catch(e){}}();
3
3
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
4
- import { A as AuthorizationPolicy, C as manifestDeclaredSubgraphs, D as createCredentialInvalidator, E as AuthService, F as ForbiddenError, I as MalformedStoredOperationError, L as RefusalNotRecordedError, M as createAuthorizationService, N as AuthEvaluationUnsupportedError, O as CanonicalDocumentIdResolutionError, P as AuthenticationRequiredError, S as loadSubgraphs, T as callerSubject, _ as debounce, b as loadDocumentModels, c as piecesFromListModule, d as buildGraphQlDriveDocument, f as buildGraphqlOperation, g as runDetached, h as reportFailure, i as PIECE_SOURCE_LIST, j as AuthorizedDocumentHandle, k as createCanonicalDocumentIdResolver, l as extractDocumentModels, m as isSubgraphClass, o as pieceListLocation, p as buildGraphqlOperations, s as piecesFromCdnList, t as extractSubgraphs, u as buildGraphQlDocument, v as extractUpgradeManifests, w as BaseSubgraph, x as loadProcessors } from "./subgraph-extraction-CcgWd0De.mjs";
5
- import { C as hasOperationSchemas, D as schema_default$1, E as typeDefinitionNames, S as getGeneratedDocumentModelTypes, T as reservedTypeNamesTaken, _ as generateDocumentModelSchema, a as collectSubgraphClaims, b as getDocumentModelSubgraphName, c as DocumentModelSchemaCache, d as buildDocumentModelSchema, f as buildSubgraphSchemaModule, g as findSubgraphTypeCollisions, h as documentModelSubgraphTypes, i as inspectionTypeDefs, l as SubgraphTypeCollisionError, m as createSchema, n as systemTypeDefs, o as describeOwnershipConflicts, p as createMergedSchema, r as schema_default$2, s as resolveClaimOwnership, t as baseDocumentModels, u as assembleSubgraphTypeDefs, v as generatedTypesOf, w as reservedTypeNames, x as getDocumentModelTypeDefs, y as getDocumentModelSchemaName } from "./base-document-models-69WRTSfH.mjs";
6
- import { n as filterBuildableSubgraphs, r as mergeSubgraphSchemas } from "./adapter-gateway-stitching-ClVkjojb.mjs";
7
- import { l as createDurableNodeFs, n as openCurrentPgliteForVerify, r as preparePgliteDataDir, u as resolvePgliteFsync } from "./pglite-node-Ow9i5Rb4.mjs";
4
+ import { A as createCanonicalDocumentIdResolver, C as loadSubgraphs, D as AuthService, E as callerSubject, F as AuthenticationRequiredError, I as ForbiddenError, L as MalformedStoredOperationError, M as AuthorizedDocumentHandle, N as createAuthorizationService, O as createCredentialInvalidator, P as AuthEvaluationUnsupportedError, R as RefusalNotRecordedError, S as loadProcessors, T as BaseSubgraph, _ as PACKAGE_MODULE_FAILED, c as piecesFromListModule, d as buildGraphQlDriveDocument, f as buildGraphqlOperation, g as runDetached, h as reportFailure, i as PIECE_SOURCE_LIST, j as AuthorizationPolicy, k as CanonicalDocumentIdResolutionError, l as extractDocumentModels, m as isSubgraphClass, o as pieceListLocation, p as buildGraphqlOperations, s as piecesFromCdnList, t as extractSubgraphs, u as buildGraphQlDocument, v as debounce, w as manifestDeclaredSubgraphs, x as loadDocumentModels, y as extractUpgradeManifests } from "./subgraph-extraction-cSpPp3Hq.mjs";
5
+ import { A as getDocumentModelTypeDefs, C as createSchema, D as generatedTypesOf, E as generateDocumentModelSchema, F as typeDefinitionNames, I as schema_default$1, M as hasOperationSchemas, N as reservedTypeNames, O as getDocumentModelSchemaName, P as reservedTypeNamesTaken, S as createMergedSchema, T as findSubgraphTypeCollisions, _ as DocumentModelSchemaCache, a as CORE_ORIGIN, b as buildDocumentModelSchema, c as RegistrationOrder, d as decideAdmission, f as describeOrigin, g as describeOwnershipConflicts, h as collectSubgraphClaims, i as inspectionTypeDefs, j as getGeneratedDocumentModelTypes, k as getDocumentModelSubgraphName, l as admitDocumentModels, m as supergraphClaimLosers, n as systemTypeDefs, o as DOCUMENT_MODEL_ORIGIN, p as documentModelSubgraphSources, r as schema_default$2, s as HOST_ORIGIN, t as baseDocumentModels, u as byClaimPriority, v as SubgraphTypeCollisionError, w as documentModelSubgraphTypes, x as buildSubgraphSchemaModule, y as assembleSubgraphTypeDefs } from "./base-document-models-uUQKgXcf.mjs";
6
+ import { n as createApolloFetchHandler } from "./adapter-gateway-apollo-D-EdZ4e-.mjs";
7
+ import { l as createDurableNodeFs, n as openCurrentPgliteForVerify, r as preparePgliteDataDir, u as resolvePgliteFsync } from "./pglite-node-C-UQXrjU.mjs";
8
8
  import { findPackageJSON, isBuiltin } from "node:module";
9
9
  import { AnalyticsQueryEngine } from "@powerhousedao/analytics-engine-core";
10
10
  import { AnalyticsModel, AnalyticsResolvers, typedefs } from "@powerhousedao/analytics-engine-graphql";
11
11
  import { gql } from "graphql-tag";
12
- import { GraphQLError, Kind, OperationTypeNode, parse, print, valueFromASTUntyped, visit } from "graphql";
12
+ import { GraphQLError, Kind, OperationTypeNode, buildASTSchema, getOperationAST, isTypeDefinitionNode, isTypeExtensionNode, parse, print, validateSchema, valueFromASTUntyped, visit } from "graphql";
13
13
  import { AuthEnforcementDisabledError, BareReadGate, BatchJobFailedError, ChannelError, ChannelErrorSource, DEFAULT_DRIVE_CONTAINER_TYPES, DriveCollectionId, DriveInspection, InvalidDeadLetterCursorError, JOB_NOT_FOUND_ERROR_NAME, JobStatus, ModelReadGate, PropagationMode as PropagationMode$1, READ_ONLY_ACCESS, SyncOperation, SyncScopeGate, consolidateSyncOperations, createReactorHostModuleBase, createReactorInspector, driveIdFromUrl, envelopesToSyncOperations, parseDriveUrl, readDecisionModel, supportsPurgeRefusals, syncOperationErrorType, toWireDeadLetter, toWireQueueState } from "@powerhousedao/reactor";
14
14
  import { deserializeSignature, readPeerManifest, serializeSignature, setName, withSignaturePolicy } from "@powerhousedao/shared/document-model";
15
15
  import { fetchDelegationCredential, resolveSwitchboardEndpoint } from "@renown/sdk";
@@ -26,11 +26,18 @@ import { pathToFileURL } from "node:url";
26
26
  import { camelCase } from "change-case";
27
27
  import * as z$1 from "zod";
28
28
  import { z } from "zod";
29
+ import { ApolloServer } from "@apollo/server";
30
+ import { ApolloServerPluginInlineTraceDisabled } from "@apollo/server/plugin/disabled";
31
+ import { ApolloServerPluginLandingPageLocalDefault } from "@apollo/server/plugin/landingPage/default";
32
+ import { mergeResolvers, mergeTypeDefs } from "@graphql-tools/merge";
33
+ import { makeExecutableSchema } from "@graphql-tools/schema";
34
+ import { useServer } from "graphql-ws/use/ws";
29
35
  import { createHandler } from "graphql-sse/lib/use/fetch";
30
36
  import lzString from "lz-string";
31
37
  import { PubSub, withFilter } from "graphql-subscriptions";
32
38
  import dotenv from "dotenv";
33
39
  import { buildTreeUrl } from "@powerhousedao/shared";
40
+ import { resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
34
41
  import { init, parse as parse$1 } from "es-module-lexer";
35
42
  import { chmod, lstat, mkdir, readFile, readdir, readlink, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
36
43
  import { getConfig } from "@powerhousedao/config/node";
@@ -353,15 +360,15 @@ function createAuthFetchMiddleware(authService) {
353
360
  async function createGatewayAdapter(type, logger) {
354
361
  switch (type) {
355
362
  case "apollo": {
356
- const { ApolloGatewayAdapter } = await import("./adapter-gateway-apollo-DTcAJpfN.mjs");
363
+ const { ApolloGatewayAdapter } = await import("./adapter-gateway-apollo-D-EdZ4e-.mjs").then((n) => n.t);
357
364
  return new ApolloGatewayAdapter(logger);
358
365
  }
359
366
  case "mercurius": {
360
- const { MercuriusGatewayAdapter } = await import("./adapter-gateway-mercurius-BhO0nwH_.mjs");
367
+ const { MercuriusGatewayAdapter } = await import("./adapter-gateway-mercurius-CdxLge5p.mjs");
361
368
  return new MercuriusGatewayAdapter(logger);
362
369
  }
363
370
  case "stitching": {
364
- const { StitchingGatewayAdapter } = await import("./adapter-gateway-stitching-969ZPot-.mjs");
371
+ const { StitchingGatewayAdapter } = await Promise.resolve().then(() => adapter_gateway_stitching_exports);
365
372
  return new StitchingGatewayAdapter(logger);
366
373
  }
367
374
  }
@@ -4169,6 +4176,324 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
4169
4176
  }
4170
4177
  };
4171
4178
  //#endregion
4179
+ //#region src/graphql/gateway/adapter-gateway-stitching.ts
4180
+ var adapter_gateway_stitching_exports = /* @__PURE__ */ __exportAll({
4181
+ StitchingGatewayAdapter: () => StitchingGatewayAdapter,
4182
+ filterBuildableSubgraphs: () => filterBuildableSubgraphs,
4183
+ mergeSubgraphSchemas: () => mergeSubgraphSchemas,
4184
+ mergeSubgraphTypeDefs: () => mergeSubgraphTypeDefs
4185
+ });
4186
+ /** Root operation types, which a subgraph may extend without defining. */
4187
+ const ROOT_TYPE_NAMES = [
4188
+ "Query",
4189
+ "Mutation",
4190
+ "Subscription"
4191
+ ];
4192
+ /**
4193
+ * A placeholder declaration for a type name a subgraph borrows from another
4194
+ * subgraph. Same kind as the real declaration, so the borrowing subgraph's
4195
+ * SDL validates the same way it does in the merged supergraph:
4196
+ *
4197
+ * - scalar/enum/input/object: a minimal declaration of that kind.
4198
+ * - interface: the real declaration, because a subgraph that implements the
4199
+ * interface has to satisfy its field set.
4200
+ * - union: a self-contained union over one placeholder member, so nothing the
4201
+ * real declaration references has to be resolvable here.
4202
+ */
4203
+ function stubDeclaration(name, owner) {
4204
+ switch (owner?.kind) {
4205
+ case Kind.SCALAR_TYPE_DEFINITION: return `scalar ${name}`;
4206
+ case Kind.ENUM_TYPE_DEFINITION: return `enum ${name} { _STUB }`;
4207
+ case Kind.INPUT_OBJECT_TYPE_DEFINITION: return `input ${name} { _stub: Boolean }`;
4208
+ case Kind.INTERFACE_TYPE_DEFINITION: return print(owner);
4209
+ case Kind.UNION_TYPE_DEFINITION: return `type ${name}_Stub { _stub: Boolean } union ${name} = ${name}_Stub`;
4210
+ default: return `type ${name} { _stub: Boolean }`;
4211
+ }
4212
+ }
4213
+ /**
4214
+ * Drops subgraphs whose own typeDefs cannot be built into a valid schema, so
4215
+ * one malformed subgraph is excluded instead of failing the whole supergraph
4216
+ * build (which, since GraphQLManager.init() does not guard the supergraph
4217
+ * gateway, would be a boot failure). Each excluded subgraph is logged; the
4218
+ * rest are merged. This is the stitching counterpart of the federation path's
4219
+ * `filterComposableSubgraphs`.
4220
+ *
4221
+ * A stitching subgraph is not self-contained the way a federation subgraph is:
4222
+ * it may extend a root type it never defines (`analytics` only does
4223
+ * `extend type Query`) and reference types another subgraph owns (in raw form
4224
+ * `analytics` uses `DateTime`, declared by `auth`/`reactor`/`packages`).
4225
+ * Building it alone would therefore reject perfectly good subgraphs. So the isolation build adds
4226
+ * a placeholder declaration for every type name declared by some *other*
4227
+ * subgraph in the set, plus the root types, plus every directive definition in
4228
+ * the set. What is left to fail is the subgraph's own SDL: a dangling type
4229
+ * reference no subgraph declares, a duplicated field, an invalid implements
4230
+ * clause.
4231
+ *
4232
+ * Scope: like the federation filter, this only catches per-subgraph failures.
4233
+ * Errors that appear only once subgraphs are merged (a field type or type kind
4234
+ * clash) are reported by `mergeSubgraphTypeDefs`, not here.
4235
+ */
4236
+ function filterBuildableSubgraphs(subgraphs, logger, label = "Stitching gateway") {
4237
+ const owners = /* @__PURE__ */ new Map();
4238
+ const directiveDefs = /* @__PURE__ */ new Map();
4239
+ for (const subgraph of subgraphs) for (const def of subgraph.typeDefs.definitions) if (isTypeDefinitionNode(def) && !owners.has(def.name.value)) owners.set(def.name.value, def);
4240
+ else if (def.kind === Kind.DIRECTIVE_DEFINITION && !directiveDefs.has(def.name.value)) directiveDefs.set(def.name.value, def);
4241
+ return subgraphs.filter((subgraph) => {
4242
+ const own = /* @__PURE__ */ new Set();
4243
+ const ownDirectives = /* @__PURE__ */ new Set();
4244
+ for (const def of subgraph.typeDefs.definitions) if (isTypeDefinitionNode(def)) own.add(def.name.value);
4245
+ else if (def.kind === Kind.DIRECTIVE_DEFINITION) ownDirectives.add(def.name.value);
4246
+ const stubs = [];
4247
+ for (const name of /* @__PURE__ */ new Set([...owners.keys(), ...ROOT_TYPE_NAMES])) if (!own.has(name)) stubs.push(stubDeclaration(name, owners.get(name)));
4248
+ for (const [name, def] of directiveDefs) if (!ownDirectives.has(name)) stubs.push(print(def));
4249
+ try {
4250
+ const documents = stubs.length > 0 ? [subgraph.typeDefs, parse(stubs.join("\n"))] : [subgraph.typeDefs];
4251
+ const merged = mergeTypeDefs(documents, { useSchemaDefinition: false });
4252
+ const errors = validateSchema(buildASTSchema(merged));
4253
+ if (errors.length > 0) throw new Error(errors.map((error) => error.message).join("; "));
4254
+ return true;
4255
+ } catch (error) {
4256
+ logger?.error(`${label}: excluding subgraph "${subgraph.name}" from the supergraph: ${error instanceof Error ? error.message : String(error)}`);
4257
+ return false;
4258
+ }
4259
+ });
4260
+ }
4261
+ /**
4262
+ * The SDL keyword for a type definition or extension node, or undefined for a
4263
+ * node that does not declare a named type (schema definitions, directive
4264
+ * definitions, executable definitions). Extensions map to the same keyword as
4265
+ * their definition: `extend type Query` and `type Query` are the same kind.
4266
+ */
4267
+ function typeKeyword(def) {
4268
+ switch (def.kind) {
4269
+ case Kind.OBJECT_TYPE_DEFINITION:
4270
+ case Kind.OBJECT_TYPE_EXTENSION: return "type";
4271
+ case Kind.INTERFACE_TYPE_DEFINITION:
4272
+ case Kind.INTERFACE_TYPE_EXTENSION: return "interface";
4273
+ case Kind.UNION_TYPE_DEFINITION:
4274
+ case Kind.UNION_TYPE_EXTENSION: return "union";
4275
+ case Kind.ENUM_TYPE_DEFINITION:
4276
+ case Kind.ENUM_TYPE_EXTENSION: return "enum";
4277
+ case Kind.INPUT_OBJECT_TYPE_DEFINITION:
4278
+ case Kind.INPUT_OBJECT_TYPE_EXTENSION: return "input";
4279
+ case Kind.SCALAR_TYPE_DEFINITION:
4280
+ case Kind.SCALAR_TYPE_EXTENSION: return "scalar";
4281
+ default: return;
4282
+ }
4283
+ }
4284
+ /**
4285
+ * Finds type names that two subgraphs declare with different kinds (object vs
4286
+ * enum, input, interface or union). `mergeTypeDefs` does not call
4287
+ * `onFieldTypeConflict` for these - it keeps the last declaration and drops
4288
+ * the other subgraph's type entirely, with no diagnostic - so they are
4289
+ * scanned for before the merge and reported alongside field conflicts.
4290
+ */
4291
+ function scanTypeKindClashes(subgraphs) {
4292
+ const clashes = [];
4293
+ const declaredBy = /* @__PURE__ */ new Map();
4294
+ for (const subgraph of subgraphs) for (const def of subgraph.typeDefs.definitions) {
4295
+ if (!isTypeDefinitionNode(def) && !isTypeExtensionNode(def)) continue;
4296
+ const keyword = typeKeyword(def);
4297
+ if (keyword === void 0) continue;
4298
+ const name = def.name.value;
4299
+ const previous = declaredBy.get(name);
4300
+ if (previous === void 0) {
4301
+ declaredBy.set(name, {
4302
+ keyword,
4303
+ subgraph: subgraph.name
4304
+ });
4305
+ continue;
4306
+ }
4307
+ if (previous.keyword === keyword) continue;
4308
+ clashes.push(`type kind clash on ${name}: declared as ${previous.keyword} by subgraph "${previous.subgraph}" and as ${keyword} by subgraph "${subgraph.name}"; mergeTypeDefs keeps the last declaration (${keyword}) and drops the other, whatever the conflict policy`);
4309
+ declaredBy.set(name, {
4310
+ keyword,
4311
+ subgraph: subgraph.name
4312
+ });
4313
+ }
4314
+ return clashes;
4315
+ }
4316
+ /**
4317
+ * Merges all subgraph type definitions into one schema, applying the field
4318
+ * conflict policy. Exported so tests and the benchmark can exercise the merge
4319
+ * without a full adapter.
4320
+ */
4321
+ function mergeSubgraphTypeDefs(subgraphs, policy) {
4322
+ const conflicts = scanTypeKindClashes(subgraphs);
4323
+ return {
4324
+ typeDefs: mergeTypeDefs(subgraphs.map((s) => s.typeDefs), {
4325
+ useSchemaDefinition: false,
4326
+ onFieldTypeConflict: (existing, other, type) => {
4327
+ if (print(existing) === print(other)) return existing;
4328
+ const winner = policy === "first" ? existing : other;
4329
+ const loser = policy === "first" ? other : existing;
4330
+ conflicts.push(`field type clash on ${type.name.value}.${existing.name.value}: kept ${print(winner.type)} (${policy === "first" ? "first" : "last"} subgraph), dropped ${print(loser.type)}`);
4331
+ return winner;
4332
+ }
4333
+ }),
4334
+ conflicts
4335
+ };
4336
+ }
4337
+ /**
4338
+ * Merges the subgraph resolver maps in the order the conflict policy implies.
4339
+ * `mergeResolvers` is unconditionally last-wins, so under `"first"` the array
4340
+ * is reversed: the first-registered subgraph's resolver ends up applied last
4341
+ * and wins, matching the field type the merged schema advertises. Without
4342
+ * this the schema would advertise one subgraph's type while another
4343
+ * subgraph's resolver ran.
4344
+ */
4345
+ function mergeSubgraphResolvers(subgraphs, policy) {
4346
+ const ordered = policy === "first" ? [...subgraphs].reverse() : subgraphs;
4347
+ return mergeResolvers(ordered.map((s) => s.resolvers));
4348
+ }
4349
+ /**
4350
+ * Drops resolver entries that have no matching type or field in the merged
4351
+ * schema. Document-model subgraphs generate resolver entries for operations
4352
+ * their SDL does not declare (the federation runtime silently ignores those);
4353
+ * makeExecutableSchema rejects them, so they are filtered before the build.
4354
+ */
4355
+ function filterResolversToSchema(typeMap, resolvers, logger) {
4356
+ const filtered = {};
4357
+ for (const [typeName, entry] of Object.entries(resolvers)) {
4358
+ const type = typeMap[typeName];
4359
+ if (type === void 0) {
4360
+ logger?.debug(`Stitching gateway: dropped resolvers for type "${typeName}": the merged schema has no such type`);
4361
+ continue;
4362
+ }
4363
+ const fields = type instanceof Object && "getFields" in type ? type.getFields() : void 0;
4364
+ if (fields === void 0) {
4365
+ filtered[typeName] = entry;
4366
+ continue;
4367
+ }
4368
+ if (entry === null || typeof entry !== "object") {
4369
+ logger?.debug(`Stitching gateway: dropped resolver entry for type "${typeName}": expected a field map, got ${entry === null ? "null" : typeof entry}`);
4370
+ continue;
4371
+ }
4372
+ const map = entry;
4373
+ const kept = {};
4374
+ const dropped = [];
4375
+ for (const [key, value] of Object.entries(map)) if (key.startsWith("__") || fields[key] !== void 0) kept[key] = value;
4376
+ else dropped.push(key);
4377
+ if (dropped.length > 0) logger?.debug(`Stitching gateway: dropped resolvers ${dropped.map((field) => `${typeName}.${field}`).join(", ")}: the merged schema declares no such field(s)`);
4378
+ if (Object.keys(kept).length > 0) filtered[typeName] = kept;
4379
+ }
4380
+ return filtered;
4381
+ }
4382
+ /**
4383
+ * Builds the executable supergraph schema from merged type definitions and
4384
+ * resolvers (shared by the adapter and the pure merge helper).
4385
+ */
4386
+ function buildMergedSchema(typeDefs, resolvers, logger) {
4387
+ const filtered = filterResolversToSchema(buildASTSchema(typeDefs, { assumeValid: true }).getTypeMap(), resolvers, logger);
4388
+ return makeExecutableSchema({
4389
+ typeDefs,
4390
+ resolvers: filtered
4391
+ });
4392
+ }
4393
+ /**
4394
+ * Merges multiple subgraphs into a single in-process executable schema.
4395
+ * This is the "Guild" (graphql-tools) composition path: instead of federation
4396
+ * (which hard-fails on cross-subgraph type conflicts and executes subgraph
4397
+ * fields over loopback HTTP), the type definitions are merged with an
4398
+ * explicit conflict policy and the resolvers run in-process.
4399
+ */
4400
+ function mergeSubgraphSchemas(subgraphs, policy) {
4401
+ if (subgraphs.length === 0) throw new Error("Cannot merge zero subgraphs");
4402
+ const { typeDefs } = mergeSubgraphTypeDefs(subgraphs, policy);
4403
+ return buildMergedSchema(typeDefs, mergeSubgraphResolvers(subgraphs, policy));
4404
+ }
4405
+ /**
4406
+ * A stitching gateway adapter: the supergraph is one merged schema executed
4407
+ * in-process. Subgraph routes (`/graphql/<name>`) are served exactly like the
4408
+ * Apollo adapter, so direct subgraph access is unchanged.
4409
+ *
4410
+ * Note: unlike the Apollo adapter, the supergraph ApolloServer is NOT given
4411
+ * ApolloServerPluginDrainHttpServer. The plugin closes the (shared) HTTP
4412
+ * server on stop, which would kill every mounted subgraph route when
4413
+ * updateSupergraph() swaps the supergraph server. The shared server is drained
4414
+ * explicitly in stop() instead.
4415
+ */
4416
+ var StitchingGatewayAdapter = class {
4417
+ #logger;
4418
+ #policy;
4419
+ #servers = [];
4420
+ #supergraphServer = null;
4421
+ #handler = null;
4422
+ #httpServer = null;
4423
+ #getSubgraphs = null;
4424
+ #contextFactory = null;
4425
+ constructor(logger, options = {}) {
4426
+ this.#logger = logger;
4427
+ this.#policy = options.onFieldTypeConflict ?? "last";
4428
+ }
4429
+ async start(_httpServer) {}
4430
+ async createHandler(schema, contextFactory) {
4431
+ const server = await this.#makeServer(schema);
4432
+ this.#servers.push(server);
4433
+ return createApolloFetchHandler(server, contextFactory);
4434
+ }
4435
+ async createSupergraphHandler(getSubgraphs, httpServer, contextFactory) {
4436
+ if (this.#supergraphServer) throw new Error("Supergraph server is already running");
4437
+ this.#getSubgraphs = getSubgraphs;
4438
+ this.#httpServer = httpServer;
4439
+ this.#contextFactory = contextFactory;
4440
+ const server = await this.#buildSupergraphServer(getSubgraphs());
4441
+ return this.#installSupergraphServer(server);
4442
+ }
4443
+ async updateSupergraph() {
4444
+ if (!this.#getSubgraphs || !this.#contextFactory) return;
4445
+ const server = await this.#buildSupergraphServer(this.#getSubgraphs());
4446
+ const old = this.#supergraphServer;
4447
+ this.#installSupergraphServer(server);
4448
+ if (old) await old.stop();
4449
+ }
4450
+ async stop() {
4451
+ await Promise.all(this.#servers.map((s) => s.stop()));
4452
+ this.#servers.length = 0;
4453
+ if (this.#supergraphServer) {
4454
+ await this.#supergraphServer.stop();
4455
+ this.#supergraphServer = null;
4456
+ }
4457
+ this.#handler = null;
4458
+ this.#getSubgraphs = null;
4459
+ this.#contextFactory = null;
4460
+ const httpServer = this.#httpServer;
4461
+ this.#httpServer = null;
4462
+ if (httpServer?.listening) await new Promise((resolve) => httpServer.close(() => resolve()));
4463
+ }
4464
+ async #makeServer(schema) {
4465
+ const server = new ApolloServer({
4466
+ schema,
4467
+ logger: this.#logger,
4468
+ introspection: true,
4469
+ stopOnTerminationSignals: false,
4470
+ plugins: [ApolloServerPluginInlineTraceDisabled(), ApolloServerPluginLandingPageLocalDefault()]
4471
+ });
4472
+ await server.start();
4473
+ return server;
4474
+ }
4475
+ async #buildSupergraphServer(all) {
4476
+ let subgraphs = filterBuildableSubgraphs(all, this.#logger);
4477
+ if (subgraphs.length === 0 && all.length > 0) {
4478
+ this.#logger.error("Stitching gateway: every subgraph failed its isolation build; merging the unfiltered set so the underlying error surfaces");
4479
+ subgraphs = all;
4480
+ }
4481
+ const { typeDefs, conflicts } = mergeSubgraphTypeDefs(subgraphs, this.#policy);
4482
+ for (const conflict of conflicts) this.#logger.warn(`Stitching gateway (policy "${this.#policy}"): ${conflict}`);
4483
+ if (conflicts.length > 0) this.#logger.warn(`Stitching gateway: merged ${subgraphs.length} subgraphs with ${conflicts.length} schema conflict(s); each resolution is logged above`);
4484
+ else this.#logger.debug(`Stitching gateway: merged ${subgraphs.length} subgraphs without conflicts`);
4485
+ const schema = buildMergedSchema(typeDefs, mergeSubgraphResolvers(subgraphs, this.#policy), this.#logger);
4486
+ return this.#makeServer(schema);
4487
+ }
4488
+ #installSupergraphServer(server) {
4489
+ if (this.#contextFactory === null) throw new Error("Supergraph context factory not set");
4490
+ this.#supergraphServer = server;
4491
+ const handler = createApolloFetchHandler(server, this.#contextFactory);
4492
+ this.#handler = handler;
4493
+ return (request) => this.#handler(request);
4494
+ }
4495
+ };
4496
+ //#endregion
4172
4497
  //#region src/graphql/gateway/drive-middleware.ts
4173
4498
  const DRIVE_ID_HEADER = "drive-id";
4174
4499
  /**
@@ -4324,6 +4649,131 @@ var DriveOwnershipCache = class {
4324
4649
  }
4325
4650
  };
4326
4651
  //#endregion
4652
+ //#region src/graphql/subgraph-ws-router.ts
4653
+ /** One graphql-ws server; each operation goes to the first route whose root type has its fields. */
4654
+ var SubgraphWsRouter = class {
4655
+ #routes = /* @__PURE__ */ new Map();
4656
+ #operations = /* @__PURE__ */ new WeakMap();
4657
+ #order;
4658
+ #logger;
4659
+ #disposer;
4660
+ constructor(options) {
4661
+ this.#order = options.order;
4662
+ this.#logger = options.logger;
4663
+ }
4664
+ attach(wsServer, handlers) {
4665
+ if (this.#disposer) return;
4666
+ this.#disposer = useServer({
4667
+ onConnect: (ctx) => handlers.onConnect(ctx.connectionParams ?? {}, ctx.extra),
4668
+ context: (ctx) => handlers.context(ctx.connectionParams ?? {}, ctx.extra),
4669
+ onSubscribe: () => this.#routes.size === 0 ? [new GraphQLError("No subgraph serves subscriptions")] : void 0,
4670
+ schema: (ctx, id, _payload, args) => {
4671
+ const route = this.#route(args.document, args.operationName);
4672
+ if (!route) throw new Error("No subgraph serves subscriptions");
4673
+ this.#operationsOf(ctx).set(id, { route });
4674
+ return route.schema;
4675
+ },
4676
+ onOperation: (ctx, id, _payload, _args, result) => {
4677
+ const operation = this.#operations.get(ctx)?.get(id);
4678
+ if (!operation || !isAsyncGenerator$1(result)) return;
4679
+ operation.result = result;
4680
+ operation.route.running.add(result);
4681
+ if (operation.route.ended) this.#end([result]);
4682
+ },
4683
+ onComplete: (ctx, id) => {
4684
+ const operations = this.#operations.get(ctx);
4685
+ const operation = operations?.get(id);
4686
+ operations?.delete(id);
4687
+ if (operation?.result) operation.route.running.delete(operation.result);
4688
+ }
4689
+ }, wsServer);
4690
+ }
4691
+ /** Serve `owner`'s operations at `path` with `schema`. */
4692
+ set(path, owner, schema) {
4693
+ const route = this.#routes.get(path);
4694
+ if (route?.owner === owner) {
4695
+ route.schema = schema;
4696
+ return;
4697
+ }
4698
+ this.#routes.set(path, {
4699
+ owner,
4700
+ schema,
4701
+ running: /* @__PURE__ */ new Set(),
4702
+ ended: false
4703
+ });
4704
+ if (route) this.#endRoute(route);
4705
+ }
4706
+ /** Stop serving `path`, if `owner` still holds it. */
4707
+ delete(path, owner) {
4708
+ const route = this.#routes.get(path);
4709
+ if (route?.owner !== owner) return;
4710
+ this.#routes.delete(path);
4711
+ this.#endRoute(route);
4712
+ }
4713
+ async dispose() {
4714
+ const disposer = this.#disposer;
4715
+ this.#disposer = void 0;
4716
+ this.#routes.clear();
4717
+ await disposer?.dispose();
4718
+ }
4719
+ #route(document, operationName) {
4720
+ const routes = [...this.#routes.values()];
4721
+ const owners = this.#order([...new Set(routes.map((r) => r.owner))]);
4722
+ routes.sort((a, b) => owners.indexOf(a.owner) - owners.indexOf(b.owner));
4723
+ const operation = getOperationAST(document, operationName);
4724
+ if (!operation) return routes[0];
4725
+ const fields = rootFields(document, operation);
4726
+ return routes.find((route) => {
4727
+ const root = route.schema.getRootType(operation.operation);
4728
+ if (!root) return false;
4729
+ const available = root.getFields();
4730
+ return fields.every((field) => field in available);
4731
+ }) ?? routes[0];
4732
+ }
4733
+ #operationsOf(ctx) {
4734
+ let operations = this.#operations.get(ctx);
4735
+ if (!operations) {
4736
+ operations = /* @__PURE__ */ new Map();
4737
+ this.#operations.set(ctx, operations);
4738
+ }
4739
+ return operations;
4740
+ }
4741
+ #endRoute(route) {
4742
+ route.ended = true;
4743
+ this.#end(route.running);
4744
+ }
4745
+ async #end(results) {
4746
+ await Promise.all(Array.from(results, async (result) => {
4747
+ try {
4748
+ await result.return(void 0);
4749
+ } catch (error) {
4750
+ this.#logger.error("Error ending a WebSocket subscription: @error", error);
4751
+ }
4752
+ }));
4753
+ }
4754
+ };
4755
+ function isAsyncGenerator$1(value) {
4756
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value && typeof value.return === "function";
4757
+ }
4758
+ /** An operation's root field names, through fragments, without `__` fields. */
4759
+ function rootFields(document, operation) {
4760
+ const fragments = new Map(document.definitions.flatMap((definition) => definition.kind === Kind.FRAGMENT_DEFINITION ? [[definition.name.value, definition.selectionSet]] : []));
4761
+ const fields = /* @__PURE__ */ new Set();
4762
+ const visited = /* @__PURE__ */ new Set();
4763
+ const collect = (selectionSet) => {
4764
+ for (const selection of selectionSet.selections) if (selection.kind === Kind.FIELD) {
4765
+ if (!selection.name.value.startsWith("__")) fields.add(selection.name.value);
4766
+ } else if (selection.kind === Kind.INLINE_FRAGMENT) collect(selection.selectionSet);
4767
+ else if (!visited.has(selection.name.value)) {
4768
+ visited.add(selection.name.value);
4769
+ const fragment = fragments.get(selection.name.value);
4770
+ if (fragment) collect(fragment);
4771
+ }
4772
+ };
4773
+ collect(operation.selectionSet);
4774
+ return [...fields];
4775
+ }
4776
+ //#endregion
4327
4777
  //#region src/graphql/ws-credential-monitor.ts
4328
4778
  /** Default interval between credential re-checks of open WebSockets. */
4329
4779
  const DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS = 6e4;
@@ -4424,6 +4874,56 @@ function resolveWsCredentialRecheckIntervalMs(raw, logger) {
4424
4874
  }
4425
4875
  //#endregion
4426
4876
  //#region src/graphql/sse.ts
4877
+ /** Open SSE operations; `end()` completes them, and any that start later. */
4878
+ var SSEStreams = class {
4879
+ #running = /* @__PURE__ */ new Map();
4880
+ #retired = /* @__PURE__ */ new Set();
4881
+ #ended = false;
4882
+ track(result, tags = /* @__PURE__ */ new Set()) {
4883
+ const running = this.#running;
4884
+ const done = () => running.delete(tracked);
4885
+ const tracked = {
4886
+ [Symbol.asyncIterator]: () => tracked,
4887
+ next: async (...args) => {
4888
+ const step = await result.next(...args);
4889
+ if (step.done) done();
4890
+ return step;
4891
+ },
4892
+ return: (value) => {
4893
+ done();
4894
+ return result.return(value);
4895
+ },
4896
+ throw: (error) => {
4897
+ done();
4898
+ return result.throw(error);
4899
+ },
4900
+ [Symbol.asyncDispose]: async () => {
4901
+ done();
4902
+ await result.return(void 0);
4903
+ }
4904
+ };
4905
+ running.set(tracked, tags);
4906
+ if (this.#ended || [...tags].some((tag) => this.#retired.has(tag))) this.#end([tracked]);
4907
+ return tracked;
4908
+ }
4909
+ /**
4910
+ * Complete every stream, or those tagged `tag`, and any that start later
4911
+ * until `reopen()`. graphql-sse sends `complete` and closes each stream.
4912
+ */
4913
+ async end(tag) {
4914
+ if (tag === void 0) this.#ended = true;
4915
+ else this.#retired.add(tag);
4916
+ const results = [...this.#running].filter(([, tags]) => tag === void 0 || tags.has(tag)).map(([result]) => result);
4917
+ await this.#end(results);
4918
+ }
4919
+ /** Stop completing new streams for retired tags: the handler was rebuilt. */
4920
+ reopen() {
4921
+ this.#retired.clear();
4922
+ }
4923
+ async #end(results) {
4924
+ await Promise.allSettled(results.map((result) => result.return(void 0)));
4925
+ }
4926
+ };
4427
4927
  /**
4428
4928
  * Create a Fetch-API-compatible SSE handler for GraphQL subscriptions
4429
4929
  * using the graphql-sse library (graphql-sse protocol).
@@ -4441,13 +4941,19 @@ function resolveWsCredentialRecheckIntervalMs(raw, logger) {
4441
4941
  * because it adds token-management complexity with no benefit here.
4442
4942
  */
4443
4943
  function createGraphQLSSEHandler(options) {
4444
- const { schema, contextFactory } = options;
4944
+ const { schema, contextFactory, streams, tagsOf } = options;
4445
4945
  return createHandler({
4446
4946
  schema,
4447
4947
  authenticate: () => null,
4448
- context: (req) => contextFactory(req.raw)
4948
+ context: (req) => contextFactory(req.raw),
4949
+ onOperation: (_ctx, _req, args, result) => streams && isAsyncGenerator(result) ? streams.track(result, tagsOf?.(args)) : void 0
4449
4950
  });
4450
4951
  }
4952
+ const STREAM_ROOTS = [
4953
+ "Query",
4954
+ "Mutation",
4955
+ "Subscription"
4956
+ ];
4451
4957
  const FEDERATION_DIRECTIVES = /* @__PURE__ */ new Set([
4452
4958
  "authenticated",
4453
4959
  "composeDirective",
@@ -4469,58 +4975,93 @@ const FEDERATION_DIRECTIVES = /* @__PURE__ */ new Set([
4469
4975
  "shareable",
4470
4976
  "tag"
4471
4977
  ]);
4472
- function isFederationDirective(name, declared) {
4978
+ const FEDERATION_SPEC_URL = "https://specs.apollo.dev/federation/";
4979
+ function stringArgument(node, name) {
4980
+ const value = (node.kind === Kind.DIRECTIVE ? node.arguments : node.fields)?.find((arg) => arg.name.value === name)?.value;
4981
+ return value?.kind === Kind.STRING ? value.value : void 0;
4982
+ }
4983
+ function withoutAt(name) {
4984
+ return name.startsWith("@") ? name.slice(1) : void 0;
4985
+ }
4986
+ /** Includes names a federation `@link` imports under an alias or `as` prefix. */
4987
+ function federationNames(typeDefs) {
4988
+ const names = new Set(FEDERATION_DIRECTIVES);
4989
+ const prefixes = ["federation__"];
4990
+ for (const def of typeDefs.definitions) {
4991
+ if (def.kind !== Kind.SCHEMA_DEFINITION && def.kind !== Kind.SCHEMA_EXTENSION) continue;
4992
+ for (const link of def.directives ?? []) {
4993
+ if (link.name.value !== "link") continue;
4994
+ if (!stringArgument(link, "url")?.startsWith(FEDERATION_SPEC_URL)) continue;
4995
+ prefixes.push(`${stringArgument(link, "as") ?? "federation"}__`);
4996
+ const imports = link.arguments?.find((arg) => arg.name.value === "import")?.value;
4997
+ if (imports?.kind !== Kind.LIST) continue;
4998
+ for (const item of imports.values) {
4999
+ const name = item.kind === Kind.STRING ? item.value : item.kind === Kind.OBJECT ? stringArgument(item, "as") ?? stringArgument(item, "name") : void 0;
5000
+ const directive = name === void 0 ? void 0 : withoutAt(name);
5001
+ if (directive !== void 0) names.add(directive);
5002
+ }
5003
+ }
5004
+ }
5005
+ return {
5006
+ names,
5007
+ prefixes
5008
+ };
5009
+ }
5010
+ function isFederationDirective(name, declared, federation) {
4473
5011
  if (declared.has(name)) return false;
4474
- return FEDERATION_DIRECTIVES.has(name) || name.startsWith("federation__");
5012
+ return federation.names.has(name) || federation.prefixes.some((prefix) => name.startsWith(prefix));
4475
5013
  }
4476
5014
  function stripFederationDirectives(typeDefs) {
4477
5015
  const declared = /* @__PURE__ */ new Set();
4478
5016
  for (const def of typeDefs.definitions) if (def.kind === Kind.DIRECTIVE_DEFINITION) declared.add(def.name.value);
5017
+ const federation = federationNames(typeDefs);
4479
5018
  return visit(typeDefs, {
4480
- Directive: (node) => isFederationDirective(node.name.value, declared) ? null : void 0,
5019
+ Directive: (node) => isFederationDirective(node.name.value, declared, federation) ? null : void 0,
4481
5020
  SchemaExtension: { leave: (node) => !node.directives?.length && !node.operationTypes?.length ? null : void 0 }
4482
5021
  });
4483
5022
  }
4484
- /**
4485
- * The subgraphs with federation directives removed: the stream schema is
4486
- * merged in-process, where those directives are undeclared.
4487
- */
5023
+ /** `extend type X @key(...)` with no X in the set must define X to build. */
5024
+ function defineExtendedEntities(typeDefs, defined) {
5025
+ return {
5026
+ ...typeDefs,
5027
+ definitions: typeDefs.definitions.map((def) => def.kind === Kind.OBJECT_TYPE_EXTENSION && !defined.has(def.name.value) && !STREAM_ROOTS.includes(def.name.value) ? {
5028
+ ...def,
5029
+ kind: Kind.OBJECT_TYPE_DEFINITION
5030
+ } : def)
5031
+ };
5032
+ }
5033
+ /** Federation directives are undeclared in the in-process merge. */
4488
5034
  function withoutFederationDirectives(subgraphs) {
5035
+ const defined = /* @__PURE__ */ new Set();
5036
+ for (const subgraph of subgraphs) for (const def of subgraph.typeDefs.definitions) if (isTypeDefinitionNode(def)) defined.add(def.name.value);
4489
5037
  return subgraphs.map((subgraph) => ({
4490
5038
  ...subgraph,
4491
- typeDefs: stripFederationDirectives(subgraph.typeDefs)
5039
+ typeDefs: defineExtendedEntities(stripFederationDirectives(subgraph.typeDefs), defined)
4492
5040
  }));
4493
5041
  }
4494
- const STREAM_ROOTS = [
4495
- "Query",
4496
- "Mutation",
4497
- "Subscription"
4498
- ];
4499
- /**
4500
- * Merges subscription subgraphs into one stream schema, or `undefined` when no
4501
- * subgraph contributes the Query root a schema requires. A root the subgraphs
4502
- * only extend gets an empty definition to extend.
4503
- */
5042
+ /** `undefined` when there is nothing to merge; missing roots get placeholders. */
4504
5043
  function mergeStreamSubgraphs(subgraphs) {
5044
+ if (subgraphs.length === 0) return void 0;
4505
5045
  const defined = /* @__PURE__ */ new Set();
4506
5046
  const extended = /* @__PURE__ */ new Set();
4507
5047
  for (const subgraph of subgraphs) for (const def of subgraph.typeDefs.definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION) defined.add(def.name.value);
4508
5048
  else if (def.kind === Kind.OBJECT_TYPE_EXTENSION) extended.add(def.name.value);
4509
- if (!defined.has("Query") && !extended.has("Query")) return;
4510
5049
  const placeholders = STREAM_ROOTS.filter((root) => extended.has(root) && !defined.has(root)).flatMap((root) => parse(`type ${root}`).definitions);
4511
- const roots = placeholders.length > 0 ? [{
5050
+ if (!defined.has("Query") && !extended.has("Query")) placeholders.push(...parse(`type Query { _stub: Boolean }`).definitions);
5051
+ return mergeSubgraphSchemas([...placeholders.length > 0 ? [{
4512
5052
  name: "stream-roots",
4513
5053
  typeDefs: {
4514
5054
  kind: Kind.DOCUMENT,
4515
5055
  definitions: placeholders
4516
5056
  },
4517
5057
  url: ""
4518
- }] : [];
4519
- return mergeSubgraphSchemas([...roots, ...subgraphs], "last");
5058
+ }] : [], ...subgraphs], "last");
5059
+ }
5060
+ function isAsyncGenerator(value) {
5061
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value && typeof value.return === "function" && typeof value.throw === "function";
4520
5062
  }
4521
5063
  //#endregion
4522
5064
  //#region src/graphql/graphql-manager.ts
4523
- const DOCUMENT_MODELS_TO_EXCLUDE = [];
4524
5065
  const NON_MODEL_TYPE_NAMES = /* @__PURE__ */ new Set([
4525
5066
  "String",
4526
5067
  "Int",
@@ -4531,44 +5072,7 @@ const NON_MODEL_TYPE_NAMES = /* @__PURE__ */ new Set([
4531
5072
  "Mutation",
4532
5073
  "Subscription"
4533
5074
  ]);
4534
- /**
4535
- * Filter document models to keep only the latest version of each unique document model.
4536
- */
4537
- function filterLatestDocumentModelVersions(documentModels) {
4538
- const latestByName = /* @__PURE__ */ new Map();
4539
- for (const documentModel of documentModels) {
4540
- const name = documentModel.documentModel.global.name;
4541
- const existing = latestByName.get(name);
4542
- if (!existing) {
4543
- latestByName.set(name, documentModel);
4544
- continue;
4545
- }
4546
- if ((documentModel.documentModel.global.specifications.at(-1)?.version ?? 0) > (existing.documentModel.global.specifications.at(-1)?.version ?? 0)) latestByName.set(name, documentModel);
4547
- }
4548
- return Array.from(latestByName.values());
4549
- }
4550
5075
  const DefaultFeatureFlags = { enableDocumentModelSubgraphs: true };
4551
- /**
4552
- * Where a subgraph came from: a core subgraph, the host, the generated
4553
- * document-model subgraphs, or a package name. A name belongs to one origin:
4554
- * the same origin replaces it, a higher-ranked one evicts it, and any other is
4555
- * refused.
4556
- */
4557
- const CORE_ORIGIN = Symbol("core");
4558
- const DOCUMENT_MODEL_ORIGIN = Symbol("document-models");
4559
- const HOST_ORIGIN = Symbol("host");
4560
- function describeOrigin(origin) {
4561
- if (origin === CORE_ORIGIN) return "core";
4562
- if (origin === DOCUMENT_MODEL_ORIGIN) return "document models";
4563
- if (origin === HOST_ORIGIN) return "the host";
4564
- return `package ${origin}`;
4565
- }
4566
- function rank(origin) {
4567
- if (origin === CORE_ORIGIN) return 3;
4568
- if (origin === HOST_ORIGIN) return 2;
4569
- if (origin === DOCUMENT_MODEL_ORIGIN) return 1;
4570
- return 0;
4571
- }
4572
5076
  function refuseConnection(connection, reason) {
4573
5077
  const { socket } = connection;
4574
5078
  socket?.close?.(4403, reason);
@@ -4601,7 +5105,7 @@ var GraphQLManager = class {
4601
5105
  coreSubgraphsMap = /* @__PURE__ */ new Map();
4602
5106
  contextFields = {};
4603
5107
  subgraphs = /* @__PURE__ */ new Map();
4604
- subgraphWsDisposers = /* @__PURE__ */ new Map();
5108
+ #wsRouter;
4605
5109
  #authMiddleware;
4606
5110
  #requireAuthMiddleware;
4607
5111
  #driveMiddleware;
@@ -4613,6 +5117,7 @@ var GraphQLManager = class {
4613
5117
  subgraphRouteHandles = /* @__PURE__ */ new Map();
4614
5118
  /** Mounted SSE routes, keyed by path: the supergraph's and each subgraph's. */
4615
5119
  sseRouteHandles = /* @__PURE__ */ new Map();
5120
+ #sseStreams = /* @__PURE__ */ new Map();
4616
5121
  /**
4617
5122
  * Origin → the subgraph instances registered from it. Core and host
4618
5123
  * subgraphs are not tracked. Tracks the package association so that
@@ -4653,7 +5158,7 @@ var GraphQLManager = class {
4653
5158
  #loggedOwnershipExclusions = /* @__PURE__ */ new WeakMap();
4654
5159
  #claims = /* @__PURE__ */ new WeakMap();
4655
5160
  /** Claim tie-break: kept across re-registration, so HMR keeps the owner. */
4656
- #registrationOrder = /* @__PURE__ */ new Map();
5161
+ #registrationOrder = new RegistrationOrder();
4657
5162
  /** Per-subgraph handlers by name, before auth/drive middleware is applied,
4658
5163
  * for in-process queries by trusted internals. */
4659
5164
  #internalSubgraphHandlers = /* @__PURE__ */ new Map();
@@ -4722,7 +5227,10 @@ var GraphQLManager = class {
4722
5227
  report: options.reportError
4723
5228
  };
4724
5229
  this.driveOwnershipCache = new DriveOwnershipCache(options.driveStore ?? this.reactorClient);
4725
- this.wsServer.setMaxListeners(0);
5230
+ this.#wsRouter = new SubgraphWsRouter({
5231
+ order: (subgraphs) => this.#byClaimPriority(subgraphs),
5232
+ logger: this.logger
5233
+ });
4726
5234
  }
4727
5235
  async init(coreSubgraphs, authMiddleware, requireAuthMiddleware) {
4728
5236
  this.#authMiddleware = authMiddleware;
@@ -4768,6 +5276,7 @@ var GraphQLManager = class {
4768
5276
  this.logger.info(`Registered REST endpoint: GET ${driveRoutePath}`);
4769
5277
  await this.#setupCoreSubgraphs("graphql", coreSubgraphs, models);
4770
5278
  if (this.featureFlags.enableDocumentModelSubgraphs) await this.#setupDocumentModelSubgraphs("graphql", this.cachedDocumentModels);
5279
+ await this.#setupSubgraphs(this.subgraphs);
4771
5280
  await this.#createSupergraphGateway();
4772
5281
  return this.updateRouter();
4773
5282
  }
@@ -4805,66 +5314,42 @@ var GraphQLManager = class {
4805
5314
  /** Models whose schemas build and take no reserved name. */
4806
5315
  #admitModels(models) {
4807
5316
  const reserved = reservedTypeNames(Array.from(this.coreSubgraphsMap.values(), (subgraphs) => subgraphs.map((subgraph) => subgraph.typeDefs)).flat());
4808
- const refusals = /* @__PURE__ */ new Set();
4809
- const schemas = /* @__PURE__ */ new Map();
4810
- const admitted = [];
4811
- for (const { model, key, schema, error } of this.#schemaCache.resolve(models)) {
4812
- const id = model.documentModel.global.id;
4813
- const refuse = (message, reason) => {
4814
- const refusal = `${id}\n${key}\n${reason}`;
4815
- refusals.add(refusal);
4816
- if (!this.#refusals.has(refusal)) this.logger.error(message, id, reason);
4817
- };
4818
- const refuseModel = (reason) => refuse("Refusing document model @documentType from the GraphQL schema: @reason", reason);
4819
- if (!schema) {
4820
- refuseModel(`has an unusable schema: ${error.message}`);
4821
- continue;
4822
- }
4823
- const taken = this.#reservedNamesReason(model, schema, reserved);
4824
- if (taken !== void 0) {
4825
- refuseModel(taken);
4826
- continue;
4827
- }
4828
- if (schema.subgraphError) refuse("Refusing the subgraph of document model @documentType: @reason", `has an unusable subgraph schema: ${schema.subgraphError.message}`);
4829
- schemas.set(model, schema);
4830
- admitted.push(model);
4831
- }
4832
- this.#refusals = refusals;
5317
+ const { admitted, schemas, refusals } = admitDocumentModels(this.#schemaCache.resolve(models), reserved);
5318
+ const logged = /* @__PURE__ */ new Set();
5319
+ for (const refused of refusals) {
5320
+ const id = refused.model.documentModel.global.id;
5321
+ const refusal = `${id}\n${refused.key}\n${refused.reason}`;
5322
+ logged.add(refusal);
5323
+ if (this.#refusals.has(refusal)) continue;
5324
+ const versions = refused.everyVersion ? "every version" : "an older version";
5325
+ this.logger.error(refused.subgraphOnly ? `Refusing the subgraph of ${versions} of document model @documentType: @reason` : `Refusing ${versions} of document model @documentType from the GraphQL schema: @reason`, id, `version ${refused.version} ${refused.reason}`);
5326
+ }
5327
+ this.#refusals = logged;
4833
5328
  this.#modelSchemas = schemas;
4834
5329
  return admitted;
4835
5330
  }
4836
- #reservedNamesReason(model, schema, reserved) {
4837
- const taken = reservedTypeNamesTaken(model, reserved, schema.generated);
4838
- return taken.length > 0 ? `generates reserved type names: ${taken.join(", ")}` : void 0;
4839
- }
4840
5331
  async #setupDocumentModelSubgraphs(supergraph, documentModels) {
4841
- const latestDocumentModels = filterLatestDocumentModelVersions(documentModels);
4842
5332
  const registeredNames = /* @__PURE__ */ new Set();
4843
- for (const documentModel of latestDocumentModels) {
4844
- if (DOCUMENT_MODELS_TO_EXCLUDE.includes(documentModel.documentModel.global.id)) continue;
4845
- const types = this.#modelSchemas.get(documentModel)?.subgraph;
4846
- if (!types) continue;
4847
- try {
4848
- const subgraphInstance = new DocumentModelSubgraph(documentModel, {
4849
- http: this.scopeForPackage(CORE_PACKAGE_NAME),
4850
- relationalDb: this.relationalDb,
4851
- analyticsStore: this.analyticsStore,
4852
- reactorClient: this.reactorClient,
4853
- graphqlManager: this,
4854
- syncManager: this.syncManager,
4855
- path: this.path,
4856
- documentPermissionService: this.documentPermissionService,
4857
- authorizationService: this.authorizationService,
4858
- syncServingGate: this.syncServingGate,
4859
- attachments: this.attachments,
4860
- inspection: this.inspection
4861
- }, types);
4862
- const registered = await this.#addSubgraphInstance(subgraphInstance, supergraph, false, DOCUMENT_MODEL_ORIGIN);
4863
- if (registered) registeredNames.add(registered.name);
4864
- } catch (error) {
4865
- this.logger.error("Failed to setup document model subgraph for @documentType: @error", documentModel.documentModel.global.id, error instanceof Error ? error.message : error);
4866
- this.logger.debug("@error", error);
4867
- }
5333
+ for (const { model: documentModel, types } of documentModelSubgraphSources(documentModels, this.#modelSchemas)) try {
5334
+ const subgraphInstance = new DocumentModelSubgraph(documentModel, {
5335
+ http: this.scopeForPackage(CORE_PACKAGE_NAME),
5336
+ relationalDb: this.relationalDb,
5337
+ analyticsStore: this.analyticsStore,
5338
+ reactorClient: this.reactorClient,
5339
+ graphqlManager: this,
5340
+ syncManager: this.syncManager,
5341
+ path: this.path,
5342
+ documentPermissionService: this.documentPermissionService,
5343
+ authorizationService: this.authorizationService,
5344
+ syncServingGate: this.syncServingGate,
5345
+ attachments: this.attachments,
5346
+ inspection: this.inspection
5347
+ }, types);
5348
+ const registered = await this.#addSubgraphInstance(subgraphInstance, supergraph, false, DOCUMENT_MODEL_ORIGIN);
5349
+ if (registered) registeredNames.add(registered.name);
5350
+ } catch (error) {
5351
+ this.logger.error("Failed to setup document model subgraph for @documentType: @error", documentModel.documentModel.global.id, error instanceof Error ? error.message : error);
5352
+ this.logger.debug("@error", error);
4868
5353
  }
4869
5354
  return registeredNames;
4870
5355
  }
@@ -4882,10 +5367,6 @@ var GraphQLManager = class {
4882
5367
  for (const subgraphsMap of [this.coreSubgraphsMap, this.subgraphs]) for (const subgraphs of subgraphsMap.values()) for (const subgraph of subgraphs) if (subgraph.name === name) holders.add(subgraph);
4883
5368
  return holders;
4884
5369
  }
4885
- /** Core subgraph names are reserved: no other subgraph may take one. */
4886
- #isCoreNameReserved(name) {
4887
- return this.#findByName(this.coreSubgraphsMap, name) !== void 0;
4888
- }
4889
5370
  /** Buckets whose mount paths a registration into `supergraph` occupies: a
4890
5371
  * named supergraph's subgraphs are mounted under `graphql` as well. */
4891
5372
  #mountBuckets(supergraph) {
@@ -4963,51 +5444,43 @@ var GraphQLManager = class {
4963
5444
  }
4964
5445
  return true;
4965
5446
  }
4966
- /**
4967
- * Whether `instance` may register, and what it replaces. A name has one
4968
- * holder across every bucket: the same origin replaces it, a higher rank
4969
- * (core > host > document models > package) evicts it, and anything else is
4970
- * refused.
4971
- */
4972
- #admit(instance, core, origin) {
4973
- if (!core && this.#isCoreNameReserved(instance.name)) {
4974
- this.logger.error("Rejecting subgraph @name: name is reserved by a registered core subgraph", instance.name);
4975
- return { action: "reject" };
4976
- }
4977
- const holders = this.#holdersOf(instance.name);
4978
- if (holders.has(instance)) return {
4979
- action: "skip",
4980
- existing: instance
4981
- };
4982
- const rivals = Array.from(holders).filter((holder) => this.#originOf(holder) !== origin);
4983
- for (const holder of rivals) {
4984
- const holderOrigin = this.#originOf(holder);
4985
- if (rank(origin) <= rank(holderOrigin)) {
4986
- this.logger.error("Rejecting subgraph @name from @origin: name is taken by a subgraph from @existing", instance.name, describeOrigin(origin), describeOrigin(holderOrigin));
4987
- return { action: "reject" };
4988
- }
5447
+ /** Whether `instance` may register, and what it replaces or evicts. */
5448
+ #admit(instance, origin) {
5449
+ const admission = decideAdmission(instance, origin, Array.from(this.#holdersOf(instance.name), (holder) => ({
5450
+ holder,
5451
+ origin: this.#originOf(holder)
5452
+ })), () => this.#typeCollisions(instance));
5453
+ switch (admission.action) {
5454
+ case "skip": return {
5455
+ action: "skip",
5456
+ existing: instance
5457
+ };
5458
+ case "add": return admission;
4989
5459
  }
4990
- const collisions = core ? [] : this.#typeCollisions(instance);
4991
- if (collisions.length > 0) {
4992
- const reason = new SubgraphTypeCollisionError(collisions).message;
4993
- if (this.#loggedCollisions.get(instance) !== reason) {
4994
- this.#loggedCollisions.set(instance, reason);
4995
- this.logger.error("Rejecting subgraph @name: @error", instance.name, reason);
5460
+ switch (admission.reason) {
5461
+ case "core name":
5462
+ this.logger.error("Rejecting subgraph @name: name is reserved by a registered core subgraph", instance.name);
5463
+ break;
5464
+ case "rank":
5465
+ this.logger.error("Rejecting subgraph @name from @origin: name is taken by a subgraph from @existing", instance.name, describeOrigin(origin), describeOrigin(admission.holderOrigin));
5466
+ break;
5467
+ case "collision": {
5468
+ const reason = new SubgraphTypeCollisionError(admission.collisions).message;
5469
+ if (this.#loggedCollisions.get(instance) !== reason) {
5470
+ this.#loggedCollisions.set(instance, reason);
5471
+ this.logger.error("Rejecting subgraph @name: @error", instance.name, reason);
5472
+ }
5473
+ break;
4996
5474
  }
4997
- return { action: "reject" };
4998
5475
  }
4999
- return {
5000
- action: "add",
5001
- replaces: Array.from(holders).filter((it) => !rivals.includes(it)),
5002
- evicts: rivals
5003
- };
5476
+ return { action: "reject" };
5004
5477
  }
5005
5478
  #originOf(instance) {
5006
5479
  return this.#origins.get(instance) ?? HOST_ORIGIN;
5007
5480
  }
5008
5481
  async #addSubgraphInstance(subgraphInstance, supergraph = "", core = false, origin = HOST_ORIGIN) {
5009
5482
  if (core) origin = CORE_ORIGIN;
5010
- const admission = this.#admit(subgraphInstance, core, origin);
5483
+ const admission = this.#admit(subgraphInstance, origin);
5011
5484
  if (admission.action === "reject") return void 0;
5012
5485
  if (admission.action === "skip") {
5013
5486
  this.logger.debug(`Skipping duplicate subgraph: ${subgraphInstance.name}`);
@@ -5031,7 +5504,7 @@ var GraphQLManager = class {
5031
5504
  else if (bucket === supergraph) subgraphsMap.set(bucket, [subgraphInstance]);
5032
5505
  }
5033
5506
  this.#origins.set(subgraphInstance, origin);
5034
- this.#recordRegistrationOrder(origin, subgraphInstance.name);
5507
+ this.#registrationOrder.record(origin, subgraphInstance.name);
5035
5508
  if (origin !== HOST_ORIGIN && origin !== CORE_ORIGIN) {
5036
5509
  let instances = this.packageSubgraphs.get(origin);
5037
5510
  if (!instances) {
@@ -5043,17 +5516,6 @@ var GraphQLManager = class {
5043
5516
  this.logger.info(`${replaces.length + evicts.length > 0 ? "Replaced" : "Registered"} ${this.path.endsWith("/") ? this.path : this.path + "/"}${supergraph ? supergraph + "/" : ""}${subgraphInstance.name} subgraph.`);
5044
5517
  return subgraphInstance;
5045
5518
  }
5046
- #recordRegistrationOrder(origin, name) {
5047
- let entry = this.#registrationOrder.get(origin);
5048
- if (!entry) {
5049
- entry = {
5050
- order: this.#registrationOrder.size,
5051
- names: /* @__PURE__ */ new Map()
5052
- };
5053
- this.#registrationOrder.set(origin, entry);
5054
- }
5055
- if (!entry.names.has(name)) entry.names.set(name, entry.names.size);
5056
- }
5057
5519
  /**
5058
5520
  * Take `instance` off the mount paths of `buckets`. It is torn down
5059
5521
  * entirely unless it is still registered in another bucket.
@@ -5064,12 +5526,13 @@ var GraphQLManager = class {
5064
5526
  const subgraphs = subgraphsMap.get(bucket);
5065
5527
  if (!subgraphs?.includes(instance)) continue;
5066
5528
  subgraphsMap.set(bucket, subgraphs.filter((it) => it !== instance));
5067
- await this.#unmountSubgraph(instance, bucket);
5529
+ this.#unmountSubgraph(instance, bucket);
5068
5530
  }
5069
5531
  }
5070
5532
  /** Unmount what `instance` serves at its path in `bucket`: route, handler
5071
- * cache, SSE route, WebSocket handler and in-process handler. */
5072
- async #unmountSubgraph(instance, bucket) {
5533
+ * cache, SSE route, WebSocket route and in-process handler. A rebuild keeps
5534
+ * open WebSocket and SSE subscriptions; otherwise they complete. */
5535
+ #unmountSubgraph(instance, bucket, rebuild = false) {
5073
5536
  const subgraphPath = this.#getSubgraphPath(instance, bucket);
5074
5537
  if (this.subgraphHandlerCache.get(subgraphPath)?.subgraph !== instance) return;
5075
5538
  this.subgraphHandlerCache.delete(subgraphPath);
@@ -5080,15 +5543,13 @@ var GraphQLManager = class {
5080
5543
  }
5081
5544
  this.#disposeSSERoute(subgraphPath);
5082
5545
  if (this.#internalSubgraphHandlers.get(instance.name)?.path === subgraphPath) this.#internalSubgraphHandlers.delete(instance.name);
5083
- const wsDisposer = this.subgraphWsDisposers.get(subgraphPath);
5084
- if (wsDisposer) {
5085
- this.subgraphWsDisposers.delete(subgraphPath);
5086
- try {
5087
- await wsDisposer.dispose();
5088
- } catch (error) {
5089
- this.logger.error("Error disposing subgraph websocket @name: @error", instance.name, error);
5090
- }
5091
- }
5546
+ if (rebuild) return;
5547
+ this.#wsRouter.delete(subgraphPath, instance);
5548
+ const streams = this.#sseStreams.get(subgraphPath);
5549
+ this.#sseStreams.delete(subgraphPath);
5550
+ streams?.end();
5551
+ const supergraphPath = path.posix.join(this.path, "graphql");
5552
+ this.#sseStreams.get(supergraphPath)?.end(subgraphPath);
5092
5553
  }
5093
5554
  /**
5094
5555
  * Tear down a subgraph instance: disconnect it, drop it from every
@@ -5105,7 +5566,7 @@ var GraphQLManager = class {
5105
5566
  for (const subgraphsMap of [this.coreSubgraphsMap, this.subgraphs]) for (const [bucket, subgraphs] of subgraphsMap.entries()) {
5106
5567
  if (!subgraphs.includes(instance)) continue;
5107
5568
  subgraphsMap.set(bucket, subgraphs.filter((it) => it !== instance));
5108
- await this.#unmountSubgraph(instance, bucket);
5569
+ this.#unmountSubgraph(instance, bucket);
5109
5570
  }
5110
5571
  if (this.#internalSubgraphHandlers.get(instance.name)?.subgraph === instance) this.#internalSubgraphHandlers.delete(instance.name);
5111
5572
  const origin = this.#origins.get(instance);
@@ -5445,8 +5906,7 @@ var GraphQLManager = class {
5445
5906
  async shutdown() {
5446
5907
  this.logger.info("Shutting down GraphQL Manager");
5447
5908
  this.#credentialMonitor?.dispose();
5448
- for (const disposer of this.subgraphWsDisposers.values()) await disposer.dispose();
5449
- this.subgraphWsDisposers.clear();
5909
+ await this.#wsRouter.dispose();
5450
5910
  await this.gatewayAdapter.stop();
5451
5911
  return new Promise((resolve) => {
5452
5912
  this.wsServer.close(() => {
@@ -5477,7 +5937,7 @@ var GraphQLManager = class {
5477
5937
  this.logger.debug(`Setting up subgraph ${subgraph.name}`);
5478
5938
  const subgraphPath = this.#getSubgraphPath(subgraph, supergraph);
5479
5939
  if (this.#isExcludedForTypes(subgraph)) {
5480
- await this.#unmountSubgraph(subgraph, supergraph);
5940
+ this.#unmountSubgraph(subgraph, supergraph);
5481
5941
  continue;
5482
5942
  }
5483
5943
  try {
@@ -5488,7 +5948,7 @@ var GraphQLManager = class {
5488
5948
  } else if (this.#origins.has(cached.subgraph)) {
5489
5949
  this.logger.warn("Subgraph path @path already mounted by @kept; @name is shadowed and will not be mounted", subgraphPath, cached.subgraph.name, subgraph.name);
5490
5950
  continue;
5491
- } else await this.#unmountSubgraph(cached.subgraph, supergraph);
5951
+ } else this.#unmountSubgraph(cached.subgraph, supergraph);
5492
5952
  }
5493
5953
  const generated = this.#generated();
5494
5954
  const schema = createSchema(this.cachedDocumentModels, subgraph.resolvers, subgraph.typeDefs, this.#schemaOptions(subgraph));
@@ -5497,7 +5957,7 @@ var GraphQLManager = class {
5497
5957
  if (generated !== this.#generated()) continue;
5498
5958
  const previous = this.subgraphHandlerCache.get(subgraphPath);
5499
5959
  if (previous?.subgraph === subgraph && previous.generated === generated) continue;
5500
- if (previous) await this.#unmountSubgraph(previous.subgraph, supergraph);
5960
+ if (previous) this.#unmountSubgraph(previous.subgraph, supergraph, previous.subgraph === subgraph);
5501
5961
  const fetchHandler = this.#composeFetchMiddleware(rawHandler);
5502
5962
  this.subgraphHandlerCache.set(subgraphPath, {
5503
5963
  handler: fetchHandler,
@@ -5508,9 +5968,8 @@ var GraphQLManager = class {
5508
5968
  this.subgraphRouteHandles.set(subgraphPath, this.httpAdapter.mount(subgraphPath, fetchHandler));
5509
5969
  if (subgraph.hasSubscriptions) {
5510
5970
  try {
5511
- if (this.subgraphWsDisposers.get(subgraphPath)) this.logger.warn("Overwriting existing WebSocket disposer for subgraph at path @path", subgraphPath);
5512
- const wsDisposer = this.gatewayAdapter.attachWebSocket(this.wsServer, schema, this.#makeWsContextFactory());
5513
- this.subgraphWsDisposers.set(subgraphPath, wsDisposer);
5971
+ this.#wsRouter.attach(this.wsServer, this.#makeWsContextFactory());
5972
+ this.#wsRouter.set(subgraphPath, subgraph, schema);
5514
5973
  this.logger.debug(`WebSocket subscriptions enabled for ${subgraph.name}`);
5515
5974
  } catch (error) {
5516
5975
  this.logger.error("Failed to setup websocket for subgraph @name at path @path: @error", subgraph.name, subgraphPath, error);
@@ -5547,29 +6006,18 @@ var GraphQLManager = class {
5547
6006
  for (const [subgraphPath, subgraph] of members) if (losers.has(subgraph)) members.delete(subgraphPath);
5548
6007
  return members;
5549
6008
  }
6009
+ /** Rank, then first registration. */
6010
+ #byClaimPriority(subgraphs) {
6011
+ return byClaimPriority(subgraphs, (subgraph) => this.#originOf(subgraph), (subgraph) => subgraph.name, this.#registrationOrder);
6012
+ }
5550
6013
  /** Claims go by rank, then first registration; each exclusion logs once. */
5551
6014
  #claimLosers(subgraphs) {
5552
- const priority = (subgraph) => {
5553
- const origin = this.#originOf(subgraph);
5554
- const order = this.#registrationOrder.get(origin);
5555
- return [
5556
- -rank(origin),
5557
- order?.order ?? Infinity,
5558
- order?.names.get(subgraph.name) ?? Infinity
5559
- ];
5560
- };
5561
- const ranked = Array.from(subgraphs, (subgraph) => ({
5562
- subgraph,
5563
- priority: priority(subgraph)
5564
- })).sort((a, b) => {
5565
- const i = a.priority.findIndex((value, j) => value !== b.priority[j]);
5566
- return i === -1 ? 0 : a.priority[i] - b.priority[i];
5567
- });
5568
- const excluded = resolveClaimOwnership(ranked.map(({ subgraph }) => ({
5569
- candidate: subgraph,
6015
+ const excluded = supergraphClaimLosers(Array.from(subgraphs, (subgraph) => ({
6016
+ member: subgraph,
5570
6017
  name: subgraph.name,
6018
+ origin: this.#originOf(subgraph),
5571
6019
  claims: this.#claimsOf(subgraph)
5572
- })));
6020
+ })), this.#registrationOrder);
5573
6021
  for (const subgraph of subgraphs) {
5574
6022
  const conflicts = excluded.get(subgraph);
5575
6023
  if (!conflicts) {
@@ -5671,7 +6119,7 @@ var GraphQLManager = class {
5671
6119
  this.#disposeSSERoute(superGraphPath);
5672
6120
  return;
5673
6121
  }
5674
- this.#setupSSEHandler(mergedSchema, superGraphPath);
6122
+ this.#setupSSEHandler(mergedSchema, superGraphPath, subscriptionOwners(buildable, mergedSchema));
5675
6123
  this.logger.debug(`SSE subscriptions enabled at supergraph level (merged from ${buildable.length} subgraph(s))`);
5676
6124
  } catch (error) {
5677
6125
  this.logger.error("Failed to setup supergraph SSE: @error", error);
@@ -5685,11 +6133,19 @@ var GraphQLManager = class {
5685
6133
  * Express middleware (Authorization header), unlike WebSocket which
5686
6134
  * needs its own connectionParams-based auth.
5687
6135
  */
5688
- #setupSSEHandler(schema, basePath) {
6136
+ #setupSSEHandler(schema, basePath, tagsOf) {
5689
6137
  const ssePath = basePath + "/stream";
6138
+ let streams = this.#sseStreams.get(basePath);
6139
+ if (!streams) {
6140
+ streams = new SSEStreams();
6141
+ this.#sseStreams.set(basePath, streams);
6142
+ }
6143
+ streams.reopen();
5690
6144
  const rawHandler = createGraphQLSSEHandler({
5691
6145
  schema,
5692
- contextFactory: this.#makeContextFactory()
6146
+ contextFactory: this.#makeContextFactory(),
6147
+ streams,
6148
+ tagsOf
5693
6149
  });
5694
6150
  const handler = this.#composeFetchMiddleware(rawHandler);
5695
6151
  this.#disposeSSERoute(basePath);
@@ -5718,6 +6174,22 @@ var GraphQLManager = class {
5718
6174
  return handler;
5719
6175
  }
5720
6176
  };
6177
+ /** Tags a merged-schema operation with the paths of the subgraphs it reaches. */
6178
+ function subscriptionOwners(subgraphs, schema) {
6179
+ const root = schema.getSubscriptionType()?.name ?? "Subscription";
6180
+ const owners = /* @__PURE__ */ new Map();
6181
+ for (const subgraph of subgraphs) for (const definition of subgraph.typeDefs.definitions) if ((definition.kind === Kind.OBJECT_TYPE_DEFINITION || definition.kind === Kind.OBJECT_TYPE_EXTENSION) && definition.name.value === root) for (const field of definition.fields ?? []) owners.set(field.name.value, subgraph.url);
6182
+ return (args) => {
6183
+ const operation = getOperationAST(args.document, args.operationName);
6184
+ const tags = /* @__PURE__ */ new Set();
6185
+ if (!operation) return tags;
6186
+ for (const field of rootFields(args.document, operation)) {
6187
+ const owner = owners.get(field);
6188
+ if (owner !== void 0) tags.add(owner);
6189
+ }
6190
+ return tags;
6191
+ };
6192
+ }
5721
6193
  //#endregion
5722
6194
  //#region src/graphql/inspection/resolvers.ts
5723
6195
  function operatorRequired() {
@@ -7441,10 +7913,10 @@ const ADMIN_USERS = getAdminUsers();
7441
7913
  //#endregion
7442
7914
  //#region src/graphql/system/version.ts
7443
7915
  function getVersion() {
7444
- return "6.2.3-dev.64";
7916
+ return "6.2.3-dev.66";
7445
7917
  }
7446
7918
  function getGitHash() {
7447
- return "54feed6a5b9dae11bfac933dbae18479bc3bf28f";
7919
+ return "8e88ee237e483b230ddc0b8841e1718a2f4340e1";
7448
7920
  }
7449
7921
  function getGitUrl() {
7450
7922
  return buildTreeUrl(getGitHash());
@@ -7474,7 +7946,7 @@ const REGISTRY_EXTERNAL_DEPS_MISSING = "ERR_REGISTRY_EXTERNAL_DEPS_MISSING";
7474
7946
  const PACKAGE_MANIFEST = "powerhouse.manifest.json";
7475
7947
  const MANIFEST_FILE = "manifest.json";
7476
7948
  function defaultRegistryCacheDir(cwd = process.cwd()) {
7477
- return path.join(cwd, ".ph", "registry-packages");
7949
+ return path.join(resolvePhDir(cwd), "registry-packages");
7478
7950
  }
7479
7951
  const EXACT_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
7480
7952
  const PACKAGE_NAME = /^(@[a-z0-9][-a-z0-9._]*\/)?[a-z0-9][-a-z0-9._]*$/i;
@@ -8329,6 +8801,10 @@ function isExpectedLoaderMiss(error, pkg, subPath) {
8329
8801
  if (code === "ERR_MODULE_NOT_FOUND") return error.message.includes(`'${pkg}'`) || error.message.includes(`"${pkg}"`) || error.message.includes(`'${pkg}/`) || error.message.includes(`"${pkg}/`);
8330
8802
  return false;
8331
8803
  }
8804
+ const ALREADY_LOGGED = /* @__PURE__ */ new Set([REGISTRY_EXTERNAL_DEPS_MISSING, PACKAGE_MODULE_FAILED]);
8805
+ function subPathOf(kind) {
8806
+ return kind === "document models" ? "document-models" : kind;
8807
+ }
8332
8808
  function getUniqueDocumentModels(...documentModels) {
8333
8809
  const uniqueModels = /* @__PURE__ */ new Map();
8334
8810
  for (const models of documentModels) for (const model of models) uniqueModels.set(`${model.documentModel.global.id}@${model.version ?? 1}`, model);
@@ -8351,6 +8827,10 @@ var PackageManager = class {
8351
8827
  configWatcher;
8352
8828
  unsubscribePackages;
8353
8829
  subscribedPackages = /* @__PURE__ */ new Set();
8830
+ removals = 0;
8831
+ removedAt = /* @__PURE__ */ new Map();
8832
+ loadQueue = Promise.resolve();
8833
+ removedPackages = /* @__PURE__ */ new Set();
8354
8834
  debouncedUpdateCallbacks = /* @__PURE__ */ new Map();
8355
8835
  eventEmitter = new EventEmitter();
8356
8836
  get detached() {
@@ -8368,13 +8848,34 @@ var PackageManager = class {
8368
8848
  if (this.options.configFile) this.initConfigFileWatcher(this.options.configFile);
8369
8849
  return await this.loadPackages(this.getAllPackageNames());
8370
8850
  }
8371
- async loadPackages(packages) {
8372
- this.logger.info("Loading packages: @packages", packages.join(", "));
8373
- const documentModelsMap = await this.loadDocumentModels(packages);
8374
- const upgradeManifestsMap = await this.loadUpgradeManifests(packages);
8375
- const subgraphsMap = await this.loadSubgraphs(packages);
8376
- const processorsMap = await this.loadProcessors(packages);
8377
- const piecesMap = await this.loadPieces(packages);
8851
+ loadPackages(packages) {
8852
+ const requestedAt = this.removals;
8853
+ const load = this.loadQueue.then(() => this.loadPackagesNow(packages, requestedAt));
8854
+ this.loadQueue = load.catch(() => void 0);
8855
+ return load;
8856
+ }
8857
+ async loadPackagesNow(requested, requestedAt) {
8858
+ this.logger.info("Loading packages: @packages", requested.join(", "));
8859
+ const documentModelLoads = await this.loadDocumentModels(requested);
8860
+ const failed = requested.filter((pkg) => documentModelLoads.get(pkg)?.status === "failed");
8861
+ const upgradeManifestsMap = await this.loadUpgradeManifests(requested.filter((pkg) => !failed.includes(pkg)));
8862
+ for (const pkg of failed) {
8863
+ const manifests = this.upgradeManifestsMap.get(pkg);
8864
+ if (manifests) upgradeManifestsMap.set(pkg, manifests);
8865
+ }
8866
+ const documentModelsMap = new Map([...baseDocumentModels.map(([source, model]) => [source, [model]]), ...this.settle("document models", documentModelLoads, this.docModelsMap)]);
8867
+ const subgraphsMap = this.settle("subgraphs", await this.loadSubgraphs(requested), this.subgraphsMap);
8868
+ const processorsMap = this.settle("processors", await this.loadProcessors(requested), this.processorMap);
8869
+ const piecesMap = this.settle("pieces", await this.loadPieces(requested), this.piecesMap);
8870
+ const removed = requested.filter((pkg) => (this.removedAt.get(pkg) ?? 0) > requestedAt);
8871
+ for (const map of [
8872
+ documentModelsMap,
8873
+ upgradeManifestsMap,
8874
+ subgraphsMap,
8875
+ processorsMap,
8876
+ piecesMap
8877
+ ]) removed.forEach((pkg) => map.delete(pkg));
8878
+ const packages = requested.filter((pkg) => !removed.includes(pkg));
8378
8879
  this.upgradeManifestsMap = upgradeManifestsMap;
8379
8880
  this.updatePackagesMap(documentModelsMap);
8380
8881
  this.updateSubgraphsMap(subgraphsMap);
@@ -8396,31 +8897,45 @@ var PackageManager = class {
8396
8897
  pieces: piecesMap
8397
8898
  };
8398
8899
  }
8399
- async loadDocumentModels(packages) {
8400
- this.logger.debug(`Loading document models from packages: ${packages.join(", ")}`);
8401
- const documentModelModuleMap = /* @__PURE__ */ new Map();
8402
- for (const [source, model] of baseDocumentModels) documentModelModuleMap.set(source, [model]);
8900
+ settle(kind, loads, current) {
8901
+ const settled = /* @__PURE__ */ new Map();
8902
+ for (const [pkg, load] of loads) {
8903
+ if (load.status === "failed" && current.has(pkg)) this.logger.info(`Keeping the last loaded ${kind} of @pkg`, pkg);
8904
+ settled.set(pkg, load.status === "loaded" ? load.value : load.status === "failed" ? current.get(pkg) ?? [] : []);
8905
+ }
8906
+ return settled;
8907
+ }
8908
+ async loadEach(kind, packages, load) {
8909
+ this.logger.debug(`Loading ${kind} from packages: ${packages.join(", ")}`);
8910
+ const subPath = subPathOf(kind);
8911
+ const loads = /* @__PURE__ */ new Map();
8403
8912
  for (const pkg of packages) {
8404
- const allDocumentModels = [];
8405
8913
  const failures = [];
8406
- let succeeded = false;
8914
+ let loaded;
8407
8915
  for (const loader of this.loaders) try {
8408
- const documentModels = await loader.loadDocumentModels(pkg);
8409
- allDocumentModels.push(...documentModels);
8410
- this.logger.info(`[${loader.name}] Loaded document models from package @pkg: @documentModels`, pkg, documentModels.map((dm) => dm.documentModel.global.id));
8411
- succeeded = true;
8916
+ loaded = {
8917
+ status: "loaded",
8918
+ value: await load(loader, pkg)
8919
+ };
8412
8920
  break;
8413
8921
  } catch (error) {
8414
8922
  failures.push({
8415
8923
  loader: loader.name,
8416
8924
  error
8417
8925
  });
8418
- this.logger.debug(`[${loader.name}] Failed to load document models from package @pkg: @error`, pkg, error);
8926
+ this.logger.debug("[@loader] Failed to load @kind from package @package: @error", loader.name, kind, pkg, error);
8419
8927
  }
8420
- this.maybeWarnAllLoadersFailed("document models", pkg, succeeded, failures);
8421
- documentModelModuleMap.set(pkg, allDocumentModels);
8928
+ this.maybeWarnAllLoadersFailed(kind, pkg, loaded !== void 0, failures);
8929
+ loads.set(pkg, loaded ?? (failures.every(({ error }) => isExpectedLoaderMiss(error, pkg, subPath)) ? { status: "absent" } : { status: "failed" }));
8422
8930
  }
8423
- return documentModelModuleMap;
8931
+ return loads;
8932
+ }
8933
+ loadDocumentModels(packages) {
8934
+ return this.loadEach("document models", packages, async (loader, pkg) => {
8935
+ const documentModels = await loader.loadDocumentModels(pkg);
8936
+ this.logger.info(`[${loader.name}] Loaded document models from package @pkg: @documentModels`, pkg, documentModels.map((dm) => dm.documentModel.global.id));
8937
+ return documentModels;
8938
+ });
8424
8939
  }
8425
8940
  /** Upgrade manifests currently loaded across all packages, one per type. */
8426
8941
  getUniqueUpgradeManifests() {
@@ -8443,132 +8958,83 @@ var PackageManager = class {
8443
8958
  return manifestsMap;
8444
8959
  }
8445
8960
  async loadSubgraphs(packages) {
8446
- this.logger.debug(`Loading subgraphs from packages: ${packages.join(", ")}`);
8447
- const subgraphsMap = /* @__PURE__ */ new Map();
8448
- for (const pkg of packages) {
8449
- const allSubgraphs = [];
8450
- const failures = [];
8451
- let succeeded = false;
8452
- for (const loader of this.loaders) try {
8453
- const subgraphs = await loader.loadSubgraphs(pkg);
8454
- allSubgraphs.push(...subgraphs);
8455
- succeeded = true;
8456
- break;
8457
- } catch (error) {
8458
- failures.push({
8459
- loader: loader.name,
8460
- error
8461
- });
8462
- this.logger.debug("[@loader] Failed to load subgraphs from package @package: @error", loader.name, pkg, error);
8463
- }
8464
- this.maybeWarnAllLoadersFailed("subgraphs", pkg, succeeded, failures);
8465
- if (allSubgraphs.length === 0) {
8466
- const declared = manifestDeclaredSubgraphs(pkg);
8467
- if (declared.length > 0) this.logger.warn("Package @pkg declares subgraphs in powerhouse.manifest.json (@declared) but none was loaded; check the exports of subgraphs/index.ts", pkg, declared.join(", "));
8468
- }
8469
- subgraphsMap.set(pkg, allSubgraphs);
8470
- }
8471
- return subgraphsMap;
8472
- }
8473
- async loadProcessors(packages) {
8474
- this.logger.debug(`Loading processors from packages: ${packages.join(", ")}`);
8475
- const processorsMap = /* @__PURE__ */ new Map();
8476
- for (const pkg of packages) {
8477
- const allProcessors = [];
8478
- const failures = [];
8479
- let succeeded = false;
8480
- for (const loader of this.loaders) try {
8481
- const processors = await loader.loadProcessors(pkg);
8482
- if (processors) allProcessors.push(processors);
8483
- succeeded = true;
8484
- break;
8485
- } catch (error) {
8486
- failures.push({
8487
- loader: loader.name,
8488
- error
8489
- });
8490
- this.logger.debug("[@loader] Failed to load processors from package @package: @error", loader.name, pkg, error);
8491
- }
8492
- this.maybeWarnAllLoadersFailed("processors", pkg, succeeded, failures);
8493
- processorsMap.set(pkg, allProcessors);
8494
- }
8495
- return processorsMap;
8961
+ const loads = await this.loadEach("subgraphs", packages, (loader, pkg) => loader.loadSubgraphs(pkg));
8962
+ for (const [pkg, load] of loads) {
8963
+ if (load.status === "loaded" && load.value.length > 0) continue;
8964
+ const declared = manifestDeclaredSubgraphs(pkg);
8965
+ if (declared.length > 0) this.logger.warn("Package @pkg declares subgraphs in powerhouse.manifest.json (@declared) but none was loaded; check the exports of subgraphs/index.ts", pkg, declared.join(", "));
8966
+ }
8967
+ return loads;
8968
+ }
8969
+ loadProcessors(packages) {
8970
+ return this.loadEach("processors", packages, async (loader, pkg) => {
8971
+ const processors = await loader.loadProcessors(pkg);
8972
+ return processors ? [processors] : [];
8973
+ });
8496
8974
  }
8497
8975
  async loadPieces(packages) {
8498
- this.logger.debug(`Loading pieces from packages: ${packages.join(", ")}`);
8499
- const piecesMap = /* @__PURE__ */ new Map();
8500
- for (const pkg of packages) {
8501
- const allPieces = [];
8502
- const failures = [];
8503
- let succeeded = false;
8504
- for (const loader of this.loaders) try {
8505
- allPieces.push(...await loader.loadPieces(pkg));
8506
- succeeded = true;
8507
- break;
8508
- } catch (error) {
8509
- failures.push({
8510
- loader: loader.name,
8511
- error
8512
- });
8513
- this.logger.debug("[@loader] Failed to load pieces from package @package: @error", loader.name, pkg, error);
8514
- }
8515
- this.maybeWarnAllLoadersFailed("pieces", pkg, succeeded, failures);
8516
- if (allPieces.length > 0) this.logger.info("Loaded @count piece(s) from package @pkg: @pieces", allPieces.length, pkg, allPieces.map((piece) => piece.name).join(", "));
8517
- piecesMap.set(pkg, allPieces);
8976
+ const loads = await this.loadEach("pieces", packages, (loader, pkg) => loader.loadPieces(pkg));
8977
+ for (const [pkg, load] of loads) {
8978
+ if (load.status !== "loaded" || load.value.length === 0) continue;
8979
+ this.logger.info("Loaded @count piece(s) from package @pkg: @pieces", load.value.length, pkg, load.value.map((piece) => piece.name).join(", "));
8518
8980
  }
8519
- return piecesMap;
8981
+ return loads;
8520
8982
  }
8521
8983
  maybeWarnAllLoadersFailed(kind, pkg, succeeded, failures) {
8522
8984
  if (succeeded || failures.length === 0) return;
8523
- const subPath = kind === "document models" ? "document-models" : kind;
8524
- const realFailures = failures.filter(({ error }) => !isExpectedLoaderMiss(error, pkg, subPath) && error?.code !== "ERR_REGISTRY_EXTERNAL_DEPS_MISSING");
8985
+ const subPath = subPathOf(kind);
8986
+ const realFailures = failures.filter(({ error }) => !isExpectedLoaderMiss(error, pkg, subPath) && !ALREADY_LOGGED.has(error?.code ?? ""));
8525
8987
  if (realFailures.length === 0) return;
8526
8988
  const details = realFailures.map(({ loader, error }) => {
8527
8989
  return ` [${loader}] ${error instanceof Error ? error.message : String(error)}`;
8528
8990
  }).join("\n");
8529
8991
  this.logger.warn(`All package loaders failed to load ${kind} from @pkg:\n@details`, pkg, details);
8530
8992
  }
8993
+ withReload(kind, current, pkg, load) {
8994
+ if (load?.status === "failed") {
8995
+ if (current.has(pkg)) this.logger.info(`Keeping the last loaded ${kind} of @pkg`, pkg);
8996
+ return;
8997
+ }
8998
+ const next = new Map(current);
8999
+ const value = load?.status === "loaded" ? load.value : [];
9000
+ if (value.length === 0) next.delete(pkg);
9001
+ else next.set(pkg, value);
9002
+ return next;
9003
+ }
8531
9004
  async updateDocumentModelsForPackage(pkg) {
8532
9005
  this.logger.debug(`Updating document models for package: ${pkg}`);
8533
- const documentModels = await this.loadDocumentModels([pkg]);
9006
+ const load = (await this.loadDocumentModels([pkg])).get(pkg);
9007
+ const documentModelsMap = this.withReload("document models", this.docModelsMap, pkg, load);
9008
+ if (!documentModelsMap) return;
8534
9009
  const upgradeManifests = await this.loadUpgradeManifests([pkg]);
9010
+ if (!this.subscribedPackages.has(pkg)) return;
8535
9011
  const upgradeManifestsMap = new Map(this.upgradeManifestsMap);
8536
9012
  const pkgManifests = upgradeManifests.get(pkg) ?? [];
8537
9013
  if (pkgManifests.length === 0) upgradeManifestsMap.delete(pkg);
8538
9014
  else upgradeManifestsMap.set(pkg, pkgManifests);
8539
9015
  this.upgradeManifestsMap = upgradeManifestsMap;
8540
- const documentModelsMap = new Map(this.docModelsMap);
8541
- const pkgModels = documentModels.get(pkg) ?? [];
8542
- if (pkgModels.length === 0) documentModelsMap.delete(pkg);
8543
- else documentModelsMap.set(pkg, pkgModels);
8544
9016
  this.updatePackagesMap(documentModelsMap);
8545
9017
  }
8546
9018
  async updateSubgraphsForPackage(pkg) {
8547
9019
  this.logger.debug(`Updating subgraphs for package: ${pkg}`);
8548
- const subgraphs = await this.loadSubgraphs([pkg]);
8549
- const subgraphsMap = new Map(this.subgraphsMap);
8550
- const pkgSubgraphs = subgraphs.get(pkg) ?? [];
8551
- if (pkgSubgraphs.length === 0) subgraphsMap.delete(pkg);
8552
- else subgraphsMap.set(pkg, pkgSubgraphs);
8553
- this.updateSubgraphsMap(subgraphsMap);
9020
+ const load = (await this.loadSubgraphs([pkg])).get(pkg);
9021
+ if (!this.subscribedPackages.has(pkg)) return;
9022
+ const next = this.withReload("subgraphs", this.subgraphsMap, pkg, load);
9023
+ if (next) this.updateSubgraphsMap(next);
8554
9024
  }
8555
9025
  async updateProcessorsForPackage(pkg) {
8556
9026
  this.logger.debug(`Updating processors for package: ${pkg}`);
8557
- const processors = await this.loadProcessors([pkg]);
8558
- const processorsMap = new Map(this.processorMap);
8559
- const pkgProcessors = processors.get(pkg) ?? [];
8560
- if (pkgProcessors.length === 0) processorsMap.delete(pkg);
8561
- else processorsMap.set(pkg, pkgProcessors);
8562
- this.updateProcessorsMap(processorsMap);
9027
+ const load = (await this.loadProcessors([pkg])).get(pkg);
9028
+ if (!this.subscribedPackages.has(pkg)) return;
9029
+ const next = this.withReload("processors", this.processorMap, pkg, load);
9030
+ if (next) this.updateProcessorsMap(next);
8563
9031
  }
8564
9032
  async updatePiecesForPackage(pkg) {
8565
9033
  this.logger.debug(`Updating pieces for package: ${pkg}`);
8566
- const pieces = await this.loadPieces([pkg]);
8567
- const piecesMap = new Map(this.piecesMap);
8568
- const pkgPieces = pieces.get(pkg) ?? [];
8569
- if (pkgPieces.length === 0) piecesMap.delete(pkg);
8570
- else piecesMap.set(pkg, pkgPieces);
8571
- this.updatePiecesMap(piecesMap);
9034
+ const load = (await this.loadPieces([pkg])).get(pkg);
9035
+ if (!this.subscribedPackages.has(pkg)) return;
9036
+ const next = this.withReload("pieces", this.piecesMap, pkg, load);
9037
+ if (next) this.updatePiecesMap(next);
8572
9038
  }
8573
9039
  /** Debounced per key so repeated subscribePackages calls reuse one timer. */
8574
9040
  getDebouncedUpdateCallback(pkg, kind, update) {
@@ -8603,7 +9069,8 @@ var PackageManager = class {
8603
9069
  getAllPackageNames() {
8604
9070
  const packageNames = new Set(this.options.packages);
8605
9071
  if (this.options.configFile) for (const name of this.getPackageNamesFromConfigFile(this.options.configFile)) packageNames.add(name);
8606
- return Array.from(packageNames);
9072
+ for (const pkg of this.removedPackages) if (!packageNames.has(pkg)) this.removedPackages.delete(pkg);
9073
+ return Array.from(packageNames).filter((pkg) => !this.removedPackages.has(pkg));
8607
9074
  }
8608
9075
  getPackageNamesFromConfigFile(configFile) {
8609
9076
  return getConfig(configFile).packages?.map((pkg) => pkg.packageName) ?? [];
@@ -8658,15 +9125,15 @@ var PackageManager = class {
8658
9125
  getPieces() {
8659
9126
  return new Map(this.piecesMap);
8660
9127
  }
8661
- /**
8662
- * Remove `pkg` from all package maps and emit the change events, tearing
8663
- * down everything the package registered (subgraphs, processors, document
8664
- * models). For an uninstalled package no loader can serve it again, so
8665
- * nothing can re-add it.
8666
- */
9128
+ hasPackage(pkg) {
9129
+ return this.subscribedPackages.has(pkg);
9130
+ }
9131
+ /** Tear down everything `pkg` registered; config reloads leave it out. */
8667
9132
  removePackage(pkg) {
8668
9133
  this.logger.info(`Removing package: ${pkg}`);
8669
9134
  this.subscribedPackages.delete(pkg);
9135
+ this.removedAt.set(pkg, ++this.removals);
9136
+ this.removedPackages.add(pkg);
8670
9137
  const dropKey = (map) => {
8671
9138
  if (!map.has(pkg)) return map;
8672
9139
  const next = new Map(map);
@@ -9250,11 +9717,9 @@ function setupEventListeners(pkgManager, graphqlManager, reactorProcessorManager
9250
9717
  const newModules = getUniqueDocumentModels(Object.values(packagedModels).flat());
9251
9718
  const incomingTypes = typesOf(newModules);
9252
9719
  const removedTypes = /* @__PURE__ */ new Set();
9253
- for (const [pkg, models] of Object.entries(packagedModels)) {
9254
- if (models.length === 0) continue;
9255
- for (const type of packagedTypes.get(pkg) ?? []) if (!incomingTypes.has(type)) removedTypes.add(type);
9256
- packagedTypes.set(pkg, typesOf(models));
9257
- }
9720
+ for (const types of packagedTypes.values()) for (const type of types) if (!incomingTypes.has(type)) removedTypes.add(type);
9721
+ packagedTypes.clear();
9722
+ for (const [pkg, models] of Object.entries(packagedModels)) packagedTypes.set(pkg, typesOf(models));
9258
9723
  if (removedTypes.size > 0) {
9259
9724
  documentModelRegistry.unregisterModules(...removedTypes);
9260
9725
  documentModelRegistry.unregisterUpgradeManifests(...removedTypes);
@@ -10617,15 +11082,21 @@ var PackageManagementService = class {
10617
11082
  }
10618
11083
  async uninstallPackage(name) {
10619
11084
  const existing = await this.storage.get(name);
10620
- if (!existing) {
11085
+ const managed = this.packageManager?.hasPackage(name) ?? false;
11086
+ if (!existing && !managed) {
10621
11087
  this.logger.warn("Package @name is not installed", name);
10622
11088
  return false;
10623
11089
  }
10624
11090
  this.logger.info("Uninstalling package @name", name);
10625
- await this.storage.delete(name);
10626
- this.loadedModulesCache.delete(name);
10627
11091
  if (this.httpLoader) this.httpLoader.documentModelLoader.removeFromCache(name);
10628
- if (this.documentModelRegistry) this.documentModelRegistry.unregisterModules(...existing.documentTypes);
11092
+ if (existing && this.documentModelRegistry) {
11093
+ this.documentModelRegistry.unregisterModules(...existing.documentTypes);
11094
+ this.documentModelRegistry.unregisterUpgradeManifests(...existing.documentTypes);
11095
+ }
11096
+ if (existing) {
11097
+ await this.storage.delete(name);
11098
+ this.loadedModulesCache.delete(name);
11099
+ }
10629
11100
  if (this.packageManager) this.packageManager.removePackage(name);
10630
11101
  this.triggerModelsChanged();
10631
11102
  this.logger.info("Uninstalled package @name", name);
@@ -10653,4 +11124,4 @@ var PackageManagementService = class {
10653
11124
  export { ADMIN_USERS, ActionCandidateInputSchema, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentAccessFailed, AttachmentAccessService, AttachmentAccessUnavailable, AttachmentClientProvider, AuthDecision, AuthDecisionSchema, AuthEvaluationUnsupportedError, AuthService, AuthSubgraph, AuthenticationRequiredError, AuthorizationPolicy, AuthorizedAttachmentService, AuthorizedDocumentHandle, BaseSubgraph, CORE_PACKAGE_NAME, CanonicalDocumentIdResolutionError, ChannelMetaInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DEFAULT_INSPECTION_THROTTLE, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentModelSchemaCache, DocumentOperationsFilterInputSchema, DocumentPermissionService, DocumentRelationshipFieldsFragmentDoc, EvaluateActionsDocument, ExecuteBatchDocument, ExecutionJobInputSchema, FindDocumentsDocument, ForbiddenError, GetCreateDefaultsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentServedDocument, GetDocumentWithOperationsDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, HttpRouteService, ImportPackageLoader, InMemoryPackageStorage, InspectionSubgraph, InspectionThrottle, InspectionThrottledError, InvalidNamespaceError, JobChangesDocument, JobInfoFieldsFragmentDoc, MalformedStoredOperationError, MemoryWebhookStore, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PACKAGE_ROUTE_SEGMENT, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PrivacyPermissionAdapter, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RefusalNotRecordedError, RelationalWebhookStore, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, SearchFilterInputSchema, SetPreferredEditorDocument, SubgraphTypeCollisionError, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SyncRefusalInputSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, UpdateRelationshipDocument, ViewFilterInputSchema, WEBHOOK_SEGMENT, WS_AUTH_CLOSE_REASONS, WS_CLOSE_REASON_AUTHENTICATION_REQUIRED, WS_CLOSE_REASON_BEARER_REJECTED, WS_CLOSE_REASON_CREDENTIAL_REVOKED, WebhookService, assembleSubgraphTypeDefs, assertAttachmentPolicyReadsAllowed, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertHostMountPath, assertRequireAuthenticatedCallerAllowed, assertSkipCredentialVerificationAllowed, baseDocumentModels, buildDocumentModelSchema, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, callerSubject, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createCredentialInvalidator, createGatewayAdapter, createHttpAdapter, createInspectionResolvers, createMergedSchema, createReactorGraphQLClient, createReactorInspectionSource, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, definedNonNullAnySchema, documentModelSubgraphTypes, driveIdFromUrl, extractSubgraphs, extractSubgraphsFromModule, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getExplorerPrefix, getGeneratedDocumentModelTypes, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, hasOperationSchemas, initAnalyticsStoreSql, initializeAndStartAPI, inspectionTypeDefs, isDefinedNonNullAny, isExpectedLoaderMiss, isListedAdmin, isPostgresConnectionString, isSubgraphClass, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, piecesBaseUrl, redactHeaders, renderGraphqlPlayground, reportFailure, reservedTypeNames, reservedTypeNamesTaken, resolveCredentialCacheTtlMs, resolvePackageName, resolveRenownConfig, runDetached, typeDefinitionNames, verifyWebhook };
10654
11125
 
10655
11126
  //# sourceMappingURL=index.mjs.map
10656
- //# debugId=061cb7f9-bbbc-55da-a218-225c0b3c993d
11127
+ //# debugId=15ac44c0-1e9f-5725-b675-7e5e00ca51a4