@contello/client 3.0.2 → 3.1.1

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/cli.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
 
2
- export { };
2
+ export {}
package/dist/cli.js CHANGED
@@ -3,7 +3,7 @@
3
3
  const command = process.argv[2];
4
4
  switch (command) {
5
5
  case "generate":
6
- await import("./generate-D_j088z7.js");
6
+ await import("./generate-CqlYWWhF.js");
7
7
  break;
8
8
  default:
9
9
  console.error(command ? `unknown command: ${command}` : "usage: contello-client <command>");
@@ -2,7 +2,7 @@
2
2
  import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { glob } from "node:fs/promises";
4
4
  import { dirname, relative, resolve } from "node:path";
5
- import { Kind, NoFragmentCyclesRule, NoUnusedFragmentsRule, Source, buildClientSchema, doTypesOverlap, getIntrospectionQuery, getLocation, isCompositeType, isEnumType, isInputObjectType, isInterfaceType, isListType, isNonNullType, isObjectType, isScalarType, isUnionType, parse, print, specifiedRules, typeFromAST, validate, visit } from "graphql";
5
+ import { Kind, NoFragmentCyclesRule, NoUnusedFragmentsRule, Source, buildClientSchema, doTypesOverlap, getIntrospectionQuery, getLocation, isCompositeType, isEnumType, isInputObjectType, isInterfaceType, isListType, isNonNullType, isObjectType, isRequiredArgument, isScalarType, isUnionType, parse, print, specifiedRules, typeFromAST, validate, visit } from "graphql";
6
6
  import { pathToFileURL } from "node:url";
7
7
  //#region src/generate/config.ts
8
8
  const CONFIG_NAMES = [
@@ -86,10 +86,11 @@ function sortFragmentsByDependency(fragments) {
86
86
  return sorted;
87
87
  }
88
88
  function validateDocuments(schema, fragments, operations) {
89
- const errors = validate(schema, {
89
+ const combined = {
90
90
  kind: Kind.DOCUMENT,
91
91
  definitions: [...fragments.values(), ...operations]
92
- }, VALIDATION_RULES);
92
+ };
93
+ const errors = validate(schema, combined, VALIDATION_RULES);
93
94
  if (errors.length === 0) return;
94
95
  const formatted = errors.map((err) => {
95
96
  const locations = (err.nodes ?? []).map((node) => {
@@ -264,23 +265,25 @@ function resolveSelection(schema, selection, parentType, fragments, indent) {
264
265
  const typeName = selection.typeCondition.name.value;
265
266
  const conditionalType = schema.getType(typeName);
266
267
  if (!conditionalType) throw new Error(`unknown type "${typeName}" in inline fragment`);
267
- if (isCompositeType(conditionalType)) if (isInterfaceType(conditionalType)) {
268
- const inner = resolveSelectionSet(schema, selection.selectionSet, conditionalType, fragments, indent);
269
- fields.push(...inner.fields);
270
- fragmentRefs.push(...inner.fragmentRefs);
271
- } else if (isObjectType(conditionalType)) {
272
- const nested = resolveSelectionSetType(schema, selection.selectionSet, conditionalType, fragments, indent);
273
- const model = isContelloModel(schema, conditionalType.name) ? deriveModelName(conditionalType.name) : void 0;
274
- if (nested.startsWith("{")) {
275
- const discriminant = model ? `${indent} __typename: '${conditionalType.name}';\n${indent} __model: '${model}';` : `${indent} __typename: '${conditionalType.name}';`;
276
- inlineUnions.push(`{\n${discriminant}\n${nested.slice(2)}`);
268
+ if (isCompositeType(conditionalType)) {
269
+ if (isInterfaceType(conditionalType)) {
270
+ const inner = resolveSelectionSet(schema, selection.selectionSet, conditionalType, fragments, indent);
271
+ fields.push(...inner.fields);
272
+ fragmentRefs.push(...inner.fragmentRefs);
273
+ } else if (isObjectType(conditionalType)) {
274
+ const nested = resolveSelectionSetType(schema, selection.selectionSet, conditionalType, fragments, indent);
275
+ const model = isContelloModel(schema, conditionalType.name) ? deriveModelName(conditionalType.name) : void 0;
276
+ if (nested.startsWith("{")) {
277
+ const discriminant = model ? `${indent} __typename: '${conditionalType.name}';\n${indent} __model: '${model}';` : `${indent} __typename: '${conditionalType.name}';`;
278
+ inlineUnions.push(`{\n${discriminant}\n${nested.slice(2)}`);
279
+ } else {
280
+ const discriminant = model ? `{\n${indent} __typename: '${conditionalType.name}';\n${indent} __model: '${model}';\n${indent}}` : `{\n${indent} __typename: '${conditionalType.name}';\n${indent}}`;
281
+ inlineUnions.push(`${discriminant} & ${nested}`);
282
+ }
277
283
  } else {
278
- const discriminant = model ? `{\n${indent} __typename: '${conditionalType.name}';\n${indent} __model: '${model}';\n${indent}}` : `{\n${indent} __typename: '${conditionalType.name}';\n${indent}}`;
279
- inlineUnions.push(`${discriminant} & ${nested}`);
284
+ const nested = resolveSelectionSetType(schema, selection.selectionSet, conditionalType, fragments, indent);
285
+ inlineUnions.push(nested);
280
286
  }
281
- } else {
282
- const nested = resolveSelectionSetType(schema, selection.selectionSet, conditionalType, fragments, indent);
283
- inlineUnions.push(nested);
284
287
  }
285
288
  }
286
289
  break;
@@ -511,6 +514,71 @@ function extractEntityModels(schema) {
511
514
  return map;
512
515
  }
513
516
  //#endregion
517
+ //#region src/built-in-mutations.ts
518
+ /**
519
+ * Write bindings for the built-in sources. Unlike entity mutations these are not derived — their
520
+ * field and argument names are fixed parts of every Contello schema — but the generator still
521
+ * checks each one against the introspected schema before emitting it, so a server without them
522
+ * (or with a different shape) simply yields a read-only source.
523
+ *
524
+ * Routes are the odd ones: `updateContelloRoute` is keyed by the `path` inside its input rather
525
+ * than by an id, and it replaces the route rather than patching it. `deleteContelloRoute` takes a
526
+ * bare `id` and answers with a bare id string.
527
+ *
528
+ * Assets have no `create` — an asset comes into being through `client.upload()`, not a mutation.
529
+ */
530
+ const BUILT_IN_MUTATIONS = {
531
+ route: {
532
+ create: {
533
+ field: "createContelloRoute",
534
+ arguments: [{
535
+ name: "route",
536
+ type: "ContelloRouteInput!",
537
+ from: "input"
538
+ }],
539
+ result: "entity"
540
+ },
541
+ update: {
542
+ field: "updateContelloRoute",
543
+ arguments: [{
544
+ name: "route",
545
+ type: "ContelloRouteInput!",
546
+ from: "input"
547
+ }],
548
+ result: "entity"
549
+ },
550
+ delete: {
551
+ field: "deleteContelloRoute",
552
+ arguments: [{
553
+ name: "id",
554
+ type: "String",
555
+ from: "id"
556
+ }],
557
+ result: "idScalar"
558
+ }
559
+ },
560
+ asset: {
561
+ update: {
562
+ field: "updateContelloAsset",
563
+ arguments: [{
564
+ name: "request",
565
+ type: "ContelloAssetUpdateInput!",
566
+ from: "input"
567
+ }],
568
+ result: "entity"
569
+ },
570
+ delete: {
571
+ field: "deleteContelloAsset",
572
+ arguments: [{
573
+ name: "id",
574
+ type: "String!",
575
+ from: "id"
576
+ }],
577
+ result: "idObject"
578
+ }
579
+ }
580
+ };
581
+ //#endregion
514
582
  //#region src/generate/sources.ts
515
583
  /** Built-in (non-entity) types that are source-able through dedicated Subscription fields. */
516
584
  const BUILT_IN_SOURCES = [
@@ -584,6 +652,155 @@ function indexBuiltInSources(schema) {
584
652
  }
585
653
  return result;
586
654
  }
655
+ const MUTATION_KINDS = [
656
+ "create",
657
+ "update",
658
+ "delete"
659
+ ];
660
+ /**
661
+ * A create/update mutation answers with the entity itself; a delete answers with a response
662
+ * object. Both are only ever selected down to `id`, so the requirement is structural: the
663
+ * return type must be an object type carrying an `id` field, and for create/update it must be
664
+ * the entity type the source is bound to.
665
+ */
666
+ function returnsEntityId(type, entityTypeName) {
667
+ const { entityType, isList } = unwrapEntity(type);
668
+ if (!entityType || isList) return false;
669
+ if (entityTypeName !== void 0 && entityType.name !== entityTypeName) return false;
670
+ return Object.hasOwn(entityType.getFields(), "id");
671
+ }
672
+ /**
673
+ * Unwraps a one-field envelope argument (`CreateCategoryRequestInput { entity: ... }`) so the
674
+ * accessor takes the entity input directly. Only a single non-null input-object field is
675
+ * unwrapped — anything else (lists, scalars, several fields) is passed through as-is.
676
+ */
677
+ function resolveArgumentInput(type) {
678
+ const fields = Object.values(type.getFields());
679
+ const only = fields.length === 1 ? fields[0] : void 0;
680
+ if (only && isNonNullType(only.type) && isInputObjectType(only.type.ofType)) return {
681
+ envelope: only.name,
682
+ inputTypeName: only.type.ofType.name
683
+ };
684
+ return {
685
+ envelope: void 0,
686
+ inputTypeName: type.name
687
+ };
688
+ }
689
+ function indexMutationsForModel(mutationType, model, entityTypeName) {
690
+ const fields = mutationType.getFields();
691
+ const result = {};
692
+ for (const kind of MUTATION_KINDS) {
693
+ const field = fields[`${kind}${pascalCase(model)}`];
694
+ if (!field || field.args.length !== 1) continue;
695
+ if (!returnsEntityId(field.type, kind === "delete" ? void 0 : entityTypeName)) continue;
696
+ const argument = field.args[0];
697
+ const argumentNamedType = isNonNullType(argument.type) ? argument.type.ofType : argument.type;
698
+ if (!isInputObjectType(argumentNamedType)) continue;
699
+ const { envelope, inputTypeName } = resolveArgumentInput(argumentNamedType);
700
+ result[kind] = {
701
+ field: field.name,
702
+ arguments: [{
703
+ name: argument.name,
704
+ type: argument.type.toString(),
705
+ from: "input",
706
+ ...envelope !== void 0 && { envelope }
707
+ }],
708
+ result: kind === "delete" ? "idObject" : "entity",
709
+ inputType: inputTypeName
710
+ };
711
+ }
712
+ return result;
713
+ }
714
+ /**
715
+ * TS input types for the built-in write bindings. Route and asset inputs are fixed schema types;
716
+ * a delete is addressed by id alone, so its input type is spelled out rather than named.
717
+ */
718
+ const BUILT_IN_INPUT_TYPES = {
719
+ route: {
720
+ create: "ContelloRouteInput",
721
+ update: "ContelloRouteInput",
722
+ delete: "{ id: string }"
723
+ },
724
+ asset: {
725
+ update: "ContelloAssetUpdateInput",
726
+ delete: "{ id: string }"
727
+ }
728
+ };
729
+ /**
730
+ * Checks one built-in binding against the introspected schema: the field must exist, carry every
731
+ * bound argument, leave no required argument unbound, and answer with the shape the binding
732
+ * declares. A server that renamed, dropped or added to any of it yields no binding at all rather
733
+ * than a document that fails at request time.
734
+ */
735
+ function verifyBuiltInMutation(mutationType, binding, typeName) {
736
+ const field = mutationType.getFields()[binding.field];
737
+ if (!field) return;
738
+ const args = binding.arguments.map((argument) => {
739
+ const schemaArgument = field.args.find((a) => a.name === argument.name);
740
+ return schemaArgument ? {
741
+ ...argument,
742
+ type: schemaArgument.type.toString()
743
+ } : void 0;
744
+ });
745
+ if (args.includes(void 0)) return;
746
+ const bound = new Set(binding.arguments.map((argument) => argument.name));
747
+ if (field.args.some((argument) => !bound.has(argument.name) && isRequiredArgument(argument))) return;
748
+ const answersWithEntity = returnsEntityId(field.type, typeName);
749
+ if (!(binding.result === "entity" ? answersWithEntity : binding.result === "idObject" ? returnsEntityId(field.type, void 0) : isScalarResult(field.type))) return;
750
+ return {
751
+ ...binding,
752
+ arguments: args
753
+ };
754
+ }
755
+ function isScalarResult(type) {
756
+ return isScalarType(isNonNullType(type) ? type.ofType : type);
757
+ }
758
+ function verifyBuiltInMutations(mutationType, typeName, declared, inputTypes) {
759
+ const bindings = {};
760
+ for (const kind of MUTATION_KINDS) {
761
+ const binding = declared[kind];
762
+ const inputType = inputTypes[kind];
763
+ const verified = binding && inputType ? verifyBuiltInMutation(mutationType, binding, typeName) : void 0;
764
+ if (verified && inputType) bindings[kind] = {
765
+ ...verified,
766
+ inputType
767
+ };
768
+ }
769
+ return bindings;
770
+ }
771
+ /**
772
+ * Indexes the write mutations of the built-in sources the schema actually exposes, keyed by
773
+ * cardinality. Bindings are fixed (their field names are part of every Contello schema) but each
774
+ * one is verified before it is emitted.
775
+ */
776
+ function indexBuiltInMutations(schema, builtInBindings) {
777
+ const result = /* @__PURE__ */ new Map();
778
+ const mutationType = schema.getMutationType();
779
+ if (!mutationType) return result;
780
+ for (const [typeName, { cardinality }] of builtInBindings) {
781
+ const declared = BUILT_IN_MUTATIONS[cardinality];
782
+ const inputTypes = BUILT_IN_INPUT_TYPES[cardinality];
783
+ if (!declared || !inputTypes) continue;
784
+ const bindings = verifyBuiltInMutations(mutationType, typeName, declared, inputTypes);
785
+ if (Object.keys(bindings).length > 0) result.set(cardinality, bindings);
786
+ }
787
+ return result;
788
+ }
789
+ /**
790
+ * Indexes the write mutations each entity source can bind to, keyed by model reference name.
791
+ * A model with no mutations at all is left out of the map; a model missing one kind gets the
792
+ * others — singletons, for one, have no `create`.
793
+ */
794
+ function indexEntityMutations(schema, entityBindings) {
795
+ const result = /* @__PURE__ */ new Map();
796
+ const mutationType = schema.getMutationType();
797
+ if (!mutationType) return result;
798
+ for (const [entityTypeName, binding] of entityBindings) {
799
+ const bindings = indexMutationsForModel(mutationType, binding.model, entityTypeName);
800
+ if (Object.keys(bindings).length > 0) result.set(binding.model, bindings);
801
+ }
802
+ return result;
803
+ }
587
804
  function unwrapEntity(type) {
588
805
  let current = type;
589
806
  let isList = false;
@@ -615,9 +832,15 @@ function generateSourcesType(entries) {
615
832
  const sorted = organize(entries);
616
833
  if (sorted.length === 0) return "";
617
834
  const lines = ["export type Sources = {"];
618
- for (const { fragmentName, binding } of sorted) {
619
- const type = `SourceDef<'${binding.sourceKey}', '${binding.cardinality}', ${fragmentName}Fragment>`;
620
- lines.push(` ${binding.sourceKey}: ${type};`);
835
+ for (const { fragmentName, binding, mutations } of sorted) {
836
+ const writes = generateWritesType(mutations);
837
+ const args = [
838
+ `'${binding.sourceKey}'`,
839
+ `'${binding.cardinality}'`,
840
+ `${fragmentName}Fragment`
841
+ ];
842
+ if (writes) args.push(writes);
843
+ lines.push(` ${binding.sourceKey}: SourceDef<${args.join(", ")}>;`);
621
844
  }
622
845
  lines.push("};");
623
846
  return lines.join("\n");
@@ -627,10 +850,46 @@ function generateSourcesConst(entries) {
627
850
  const sorted = organize(entries);
628
851
  if (sorted.length === 0) return "";
629
852
  const lines = ["const sources: Sources = {"];
630
- for (const { fragmentName, binding, fragmentExpression } of sorted) lines.push(` ${binding.sourceKey}: {`, ` document: ${fragmentExpression},`, ` fragment: '${fragmentName}',`, ` subscription: '${binding.fieldName}',`, ` __model: '${binding.sourceKey}',`, ` __cardinality: '${binding.cardinality}',`, ` },`);
853
+ for (const { fragmentName, binding, fragmentExpression, mutations } of sorted) {
854
+ lines.push(` ${binding.sourceKey}: {`, ` document: ${fragmentExpression},`, ` fragment: '${fragmentName}',`, ` subscription: '${binding.fieldName}',`);
855
+ for (const line of generateMutationsConst(mutations)) lines.push(line);
856
+ lines.push(` __model: '${binding.sourceKey}',`, ` __cardinality: '${binding.cardinality}',`, ` },`);
857
+ }
631
858
  lines.push("};");
632
859
  return lines.join("\n");
633
860
  }
861
+ /** The phantom write shape — `{ create: CreateCategoryEntityInput; ... }`, omitted when there are no mutations. */
862
+ function generateWritesType(mutations) {
863
+ const entries = mutationEntries(mutations);
864
+ if (entries.length === 0) return;
865
+ return `{ ${entries.map(([kind, binding]) => `${kind}: ${binding.inputType}`).join("; ")} }`;
866
+ }
867
+ /** The runtime `mutations` object of a source const. */
868
+ function generateMutationsConst(mutations) {
869
+ const entries = mutationEntries(mutations);
870
+ if (entries.length === 0) return [];
871
+ const lines = [" mutations: {"];
872
+ for (const [kind, binding] of entries) {
873
+ const args = binding.arguments.map((argument) => {
874
+ const parts = [
875
+ `name: '${argument.name}'`,
876
+ `type: '${argument.type}'`,
877
+ `from: '${argument.from}'`
878
+ ];
879
+ if (argument.envelope) parts.push(`envelope: '${argument.envelope}'`);
880
+ return `{ ${parts.join(", ")} }`;
881
+ }).join(", ");
882
+ lines.push(` ${kind}: { field: '${binding.field}', arguments: [${args}], result: '${binding.result}' },`);
883
+ }
884
+ lines.push(" },");
885
+ return lines;
886
+ }
887
+ function mutationEntries(mutations) {
888
+ return MUTATION_KINDS.flatMap((kind) => {
889
+ const binding = mutations?.[kind];
890
+ return binding ? [[kind, binding]] : [];
891
+ });
892
+ }
634
893
  //#endregion
635
894
  //#region src/generate/transform-components.ts
636
895
  const FLAT_PREFIX = "_flat_";
@@ -941,7 +1200,7 @@ function collectFragmentSpreads(fragment) {
941
1200
  } });
942
1201
  return refs;
943
1202
  }
944
- function collectEntitySourceEntries(fragments, entityBindings, transformedFragments) {
1203
+ function collectEntitySourceEntries(fragments, entityBindings, transformedFragments, mutationBindings) {
945
1204
  const entries = [];
946
1205
  for (const [name, fragment] of fragments) {
947
1206
  const entityBinding = entityBindings.get(fragment.typeCondition.name.value);
@@ -955,12 +1214,13 @@ function collectEntitySourceEntries(fragments, entityBindings, transformedFragme
955
1214
  fieldName: entityBinding.fieldName,
956
1215
  sourceKey: entityBinding.model
957
1216
  },
958
- fragmentExpression: fragmentBundleExpression(transformed, transformedFragments)
1217
+ fragmentExpression: fragmentBundleExpression(transformed, transformedFragments),
1218
+ mutations: mutationBindings.get(entityBinding.model)
959
1219
  });
960
1220
  }
961
1221
  return entries;
962
1222
  }
963
- function collectBuiltInSourceEntries(fragments, builtInBindings, transformedFragments) {
1223
+ function collectBuiltInSourceEntries(fragments, builtInBindings, transformedFragments, mutationBindings) {
964
1224
  const entries = [];
965
1225
  for (const [typeName, builtInBinding] of builtInBindings) {
966
1226
  const candidates = [];
@@ -984,7 +1244,8 @@ function collectBuiltInSourceEntries(fragments, builtInBindings, transformedFrag
984
1244
  fieldName: builtInBinding.fieldName,
985
1245
  sourceKey: uncapitalize(picked.name)
986
1246
  },
987
- fragmentExpression: fragmentBundleExpression(transformed, transformedFragments)
1247
+ fragmentExpression: fragmentBundleExpression(transformed, transformedFragments),
1248
+ mutations: mutationBindings.get(builtInBinding.cardinality)
988
1249
  });
989
1250
  }
990
1251
  return entries;
@@ -1016,7 +1277,9 @@ async function main() {
1016
1277
  for (let i = 0; i < transformedOperations.length; i++) transformedOperations[i] = transformScalarOperation(schema, transformedOperations[i]);
1017
1278
  const entityBindings = indexEntitySources(schema);
1018
1279
  const builtInBindings = indexBuiltInSources(schema);
1019
- const sourceEntries = [...collectEntitySourceEntries(fragments, entityBindings, transformedFragments), ...collectBuiltInSourceEntries(fragments, builtInBindings, transformedFragments)];
1280
+ const entityMutations = indexEntityMutations(schema, entityBindings);
1281
+ const builtInMutations = indexBuiltInMutations(schema, builtInBindings);
1282
+ const sourceEntries = [...collectEntitySourceEntries(fragments, entityBindings, transformedFragments, entityMutations), ...collectBuiltInSourceEntries(fragments, builtInBindings, transformedFragments, builtInMutations)];
1020
1283
  const entityModels = extractEntityModels(schema);
1021
1284
  const parts = [
1022
1285
  "/* eslint-disable */",
@@ -1072,4 +1335,4 @@ try {
1072
1335
  //#endregion
1073
1336
  export {};
1074
1337
 
1075
- //# sourceMappingURL=generate-D_j088z7.js.map
1338
+ //# sourceMappingURL=generate-CqlYWWhF.js.map