document-model 6.2.3-dev.101 → 6.2.3-dev.102

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -651,72 +651,7 @@ function printSchemaSegment(definitions, known = definitions) {
651
651
  return `${definitions.map((definition) => printNamedDefinition(definition, inventory)).join(`${LINE}${LINE}`)}${LINE}`;
652
652
  }
653
653
  //#endregion
654
- //#region src/definition/compiler/segments.ts
655
- function referencedNames(definition) {
656
- const names = [];
657
- const visit = (reference) => {
658
- if (reference.kind === "list") {
659
- visit(reference.item);
660
- return;
661
- }
662
- if (reference.kind === "named") names.push(reference.name);
663
- };
664
- switch (definition.kind) {
665
- case "enum": return names;
666
- case "union": return definition.members;
667
- case "input":
668
- definition.fields.forEach((field) => visit(field.type));
669
- return names;
670
- case "object":
671
- case "interface":
672
- names.push(...definition.implements ?? []);
673
- for (const field of definition.fields) {
674
- field.args?.forEach((argument) => visit(argument.type));
675
- visit(field.type);
676
- }
677
- return names;
678
- }
679
- }
680
- function reachableFrom(rootName, index) {
681
- const reached = /* @__PURE__ */ new Set();
682
- if (rootName === null) return reached;
683
- const queue = [rootName];
684
- while (queue.length > 0) {
685
- const name = queue.pop();
686
- if (reached.has(name)) continue;
687
- const definition = index.get(name);
688
- if (definition === void 0) continue;
689
- reached.add(name);
690
- queue.push(...referencedNames(definition));
691
- }
692
- return reached;
693
- }
694
- function assignStoredSegments(input) {
695
- const stateIndex = new Map(input.types.map((definition) => [definition.name, definition]));
696
- const globalReach = reachableFrom(input.globalRoot, stateIndex);
697
- const localReach = reachableFrom(input.localRoot, stateIndex);
698
- const operationIndex = new Map(stateIndex);
699
- for (const operation of input.operations) if (operation.input !== null) operationIndex.set(operation.input.name, operation.input);
700
- const claimed = /* @__PURE__ */ new Set();
701
- const operations = /* @__PURE__ */ new Map();
702
- for (const operation of input.operations) {
703
- if (operation.input === null) continue;
704
- claimed.add(operation.input.name);
705
- const reached = reachableFrom(operation.input.name, operationIndex);
706
- const supporting = input.types.filter((definition) => definition.kind === "input" && reached.has(definition.name) && !claimed.has(definition.name));
707
- for (const definition of supporting) claimed.add(definition.name);
708
- operations.set(operation.key, [operation.input, ...supporting]);
709
- }
710
- const local = input.types.filter((definition) => definition.kind !== "input" && localReach.has(definition.name) && !globalReach.has(definition.name));
711
- const localDeclared = new Set(local.map((definition) => definition.name));
712
- return {
713
- global: input.types.filter((definition) => !localDeclared.has(definition.name) && !claimed.has(definition.name)),
714
- local,
715
- operations
716
- };
717
- }
718
- //#endregion
719
- //#region src/definition/compiler/graphql-projection.ts
654
+ //#region src/definition/compiler/graphql-nodes.ts
720
655
  const nameNode = (value) => ({
721
656
  kind: "Name",
722
657
  value
@@ -883,6 +818,73 @@ function definitionNode(definition, inventory) {
883
818
  };
884
819
  }
885
820
  }
821
+ //#endregion
822
+ //#region src/definition/compiler/segments.ts
823
+ function referencedNames(definition) {
824
+ const names = [];
825
+ const visit = (reference) => {
826
+ if (reference.kind === "list") {
827
+ visit(reference.item);
828
+ return;
829
+ }
830
+ if (reference.kind === "named") names.push(reference.name);
831
+ };
832
+ switch (definition.kind) {
833
+ case "enum": return names;
834
+ case "union": return definition.members;
835
+ case "input":
836
+ definition.fields.forEach((field) => visit(field.type));
837
+ return names;
838
+ case "object":
839
+ case "interface":
840
+ names.push(...definition.implements ?? []);
841
+ for (const field of definition.fields) {
842
+ field.args?.forEach((argument) => visit(argument.type));
843
+ visit(field.type);
844
+ }
845
+ return names;
846
+ }
847
+ }
848
+ function reachableFrom(rootName, index) {
849
+ const reached = /* @__PURE__ */ new Set();
850
+ if (rootName === null) return reached;
851
+ const queue = [rootName];
852
+ while (queue.length > 0) {
853
+ const name = queue.pop();
854
+ if (reached.has(name)) continue;
855
+ const definition = index.get(name);
856
+ if (definition === void 0) continue;
857
+ reached.add(name);
858
+ queue.push(...referencedNames(definition));
859
+ }
860
+ return reached;
861
+ }
862
+ function assignStoredSegments(input) {
863
+ const stateIndex = new Map(input.types.map((definition) => [definition.name, definition]));
864
+ const globalReach = reachableFrom(input.globalRoot, stateIndex);
865
+ const localReach = reachableFrom(input.localRoot, stateIndex);
866
+ const operationIndex = new Map(stateIndex);
867
+ for (const operation of input.operations) if (operation.input !== null) operationIndex.set(operation.input.name, operation.input);
868
+ const claimed = /* @__PURE__ */ new Set();
869
+ const operations = /* @__PURE__ */ new Map();
870
+ for (const operation of input.operations) {
871
+ if (operation.input === null) continue;
872
+ claimed.add(operation.input.name);
873
+ const reached = reachableFrom(operation.input.name, operationIndex);
874
+ const supporting = input.types.filter((definition) => definition.kind === "input" && reached.has(definition.name) && !claimed.has(definition.name));
875
+ for (const definition of supporting) claimed.add(definition.name);
876
+ operations.set(operation.key, [operation.input, ...supporting]);
877
+ }
878
+ const local = input.types.filter((definition) => definition.kind !== "input" && localReach.has(definition.name) && !globalReach.has(definition.name));
879
+ const localDeclared = new Set(local.map((definition) => definition.name));
880
+ return {
881
+ global: input.types.filter((definition) => !localDeclared.has(definition.name) && !claimed.has(definition.name)),
882
+ local,
883
+ operations
884
+ };
885
+ }
886
+ //#endregion
887
+ //#region src/definition/compiler/graphql-projection.ts
886
888
  function isPackageScalar(scalar) {
887
889
  return scalar.implementation.startsWith("package#");
888
890
  }
@@ -2555,6 +2557,14 @@ function interfaceConformanceProblems(definitions) {
2555
2557
  received: printTypeReference(field.type),
2556
2558
  repair: `Give ${received} a type compatible with ${expected}.`
2557
2559
  });
2560
+ const required = field?.args?.find((arg) => arg.type.required && arg.defaultValue === void 0 && !ifaceField.args?.some(({ name }) => name === arg.name));
2561
+ if (required !== void 0) problems.push({
2562
+ owner: owner.name,
2563
+ message: `${received} has the required argument ${required.name}, which the interface field ${expected} does not declare.`,
2564
+ expected: `no required argument beyond those of ${expected}`,
2565
+ received: `${required.name}: ${printTypeReference(required.type)}`,
2566
+ repair: `Make ${required.name} nullable or give it a default value.`
2567
+ });
2558
2568
  }
2559
2569
  }
2560
2570
  }
@@ -2581,11 +2591,13 @@ var DescriptorWalk = class {
2581
2591
  catalogScalars = /* @__PURE__ */ new Set();
2582
2592
  packageScalars = /* @__PURE__ */ new Map();
2583
2593
  #collector;
2594
+ #deferObjectFields;
2584
2595
  #built = /* @__PURE__ */ new Map();
2585
2596
  #visited = /* @__PURE__ */ new Set();
2586
2597
  #claims = /* @__PURE__ */ new Map();
2587
- constructor(collector) {
2598
+ constructor(collector, options = {}) {
2588
2599
  this.#collector = collector;
2600
+ this.#deferObjectFields = options.deferObjectFields ?? false;
2589
2601
  }
2590
2602
  visitType(candidate, position, path, options = {}) {
2591
2603
  if (!isTypeDescriptor(candidate)) {
@@ -2632,13 +2644,20 @@ var DescriptorWalk = class {
2632
2644
  });
2633
2645
  }
2634
2646
  }
2635
- checkInterfaceImplementations() {
2636
- for (const { owner, ...problem } of interfaceConformanceProblems(this.definitions)) this.#collector.add({
2647
+ checkInterfaceImplementations(definitions = this.definitions) {
2648
+ for (const { owner, ...problem } of interfaceConformanceProblems(definitions)) this.#collector.add({
2637
2649
  code: "PH-DM-INTERFACE-INVALID",
2638
2650
  path: this.#claims.get(owner)?.path ?? [],
2639
2651
  ...problem
2640
2652
  });
2641
2653
  }
2654
+ checkObjectFields(definitions) {
2655
+ for (const definition of definitions) {
2656
+ if (definition.kind !== "object" || definition.fields.length > 0) continue;
2657
+ const { kind, name } = definition;
2658
+ this.#noFields(kind, name, this.#claims.get(name)?.path ?? []);
2659
+ }
2660
+ }
2642
2661
  #namedDefinition(descriptor, path) {
2643
2662
  const name = this.#requireName(descriptor, path);
2644
2663
  switch (descriptor.kind) {
@@ -2726,15 +2745,8 @@ var DescriptorWalk = class {
2726
2745
  }
2727
2746
  }
2728
2747
  #requireFields(fields, kind, name, path) {
2729
- if (Object.keys(fields).length === 0) {
2730
- this.#collector.add({
2731
- code: "PH-DM-DECLARATION-INVALID",
2732
- path: [...path, "fields"],
2733
- message: `The ${kind} type ${JSON.stringify(name)} declares no fields, and GraphQL cannot build a schema that contains it.`,
2734
- expected: "at least one field",
2735
- received: "no fields",
2736
- repair: `Give ${JSON.stringify(name)} a field, or remove it from the model. Only ph.input({ fields: {} }) may be member-less, because it projects _empty: Boolean.`
2737
- });
2748
+ if (Object.keys(fields).length === 0 && !(kind === "object" && this.#deferObjectFields)) {
2749
+ this.#noFields(kind, name, path);
2738
2750
  throw new WalkAbort();
2739
2751
  }
2740
2752
  return Object.entries(fields).map(([key, field]) => ({
@@ -2750,6 +2762,16 @@ var DescriptorWalk = class {
2750
2762
  ...directivesOf(field)
2751
2763
  }));
2752
2764
  }
2765
+ #noFields(kind, name, path) {
2766
+ this.#collector.add({
2767
+ code: "PH-DM-DECLARATION-INVALID",
2768
+ path: [...path, "fields"],
2769
+ message: `The ${kind} type ${JSON.stringify(name)} declares no fields, and GraphQL cannot build a schema that contains it.`,
2770
+ expected: "at least one field",
2771
+ received: "no fields",
2772
+ repair: `Give ${JSON.stringify(name)} a field, or remove it from the model. Only ph.input({ fields: {} }) may be member-less, because it projects _empty: Boolean.`
2773
+ });
2774
+ }
2753
2775
  #inputFields(owner, path) {
2754
2776
  return Object.entries(owner.fields).map(([key, field]) => {
2755
2777
  const defaultValue = fieldDefault(field);
@@ -4065,8 +4087,20 @@ function normalizeScopes(collector, value, names) {
4065
4087
  });
4066
4088
  return [];
4067
4089
  });
4068
- const global = normalizeScope(collector, scopes.global, "global", names.global);
4069
- const local = normalizeScope(collector, scopes.local, "local", names.local);
4090
+ if (scopes.global === void 0) collector.add({
4091
+ code: "PH-DM-DECLARATION-INVALID",
4092
+ path: [...path, "global"],
4093
+ message: "A document model must declare a global scope; only local can be omitted.",
4094
+ expected: "a global scope declaration",
4095
+ received: "absent",
4096
+ repair: `Add global: { schema: ph.object(${JSON.stringify(names.global)}, { fields: { ... } }), initialValue: { ... } }.`
4097
+ });
4098
+ const global = scopes.global === void 0 ? void 0 : normalizeScope(collector, scopes.global, "global", names.global);
4099
+ const local = scopes.local === void 0 ? {
4100
+ root: null,
4101
+ initialValue: {},
4102
+ examples: []
4103
+ } : normalizeScope(collector, scopes.local, "local", names.local);
4070
4104
  if (global === void 0 || global.root === null || local === void 0) return;
4071
4105
  return {
4072
4106
  auxiliaryTypes,
@@ -5692,6 +5726,772 @@ function materialize(definition) {
5692
5726
  return materializeFamily(family.versions, copyUpgradeManifest(family.upgradeManifest));
5693
5727
  }
5694
5728
  //#endregion
5695
- export { ConsoleLogger, DefinitionError, DocumentModelController, PHDocumentController, assertIsDocumentOfType, assertIsStateOfType, childLogger, defineDocumentModel, defineDocumentModelFamily, documentModelCreateDocument, documentModelCreateState, documentModelDocumentModelModule, inspectDocumentModelDefinition, isDocumentOfType, isStateOfType, logger, materialize, operationsByActionType, ph, projectDocumentModelGraphQL, setErrorHandler, setLogLevel };
5729
+ //#region src/definition/subgraph/diagnostic-codes.ts
5730
+ const subgraphDiagnostics = defineDiagnosticCatalog({
5731
+ "PH-SG-NAME-INVALID": {
5732
+ severity: "error",
5733
+ phase: "definition",
5734
+ meaning: "A subgraph name is not lowercase kebab-case"
5735
+ },
5736
+ "PH-SG-ENTRY-INVALID": {
5737
+ severity: "error",
5738
+ phase: "definition",
5739
+ meaning: "A subgraph declares no entries, or an entry is not built by the entry builders or has malformed options"
5740
+ },
5741
+ "PH-SG-RESOLVER-MISSING": {
5742
+ severity: "error",
5743
+ phase: "definition",
5744
+ meaning: "An entry has no resolve, subscribe, or resolveType function where it needs one"
5745
+ },
5746
+ "PH-SG-DUPLICATE-COORDINATE": {
5747
+ severity: "error",
5748
+ phase: "definition",
5749
+ meaning: "Two entries, or an entry and a declared field, bind the same schema coordinate"
5750
+ },
5751
+ "PH-SG-FIELD-PARENT-INVALID": {
5752
+ severity: "error",
5753
+ phase: "definition",
5754
+ meaning: "A computed field's parent is not an object type that the subgraph's entries reach"
5755
+ },
5756
+ "PH-SG-RESOLVE-TYPE-INVALID": {
5757
+ severity: "error",
5758
+ phase: "definition",
5759
+ meaning: "resolveType names a type that is not an interface or union that the subgraph's entries reach"
5760
+ },
5761
+ "PH-SG-INTERFACE-UNIMPLEMENTED": {
5762
+ severity: "warning",
5763
+ phase: "definition",
5764
+ meaning: "An interface the subgraph serves has no object type in the subgraph that implements it"
5765
+ },
5766
+ "PH-SG-FEDERATION-UNSUPPORTED": {
5767
+ severity: "error",
5768
+ phase: "definition",
5769
+ meaning: "A typed subgraph uses an Apollo Federation directive or declares a Query field Federation adds"
5770
+ }
5771
+ }, compilerDiagnostics);
5772
+ //#endregion
5773
+ //#region src/definition/subgraph/entries.ts
5774
+ const records = getGlobalRegistry("powerhouse.document-model.subgraph-entries.v1", () => /* @__PURE__ */ new WeakMap());
5775
+ function readEntry(value) {
5776
+ return value !== null && typeof value === "object" ? records.get(value) : void 0;
5777
+ }
5778
+ function register(record) {
5779
+ const entry = Object.freeze({ kind: record.kind });
5780
+ records.set(entry, Object.freeze(record));
5781
+ return entry;
5782
+ }
5783
+ const FIELD_SPEC_KEYS = [
5784
+ "args",
5785
+ "type",
5786
+ "description",
5787
+ "deprecated"
5788
+ ];
5789
+ function argsInput(value, path) {
5790
+ if (value === void 0) return null;
5791
+ const members = snapshotFieldMap(value, path);
5792
+ const keys = Object.keys(members);
5793
+ if (keys.length === 0) return null;
5794
+ for (const key of keys) {
5795
+ assertAuthoredName(key, [...path, key]);
5796
+ assertFieldUse(members[key], [...path, key]);
5797
+ }
5798
+ return ph.input({ fields: members });
5799
+ }
5800
+ function entryField(collector, name, config) {
5801
+ const validName = collector.capture(() => assertAuthoredName(name, ["name"]));
5802
+ const args = collector.capture(() => argsInput(config.args, ["spec", "args"]));
5803
+ const type = collector.capture(() => {
5804
+ if (config.type === void 0) subgraphDiagnostics.fail({
5805
+ code: "PH-SG-ENTRY-INVALID",
5806
+ path: ["spec", "type"],
5807
+ message: "The entry declares no type.",
5808
+ repair: "Add type: a field use such as ph.String() or ph.ref(SomeType)."
5809
+ });
5810
+ assertFieldUse(config.type, ["spec", "type"]);
5811
+ return config.type;
5812
+ });
5813
+ const description = collector.capture(() => stringOption(config, "description", ["spec"]));
5814
+ const deprecated = collector.capture(() => stringOption(config, "deprecated", ["spec"]));
5815
+ if (validName === void 0 || args === void 0 || type === void 0 || description === void 0 || deprecated === void 0) return;
5816
+ return {
5817
+ name: validName,
5818
+ args,
5819
+ type,
5820
+ description,
5821
+ deprecated
5822
+ };
5823
+ }
5824
+ function resolverOption(collector, value, path, subject) {
5825
+ if (typeof value === "function") return value;
5826
+ collector.add({
5827
+ code: "PH-SG-RESOLVER-MISSING",
5828
+ path,
5829
+ message: `${subject} has no ${String(path.at(-1))} function.`,
5830
+ expected: "a function",
5831
+ received: describeReceived(value),
5832
+ repair: `Add ${String(path.at(-1))}: a function that takes { parent, args, request, info, subgraph }.`
5833
+ });
5834
+ }
5835
+ function snapshotSpec(collector, spec, keys) {
5836
+ return collector.capture(() => snapshotDescriptorOptions(spec, keys, ["spec"]));
5837
+ }
5838
+ function rootEntry(kind, name, spec) {
5839
+ const collector = new DefinitionDiagnosticCollector(subgraphDiagnostics);
5840
+ const functions = kind === "subscription" ? ["subscribe", "resolve"] : ["resolve"];
5841
+ const config = snapshotSpec(collector, spec, [...FIELD_SPEC_KEYS, ...functions]);
5842
+ if (config === void 0) return register({
5843
+ kind,
5844
+ diagnostics: collector.diagnostics
5845
+ });
5846
+ const field = entryField(collector, name, config);
5847
+ const subject = `${kind} ${JSON.stringify(field?.name ?? name)}`;
5848
+ if (kind === "subscription") {
5849
+ const subscribe = resolverOption(collector, config.subscribe, ["spec", "subscribe"], subject);
5850
+ const resolve = config.resolve === void 0 ? void 0 : resolverOption(collector, config.resolve, ["spec", "resolve"], subject);
5851
+ return register({
5852
+ kind,
5853
+ ...field !== void 0 && { field },
5854
+ ...subscribe !== void 0 && { subscribe },
5855
+ ...resolve !== void 0 && { resolve },
5856
+ diagnostics: collector.diagnostics
5857
+ });
5858
+ }
5859
+ const resolve = resolverOption(collector, config.resolve, ["spec", "resolve"], subject);
5860
+ return register({
5861
+ kind,
5862
+ ...field !== void 0 && { field },
5863
+ ...resolve !== void 0 && { resolve },
5864
+ diagnostics: collector.diagnostics
5865
+ });
5866
+ }
5867
+ function computedFieldEntry(parent, name, spec) {
5868
+ const collector = new DefinitionDiagnosticCollector(subgraphDiagnostics);
5869
+ const objectParent = isTypeDescriptor(parent) && parent.kind === "object" ? parent : void 0;
5870
+ if (objectParent === void 0) collector.add({
5871
+ code: "PH-SG-FIELD-PARENT-INVALID",
5872
+ path: ["parent"],
5873
+ message: "A computed field's parent must be an object type.",
5874
+ expected: "a descriptor returned by ph.object",
5875
+ received: isTypeDescriptor(parent) ? `${parent.kind} ${JSON.stringify(parent.name)}` : describeReceived(parent),
5876
+ repair: "Pass the ph.object type the field belongs to."
5877
+ });
5878
+ const config = snapshotSpec(collector, spec, [...FIELD_SPEC_KEYS, "resolve"]);
5879
+ if (config === void 0) return register({
5880
+ kind: "computed-field",
5881
+ diagnostics: collector.diagnostics
5882
+ });
5883
+ const field = entryField(collector, name, config);
5884
+ const resolve = resolverOption(collector, config.resolve, ["spec", "resolve"], `field ${JSON.stringify(field?.name ?? name)}`);
5885
+ return register({
5886
+ kind: "computed-field",
5887
+ ...objectParent !== void 0 && { parent: objectParent },
5888
+ ...field !== void 0 && { field },
5889
+ ...resolve !== void 0 && { resolve },
5890
+ diagnostics: collector.diagnostics
5891
+ });
5892
+ }
5893
+ function resolveTypeEntry(type, resolveType) {
5894
+ const collector = new DefinitionDiagnosticCollector(subgraphDiagnostics);
5895
+ const abstract = isTypeDescriptor(type) && (type.kind === "interface" || type.kind === "union") ? type : void 0;
5896
+ if (abstract === void 0) collector.add({
5897
+ code: "PH-SG-RESOLVE-TYPE-INVALID",
5898
+ path: ["type"],
5899
+ message: "resolveType takes an interface or a union.",
5900
+ expected: "a descriptor returned by ph.interface or ph.union",
5901
+ received: isTypeDescriptor(type) ? `${type.kind} ${JSON.stringify(type.name)}` : describeReceived(type),
5902
+ repair: "Pass the abstract type. An object type needs no resolveType; GraphQL knows its type."
5903
+ });
5904
+ const resolver = resolverOption(collector, resolveType, ["resolveType"], `resolveType for ${abstract?.name ?? "this type"}`);
5905
+ return register({
5906
+ kind: "resolve-type",
5907
+ ...abstract !== void 0 && { type: abstract },
5908
+ ...resolver !== void 0 && { resolveType: resolver },
5909
+ diagnostics: collector.diagnostics
5910
+ });
5911
+ }
5912
+ function typeEntry(type) {
5913
+ const collector = new DefinitionDiagnosticCollector(subgraphDiagnostics);
5914
+ if (!isTypeDescriptor(type)) collector.add({
5915
+ code: "PH-SG-ENTRY-INVALID",
5916
+ path: ["type"],
5917
+ message: "type takes a named type.",
5918
+ expected: "a descriptor returned by ph.object, ph.interface, ph.union, ph.enum, or ph.input",
5919
+ received: describeReceived(type),
5920
+ repair: "Pass the type the subgraph serves, such as an object type."
5921
+ });
5922
+ return register({
5923
+ kind: "type",
5924
+ ...isTypeDescriptor(type) && { type },
5925
+ diagnostics: collector.diagnostics
5926
+ });
5927
+ }
5928
+ const builders = Object.freeze({
5929
+ query: (name, spec) => rootEntry("query", name, spec),
5930
+ mutation: (name, spec) => rootEntry("mutation", name, spec),
5931
+ subscription: (name, spec) => rootEntry("subscription", name, spec),
5932
+ field: computedFieldEntry,
5933
+ resolveType: resolveTypeEntry,
5934
+ type: typeEntry
5935
+ });
5936
+ /**
5937
+ * @experimental The builders a code-first subgraph declares its entries
5938
+ * with. Each call returns a frozen entry; `compileSubgraph` reports what is
5939
+ * wrong with it instead of the builder throwing.
5940
+ */
5941
+ function createSubgraphEntryBuilders() {
5942
+ return builders;
5943
+ }
5944
+ //#endregion
5945
+ //#region src/definition/subgraph/federation.ts
5946
+ /**
5947
+ * The directives Apollo Federation 1 and 2 define. Entities and federation
5948
+ * composition are out of scope for typed subgraphs, so their directives are
5949
+ * refused rather than projected into a schema that composes differently.
5950
+ */
5951
+ const FEDERATION_DIRECTIVES = /* @__PURE__ */ new Set([
5952
+ "key",
5953
+ "extends",
5954
+ "external",
5955
+ "requires",
5956
+ "provides",
5957
+ "shareable",
5958
+ "inaccessible",
5959
+ "override",
5960
+ "link",
5961
+ "tag",
5962
+ "composeDirective",
5963
+ "interfaceObject",
5964
+ "authenticated",
5965
+ "requiresScopes",
5966
+ "policy",
5967
+ "context",
5968
+ "fromContext",
5969
+ "cost",
5970
+ "listSize"
5971
+ ]);
5972
+ /**
5973
+ * The `Query` fields Apollo's `buildSubgraphSchema` adds to every subgraph,
5974
+ * so an entry may not declare them.
5975
+ */
5976
+ const FEDERATION_QUERY_FIELDS = /* @__PURE__ */ new Set(["_service", "_entities"]);
5977
+ function refused(directives, path) {
5978
+ return (directives ?? []).flatMap((directive, index) => FEDERATION_DIRECTIVES.has(directive.name) ? [{
5979
+ name: directive.name,
5980
+ path: [
5981
+ ...path,
5982
+ "directives",
5983
+ index
5984
+ ]
5985
+ }] : []);
5986
+ }
5987
+ function inArguments(args, path) {
5988
+ return (args ?? []).flatMap((argument) => refused(argument.directives, [
5989
+ ...path,
5990
+ "args",
5991
+ argument.name
5992
+ ]));
5993
+ }
5994
+ function inFields(fields, path) {
5995
+ return fields.flatMap((field) => {
5996
+ const fieldPath = [
5997
+ ...path,
5998
+ "fields",
5999
+ field.name
6000
+ ];
6001
+ return [...refused(field.directives, fieldPath), ..."args" in field ? inArguments(field.args, fieldPath) : []];
6002
+ });
6003
+ }
6004
+ function federationDirectiveUses(types) {
6005
+ return types.flatMap((type) => {
6006
+ const path = ["types", type.name];
6007
+ switch (type.kind) {
6008
+ case "enum": return type.values.flatMap((value) => refused(value.directives, [
6009
+ ...path,
6010
+ "values",
6011
+ value.name
6012
+ ]));
6013
+ case "object":
6014
+ case "interface":
6015
+ case "input": return inFields(type.fields, path);
6016
+ case "union": return [];
6017
+ }
6018
+ });
6019
+ }
6020
+ //#endregion
6021
+ //#region src/definition/subgraph/projection.ts
6022
+ const ROOT_TYPES = {
6023
+ query: "Query",
6024
+ mutation: "Mutation",
6025
+ subscription: "Subscription"
6026
+ };
6027
+ function subgraphRootTypes(definition) {
6028
+ return [
6029
+ "query",
6030
+ "mutation",
6031
+ "subscription"
6032
+ ].flatMap((kind) => {
6033
+ const fields = definition.entries.flatMap((entry) => entry.kind === kind ? [{
6034
+ key: entry.key,
6035
+ name: entry.fieldName,
6036
+ description: entry.description,
6037
+ deprecated: entry.deprecated,
6038
+ args: entry.args,
6039
+ type: entry.returns
6040
+ }] : []);
6041
+ return fields.length === 0 ? [] : [{
6042
+ kind: "object",
6043
+ name: ROOT_TYPES[kind],
6044
+ description: null,
6045
+ fields
6046
+ }];
6047
+ });
6048
+ }
6049
+ /**
6050
+ * @experimental The GraphQL document a subgraph definition serves, without
6051
+ * locations, in the definition's print order. A typed definition declares
6052
+ * the catalog and project scalars it uses as `scalar` definitions.
6053
+ */
6054
+ function projectSubgraphGraphQL(definition) {
6055
+ if (definition.schemaKind === "graphql-ast-compat") return definition.document;
6056
+ const roots = subgraphRootTypes(definition);
6057
+ const inventory = new Map([...definition.types, ...roots].map((type) => [type.name, type]));
6058
+ const scalars = new Set(definition.scalars.map(({ name }) => name));
6059
+ return {
6060
+ kind: "Document",
6061
+ definitions: definition.definitionOrder.flatMap((name) => {
6062
+ if (scalars.has(name)) return [{
6063
+ kind: "ScalarTypeDefinition",
6064
+ name: nameNode(name),
6065
+ directives: []
6066
+ }];
6067
+ const type = inventory.get(name);
6068
+ if (type === void 0) throw new TypeError(`definitionOrder names ${name}, which the subgraph definition does not declare.`);
6069
+ return [definitionNode(type, inventory)];
6070
+ })
6071
+ };
6072
+ }
6073
+ //#endregion
6074
+ //#region src/definition/subgraph/compile.ts
6075
+ const SUBGRAPH_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
6076
+ const ROOT_NAMES = new Set(Object.values(ROOT_TYPES));
6077
+ /**
6078
+ * The walk takes named types, so an entry's arguments and output type go
6079
+ * through it as hidden types it never emits: the arguments as a named
6080
+ * input, the output type as the only field of an object. The walk then
6081
+ * resolves, claims and checks them as it does any type. The `__` prefix
6082
+ * keeps their names from colliding with an authored type.
6083
+ */
6084
+ function hiddenArgs(name, args) {
6085
+ return registerTypeDescriptor(Object.freeze({
6086
+ ...args,
6087
+ name,
6088
+ identity: Object.freeze({
6089
+ kind: "input",
6090
+ name,
6091
+ description: null
6092
+ })
6093
+ }));
6094
+ }
6095
+ function hiddenOutput(name, field) {
6096
+ const descriptor = {
6097
+ kind: "object",
6098
+ role: NAMED_TYPE_ROLE,
6099
+ name,
6100
+ description: null,
6101
+ fields: Object.freeze({ [field.name]: field.type }),
6102
+ implements: Object.freeze([]),
6103
+ identity: Object.freeze({
6104
+ kind: "object",
6105
+ name,
6106
+ description: null
6107
+ }),
6108
+ validator: void 0
6109
+ };
6110
+ descriptor.validator = buildValidator(descriptor);
6111
+ return registerTypeDescriptor(Object.freeze(descriptor));
6112
+ }
6113
+ var SubgraphWalk = class {
6114
+ walk;
6115
+ #collector;
6116
+ #coordinates = /* @__PURE__ */ new Map();
6117
+ #hidden = 0;
6118
+ constructor(collector) {
6119
+ this.#collector = collector;
6120
+ this.walk = new DescriptorWalk(collector, { deferObjectFields: true });
6121
+ }
6122
+ claim(coordinate, path) {
6123
+ const first = this.#coordinates.get(coordinate);
6124
+ if (first === void 0) {
6125
+ this.#coordinates.set(coordinate, path);
6126
+ return true;
6127
+ }
6128
+ this.#collector.add({
6129
+ code: "PH-SG-DUPLICATE-COORDINATE",
6130
+ path,
6131
+ message: `${coordinate} is bound twice.`,
6132
+ expected: "one entry per schema coordinate",
6133
+ received: coordinate,
6134
+ repair: "Remove one of the two entries, or rename one of the fields.",
6135
+ related: [{
6136
+ path: first,
6137
+ message: "First bound here."
6138
+ }]
6139
+ });
6140
+ return false;
6141
+ }
6142
+ field(field, path) {
6143
+ const index = this.#hidden++;
6144
+ let args = [];
6145
+ if (field.args !== null) {
6146
+ const input = this.walk.visitType(hiddenArgs(`__SubgraphArgs${index}`, field.args), "input", [...path, "args"], { emit: false });
6147
+ args = input?.kind === "input" ? input.fields : void 0;
6148
+ }
6149
+ const output = this.walk.visitType(hiddenOutput(`__SubgraphField${index}`, field), "output", path, { emit: false });
6150
+ const type = output?.kind === "object" ? output.fields[0]?.type : void 0;
6151
+ return args === void 0 || type === void 0 ? void 0 : {
6152
+ args,
6153
+ type
6154
+ };
6155
+ }
6156
+ reached(descriptor, path) {
6157
+ if (!this.walk.definitions.some(({ name }) => name === descriptor.name)) return;
6158
+ return this.walk.visitType(descriptor, "output", path, { emit: false });
6159
+ }
6160
+ };
6161
+ function subgraphScalars(catalogScalars, packageScalars) {
6162
+ const catalog = documentModelScalars.map(({ name }) => name).filter((name) => catalogScalars.has(name)).map((name) => ({
6163
+ name,
6164
+ implementation: `powerhouse.catalog#${name}`,
6165
+ graphQLProfile: "legacy-graphql-default-v1"
6166
+ }));
6167
+ const declared = [...packageScalars].sort(([left], [right]) => compareCodeUnits(left, right)).map(([name, definition]) => ({
6168
+ name,
6169
+ implementation: `package#${name}`,
6170
+ graphQLProfile: "declared-coercion-v1",
6171
+ definition: storedScalarDefinition(definition)
6172
+ }));
6173
+ return [...catalog, ...declared];
6174
+ }
6175
+ function readEntries(collector, entries) {
6176
+ if (!Array.isArray(entries) || entries.length === 0) {
6177
+ collector.add({
6178
+ code: "PH-SG-ENTRY-INVALID",
6179
+ path: ["entries"],
6180
+ message: "A subgraph must declare at least one entry.",
6181
+ expected: "a nonempty array of entries",
6182
+ received: Array.isArray(entries) ? "empty array" : describeReceived(entries),
6183
+ repair: "Return the entries the builders made, such as [schema.query(...)]."
6184
+ });
6185
+ return [];
6186
+ }
6187
+ return entries.map((entry, index) => {
6188
+ const record = readEntry(entry);
6189
+ if (record === void 0) {
6190
+ collector.add({
6191
+ code: "PH-SG-ENTRY-INVALID",
6192
+ path: ["entries", index],
6193
+ message: "This entry was not made by the subgraph entry builders.",
6194
+ received: describeReceived(entry),
6195
+ repair: "Make each entry with query, mutation, subscription, field, resolveType, or type."
6196
+ });
6197
+ return;
6198
+ }
6199
+ collector.merge(record.diagnostics.map((diagnostic) => ({
6200
+ ...diagnostic,
6201
+ path: [
6202
+ "entries",
6203
+ index,
6204
+ ...diagnostic.path
6205
+ ]
6206
+ })));
6207
+ return record;
6208
+ });
6209
+ }
6210
+ function checkName(collector, name) {
6211
+ if (typeof name === "string" && SUBGRAPH_NAME.test(name)) return;
6212
+ collector.add({
6213
+ code: "PH-SG-NAME-INVALID",
6214
+ path: ["name"],
6215
+ message: "A subgraph name must be lowercase kebab-case. It is the route segment and is never normalized.",
6216
+ expected: "a name such as invoices or invoice-payments",
6217
+ received: typeof name === "string" ? name : describeReceived(name),
6218
+ repair: "Use lowercase letters and digits, separated by single hyphens, starting with a letter."
6219
+ });
6220
+ }
6221
+ function checkInterfaceImplementers(collector, types) {
6222
+ const implemented = new Set(types.flatMap((type) => type.kind === "object" ? type.implements ?? [] : []));
6223
+ for (const type of types) {
6224
+ if (type.kind !== "interface" || implemented.has(type.name)) continue;
6225
+ collector.add({
6226
+ code: "PH-SG-INTERFACE-UNIMPLEMENTED",
6227
+ path: ["types", type.name],
6228
+ message: `No object type of this subgraph implements the interface ${type.name}, so a field that returns it can only return null.`,
6229
+ expected: `an object type that implements ${type.name}`,
6230
+ received: type.name,
6231
+ repair: `Add schema.type(<Implementer>) for each object type that implements ${type.name}.`
6232
+ });
6233
+ }
6234
+ }
6235
+ /**
6236
+ * @experimental Compiles a code-first subgraph's entries into its stored
6237
+ * definition, plus the functions a host binds to each schema coordinate.
6238
+ * It never throws for an invalid declaration; it reports diagnostics.
6239
+ */
6240
+ function compileSubgraph(input) {
6241
+ const { name } = input;
6242
+ const collector = new DefinitionDiagnosticCollector(subgraphDiagnostics, typeof name === "string" ? {
6243
+ kind: "subgraph",
6244
+ key: name
6245
+ } : void 0);
6246
+ checkName(collector, name);
6247
+ const records = readEntries(collector, input.entries);
6248
+ const subgraph = new SubgraphWalk(collector);
6249
+ const entries = [];
6250
+ const bindings = /* @__PURE__ */ new Map();
6251
+ const computed = /* @__PURE__ */ new Map();
6252
+ records.forEach((record, index) => {
6253
+ if (record === void 0 || record.kind !== "query" && record.kind !== "mutation" && record.kind !== "subscription" || record.field === void 0) return;
6254
+ const path = ["entries", index];
6255
+ const typeName = ROOT_TYPES[record.kind];
6256
+ const fieldName = record.field.name;
6257
+ const coordinate = `${typeName}.${fieldName}`;
6258
+ if (record.kind === "query" && FEDERATION_QUERY_FIELDS.has(fieldName)) {
6259
+ collector.add({
6260
+ code: "PH-SG-FEDERATION-UNSUPPORTED",
6261
+ path,
6262
+ message: `${coordinate} is a field Apollo Federation adds to every subgraph.`,
6263
+ received: coordinate,
6264
+ repair: "Rename the query field."
6265
+ });
6266
+ return;
6267
+ }
6268
+ if (!subgraph.claim(coordinate, path)) return;
6269
+ const parts = subgraph.field(record.field, path);
6270
+ if (parts === void 0) return;
6271
+ entries.push({
6272
+ kind: record.kind,
6273
+ key: fieldName,
6274
+ fieldName,
6275
+ description: record.field.description,
6276
+ deprecated: record.field.deprecated,
6277
+ args: parts.args,
6278
+ returns: parts.type,
6279
+ access: { kind: "manual" }
6280
+ });
6281
+ if (record.kind === "subscription") {
6282
+ if (record.subscribe === void 0) return;
6283
+ bindings.set(coordinate, {
6284
+ kind: "subscription",
6285
+ typeName: "Subscription",
6286
+ fieldName,
6287
+ subscribe: record.subscribe,
6288
+ ...record.resolve !== void 0 && { resolve: record.resolve }
6289
+ });
6290
+ } else if (record.resolve !== void 0) bindings.set(coordinate, {
6291
+ kind: record.kind,
6292
+ typeName,
6293
+ fieldName,
6294
+ resolve: record.resolve
6295
+ });
6296
+ });
6297
+ records.forEach((record, index) => {
6298
+ if (record?.kind !== "type" || record.type === void 0) return;
6299
+ subgraph.walk.visitType(record.type, record.type.kind === "input" ? "input" : "output", [
6300
+ "entries",
6301
+ index,
6302
+ "type"
6303
+ ]);
6304
+ });
6305
+ let pending = records.flatMap((record, index) => record?.kind === "computed-field" && record.parent !== void 0 && record.field !== void 0 ? [{
6306
+ record,
6307
+ parent: record.parent,
6308
+ field: record.field,
6309
+ index
6310
+ }] : []);
6311
+ for (let progressed = true; progressed;) {
6312
+ progressed = false;
6313
+ pending = pending.filter(({ record, parent, field, index }) => {
6314
+ const path = ["entries", index];
6315
+ const definition = subgraph.reached(parent, [...path, "parent"]);
6316
+ if (definition === void 0) return true;
6317
+ progressed = true;
6318
+ if (definition.kind !== "object") return false;
6319
+ const coordinate = `${definition.name}.${field.name}`;
6320
+ if (definition.fields.some(({ name }) => name === field.name)) {
6321
+ collector.add({
6322
+ code: "PH-SG-DUPLICATE-COORDINATE",
6323
+ path: [...path, "name"],
6324
+ message: `${definition.name} already declares the field ${field.name}.`,
6325
+ expected: "a field name the object type does not declare",
6326
+ received: coordinate,
6327
+ repair: `Rename the computed field, or remove ${field.name} from ${definition.name}'s fields.`
6328
+ });
6329
+ return false;
6330
+ }
6331
+ if (!subgraph.claim(coordinate, path)) return false;
6332
+ const parts = subgraph.field(field, path);
6333
+ if (parts === void 0) return false;
6334
+ computed.set(definition.name, [...computed.get(definition.name) ?? [], {
6335
+ key: field.name,
6336
+ name: field.name,
6337
+ description: field.description,
6338
+ deprecated: field.deprecated,
6339
+ ...parts.args.length > 0 && { args: parts.args },
6340
+ type: parts.type
6341
+ }]);
6342
+ entries.push({
6343
+ kind: "computed-field",
6344
+ typeName: definition.name,
6345
+ fieldName: field.name,
6346
+ access: { kind: "manual" }
6347
+ });
6348
+ if (record.resolve !== void 0) bindings.set(coordinate, {
6349
+ kind: "computed-field",
6350
+ typeName: definition.name,
6351
+ fieldName: field.name,
6352
+ resolve: record.resolve
6353
+ });
6354
+ return false;
6355
+ });
6356
+ }
6357
+ for (const { parent, index } of pending) collector.add({
6358
+ code: "PH-SG-FIELD-PARENT-INVALID",
6359
+ path: [
6360
+ "entries",
6361
+ index,
6362
+ "parent"
6363
+ ],
6364
+ message: `No entry of this subgraph reaches the object type ${parent.name ?? "(anonymous)"}, so the computed field has no parent in the schema.`,
6365
+ received: parent.name ?? "(anonymous)",
6366
+ repair: `Return ${parent.name ?? "the type"} from a query, mutation, subscription, or computed field, or remove the computed field.`
6367
+ });
6368
+ records.forEach((record, index) => {
6369
+ if (record?.kind !== "resolve-type" || record.type === void 0) return;
6370
+ const path = ["entries", index];
6371
+ const definition = subgraph.reached(record.type, [...path, "type"]);
6372
+ if (definition === void 0) {
6373
+ collector.add({
6374
+ code: "PH-SG-RESOLVE-TYPE-INVALID",
6375
+ path: [...path, "type"],
6376
+ message: `No entry of this subgraph reaches ${record.type.name ?? "(anonymous)"}.`,
6377
+ received: record.type.name ?? "(anonymous)",
6378
+ repair: `Return ${record.type.name ?? "the type"} from an entry, or remove its resolveType.`
6379
+ });
6380
+ return;
6381
+ }
6382
+ if (!subgraph.claim(definition.name, path)) return;
6383
+ entries.push({
6384
+ kind: "resolve-type",
6385
+ typeName: definition.name,
6386
+ access: { kind: "manual" }
6387
+ });
6388
+ if (record.resolveType !== void 0) bindings.set(definition.name, {
6389
+ kind: "resolve-type",
6390
+ typeName: definition.name,
6391
+ fieldName: null,
6392
+ resolveType: record.resolveType
6393
+ });
6394
+ });
6395
+ const { walk } = subgraph;
6396
+ const types = walk.definitions.map((type) => {
6397
+ const fields = computed.get(type.name);
6398
+ return fields === void 0 || type.kind !== "object" ? type : {
6399
+ ...type,
6400
+ fields: [...type.fields, ...fields]
6401
+ };
6402
+ });
6403
+ walk.checkObjectFields(types);
6404
+ walk.checkInterfaceImplementations(types);
6405
+ checkInterfaceImplementers(collector, types);
6406
+ walk.checkInputCycles();
6407
+ const named = [...types.map(({ kind, name }) => ({
6408
+ kind,
6409
+ name,
6410
+ group: "types"
6411
+ })), ...[...walk.packageScalars.keys()].map((name) => ({
6412
+ kind: "scalar",
6413
+ name,
6414
+ group: "scalars"
6415
+ }))];
6416
+ for (const { kind, name, group } of named) {
6417
+ if (!ROOT_NAMES.has(name)) continue;
6418
+ collector.add({
6419
+ code: "PH-DM-DUPLICATE-NAME",
6420
+ path: [group, name],
6421
+ message: `GraphQL type name ${name} is a subgraph root type.`,
6422
+ expected: "a type name other than Query, Mutation, and Subscription",
6423
+ received: name,
6424
+ repair: `Rename the ${kind} type; the subgraph declares ${name} from its entries.`
6425
+ });
6426
+ }
6427
+ const roots = subgraphRootTypes({ entries });
6428
+ for (const use of federationDirectiveUses([...roots, ...types])) collector.add({
6429
+ code: "PH-SG-FEDERATION-UNSUPPORTED",
6430
+ path: use.path,
6431
+ message: `@${use.name} is an Apollo Federation directive, which a typed subgraph does not support.`,
6432
+ received: `@${use.name}`,
6433
+ repair: "Remove the directive. Federation entities are not supported yet."
6434
+ });
6435
+ const diagnostics = collector.diagnostics;
6436
+ if (diagnostics.some(({ severity }) => severity === "error")) return {
6437
+ bindings: /* @__PURE__ */ new Map(),
6438
+ diagnostics
6439
+ };
6440
+ const scalars = subgraphScalars(walk.catalogScalars, walk.packageScalars);
6441
+ return {
6442
+ definition: {
6443
+ kind: "powerhouse.subgraph",
6444
+ formatVersion: 1,
6445
+ name,
6446
+ compositionPolicy: "host-current",
6447
+ federationProfile: "host-current",
6448
+ schemaKind: "typed",
6449
+ hasSubscriptions: entries.some(({ kind }) => kind === "subscription"),
6450
+ types,
6451
+ entries,
6452
+ scalars,
6453
+ definitionOrder: [
6454
+ ...scalars.map((scalar) => scalar.name),
6455
+ ...roots.map((root) => root.name),
6456
+ ...types.map((type) => type.name)
6457
+ ]
6458
+ },
6459
+ bindings,
6460
+ diagnostics
6461
+ };
6462
+ }
6463
+ //#endregion
6464
+ //#region src/definition/subgraph/protocol.ts
6465
+ /**
6466
+ * @experimental The static member that marks a code-first subgraph class.
6467
+ * `Symbol.for` makes it the same key in every copy of the package; the
6468
+ * protocol's `version` says which contract the class speaks.
6469
+ */
6470
+ const SUBGRAPH_PROTOCOL = Symbol.for("powerhouse.subgraph.protocol");
6471
+ /**
6472
+ * @experimental Reads the protocol of a subgraph export. It reads only the
6473
+ * static `SUBGRAPH_PROTOCOL` member of a function: it never constructs the
6474
+ * class or calls the protocol.
6475
+ */
6476
+ function readSubgraphProtocol(value) {
6477
+ if (typeof value !== "function") return { kind: "schema-first" };
6478
+ const protocol = value[SUBGRAPH_PROTOCOL];
6479
+ if (protocol === void 0) return { kind: "schema-first" };
6480
+ if (protocol === null || typeof protocol !== "object") return {
6481
+ kind: "unsupported",
6482
+ version: void 0
6483
+ };
6484
+ const candidate = protocol;
6485
+ if (candidate.version === 1 && typeof candidate.describe === "function" && typeof candidate.validate === "function") return {
6486
+ kind: "code-first",
6487
+ protocol
6488
+ };
6489
+ return {
6490
+ kind: "unsupported",
6491
+ version: candidate.version
6492
+ };
6493
+ }
6494
+ //#endregion
6495
+ export { ConsoleLogger, DefinitionError, DocumentModelController, PHDocumentController, SUBGRAPH_PROTOCOL, assertIsDocumentOfType, assertIsStateOfType, childLogger, compileSubgraph, createSubgraphEntryBuilders, defineDocumentModel, defineDocumentModelFamily, documentModelCreateDocument, documentModelCreateState, documentModelDocumentModelModule, inspectDocumentModelDefinition, isDocumentOfType, isStateOfType, logger, materialize, operationsByActionType, ph, projectDocumentModelGraphQL, projectSubgraphGraphQL, readSubgraphProtocol, setErrorHandler, setLogLevel };
5696
6496
 
5697
6497
  //# sourceMappingURL=index.js.map