goatly 0.1.0 → 0.1.2

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 (161) hide show
  1. package/README.md +874 -1
  2. package/bin/goatly.js +99 -0
  3. package/dist/cli/index.js +234 -0
  4. package/dist/compat/gatsby-node-entry.js +16 -0
  5. package/dist/compat/gatsby-package.json +6 -0
  6. package/dist/compat/md5-file.js +47 -0
  7. package/dist/compat-apis.json +72 -0
  8. package/dist/compat-apis.json.js +62 -0
  9. package/dist/graphql.js +3 -0
  10. package/dist/node/actions/index.js +619 -0
  11. package/dist/node/actions/job-store.js +180 -0
  12. package/dist/node/actions/jobs.js +174 -0
  13. package/dist/node/api-runner.js +258 -0
  14. package/dist/node/bootstrap.js +569 -0
  15. package/dist/node/build/assets.js +110 -0
  16. package/dist/node/build/incremental.js +208 -0
  17. package/dist/node/build/index.js +763 -0
  18. package/dist/node/build/memory-governor.js +450 -0
  19. package/dist/node/build/output-dirs.js +70 -0
  20. package/dist/node/build/page-data.js +40 -0
  21. package/dist/node/build/page-files.js +186 -0
  22. package/dist/node/build/partitioned-state.js +258 -0
  23. package/dist/node/build/query-worker.js +626 -0
  24. package/dist/node/build/query-workers.js +863 -0
  25. package/dist/node/build/render-thread.js +103 -0
  26. package/dist/node/build/render-worker.js +162 -0
  27. package/dist/node/build/state.js +24 -0
  28. package/dist/node/build/timing-breakdown.js +216 -0
  29. package/dist/node/build/work-clock.js +75 -0
  30. package/dist/node/build/worker-pool.js +242 -0
  31. package/dist/node/cache-layout.js +99 -0
  32. package/dist/node/cache.js +1430 -0
  33. package/dist/node/compat/chokidar-shim.js +148 -0
  34. package/dist/node/compat/core-utils-lmdb.js +145 -0
  35. package/dist/node/compat/create-node-id-shim.js +1 -0
  36. package/dist/node/compat/module-hooks.js +245 -0
  37. package/dist/node/compat/redux-shim.js +1 -0
  38. package/dist/node/config/index.js +162 -0
  39. package/dist/node/config/not-found-pages.js +95 -0
  40. package/dist/node/datastore/codec.js +144 -0
  41. package/dist/node/datastore/index.js +127 -0
  42. package/dist/node/datastore/logfile/cache.js +89 -0
  43. package/dist/node/datastore/logfile/index.js +1329 -0
  44. package/dist/node/datastore/logfile/record.js +71 -0
  45. package/dist/node/datastore/types.js +1 -0
  46. package/dist/node/develop/express-compat.js +207 -0
  47. package/dist/node/develop/graphiql.js +22 -0
  48. package/dist/node/develop/hydration-report.js +41 -0
  49. package/dist/node/develop/index.js +618 -0
  50. package/dist/node/develop/local-url.js +10 -0
  51. package/dist/node/develop/ssr-runner.js +66 -0
  52. package/dist/node/gql.js +5 -0
  53. package/dist/node/index.js +15 -0
  54. package/dist/node/info.js +270 -0
  55. package/dist/node/internal-plugins/data-bridge.js +196 -0
  56. package/dist/node/internal-plugins/page-creator.js +318 -0
  57. package/dist/node/loader/import-module.js +160 -0
  58. package/dist/node/node-helpers.js +66 -0
  59. package/dist/node/not-found-pages.js +220 -0
  60. package/dist/node/plugins/api-list.js +12 -0
  61. package/dist/node/plugins/load-plugins.js +427 -0
  62. package/dist/node/plugins/resolve-plugin.js +79 -0
  63. package/dist/node/plugins/static-exports.js +64 -0
  64. package/dist/node/query/compile.js +326 -0
  65. package/dist/node/query/dependencies.js +45 -0
  66. package/dist/node/query/execute.js +417 -0
  67. package/dist/node/query/extract.js +372 -0
  68. package/dist/node/query/gql-tada-introspection.js +124 -0
  69. package/dist/node/query/graphql-env.js +231 -0
  70. package/dist/node/query/graphql-runner.js +79 -0
  71. package/dist/node/redux/actions.js +1 -0
  72. package/dist/node/redux/index.js +133 -0
  73. package/dist/node/redux/node-changes.js +128 -0
  74. package/dist/node/redux/reducers.js +193 -0
  75. package/dist/node/redux/state.js +71 -0
  76. package/dist/node/renderer.js +124 -0
  77. package/dist/node/reporter-transports.js +259 -0
  78. package/dist/node/reporter.js +497 -0
  79. package/dist/node/schema/date.js +539 -0
  80. package/dist/node/schema/extensions.js +315 -0
  81. package/dist/node/schema/index.js +542 -0
  82. package/dist/node/schema/infer.js +388 -0
  83. package/dist/node/schema/inline-objects.js +128 -0
  84. package/dist/node/schema/naming.js +20 -0
  85. package/dist/node/schema/node-model.js +207 -0
  86. package/dist/node/schema/query-engine.js +1808 -0
  87. package/dist/node/schema/resolver-kinds.js +7 -0
  88. package/dist/node/schema/resolvers.js +273 -0
  89. package/dist/node/schema/type-builders.js +45 -0
  90. package/dist/node/schema/types.js +241 -0
  91. package/dist/node/serve.js +90 -0
  92. package/dist/node/site-page-nodes.js +277 -0
  93. package/dist/node/types.js +1 -0
  94. package/dist/node/utils/content-digest.js +107 -0
  95. package/dist/node/utils/cpus.js +104 -0
  96. package/dist/node/utils/create-node-id.js +51 -0
  97. package/dist/node/utils/env.js +25 -0
  98. package/dist/node/utils/fs-retry.js +74 -0
  99. package/dist/node/utils/memory-signals.js +441 -0
  100. package/dist/node/utils/memory.js +657 -0
  101. package/dist/node/utils/murmurhash.js +32 -0
  102. package/dist/node/utils/parser.js +33 -0
  103. package/dist/node/utils/partition-hash.js +19 -0
  104. package/dist/node/utils/paths.js +122 -0
  105. package/dist/node/utils/resolver.js +48 -0
  106. package/dist/node/utils/runtime.js +5 -0
  107. package/dist/node/utils/serializable.js +41 -0
  108. package/dist/node/utils/strings.js +41 -0
  109. package/dist/node/vite/config.js +289 -0
  110. package/dist/node/vite/paths.js +12 -0
  111. package/dist/node/vite/plugin-deps.js +232 -0
  112. package/dist/node/vite/plugin.js +283 -0
  113. package/dist/node/vite/react-compiler.js +362 -0
  114. package/dist/node/vite/source-files.js +83 -0
  115. package/dist/node/vite/static-image.js +136 -0
  116. package/dist/node/vite/styled-components.js +73 -0
  117. package/dist/node/vite/transforms.js +330 -0
  118. package/dist/node/wasm-data/host.js +406 -0
  119. package/dist/node/wasm-data/lower.js +406 -0
  120. package/dist/node/wasm-data/runner.js +79 -0
  121. package/dist/node/wasm-data/worker.js +95 -0
  122. package/dist/reporter.js +5 -0
  123. package/dist/runtime/api-runner.js +81 -0
  124. package/dist/runtime/app.js +256 -0
  125. package/dist/runtime/client-entry.js +4 -0
  126. package/dist/runtime/client.js +383 -0
  127. package/dist/runtime/default-html.js +31 -0
  128. package/dist/runtime/head-markup.js +100 -0
  129. package/dist/runtime/head-sync.js +101 -0
  130. package/dist/runtime/head-tags.js +45 -0
  131. package/dist/runtime/hydration-report.js +111 -0
  132. package/dist/runtime/index.js +12 -0
  133. package/dist/runtime/link.js +293 -0
  134. package/dist/runtime/loader.js +449 -0
  135. package/dist/runtime/not-found.js +61 -0
  136. package/dist/runtime/page-renderer.js +35 -0
  137. package/dist/runtime/preamble.js +47 -0
  138. package/dist/runtime/react-compat.js +14 -0
  139. package/dist/runtime/renderer-shared.js +10 -0
  140. package/dist/runtime/renderers/react-client.js +14 -0
  141. package/dist/runtime/renderers/react-server.js +99 -0
  142. package/dist/runtime/renderers/react.js +17 -0
  143. package/dist/runtime/renderers/types.js +1 -0
  144. package/dist/runtime/root-error-handlers.js +29 -0
  145. package/dist/runtime/router/history.js +132 -0
  146. package/dist/runtime/router/index.js +240 -0
  147. package/dist/runtime/router/utils.js +118 -0
  148. package/dist/runtime/script.js +110 -0
  149. package/dist/runtime/scroll.js +40 -0
  150. package/dist/runtime/slice.js +11 -0
  151. package/dist/runtime/ssr.js +240 -0
  152. package/dist/runtime/static-query.js +47 -0
  153. package/dist/utils.js +4 -0
  154. package/package.json +105 -3
  155. package/types/graphql-tada.d.ts +223 -0
  156. package/types/graphql.d.ts +2 -0
  157. package/types/index.d.ts +2287 -0
  158. package/types/node.d.ts +389 -0
  159. package/types/reporter.d.ts +187 -0
  160. package/types/router.d.ts +102 -0
  161. package/types/vendor/gql-tada.d.ts +2529 -0
@@ -0,0 +1,542 @@
1
+ import { GraphQLInterfaceType, GraphQLObjectType, GraphQLScalarType, isIntrospectionType, isNamedType, isSpecifiedScalarType, parse } from "../gql.js";
2
+ import { apiRunnerNode } from "../api-runner.js";
3
+ import { getDataStore, getNodesByType } from "../datastore/index.js";
4
+ import { clearChangedNodeTypes, getChangedNodeTypes, getStoreEpoch } from "../redux/node-changes.js";
5
+ import { store } from "../redux/index.js";
6
+ import reporter from "../reporter.js";
7
+ import { GraphQLDate } from "./date.js";
8
+ import { builtInFieldExtensions, defaultFieldResolver, processFieldExtensions, registerFieldExtensionDirectives } from "./extensions.js";
9
+ import { collectParentTypes, collectTypeMetadata, countTypeMetadata, inferTypeFields, resetInferenceMemo } from "./infer.js";
10
+ import { isRootFree, rootFree, sharedArgs, updateInlineRootsNeeded } from "./inline-objects.js";
11
+ import { fieldNames } from "./naming.js";
12
+ import { LocalNodeModel } from "./node-model.js";
13
+ import { createChildField, createChildrenField, findManyPaginatedResolver, findOneResolver } from "./resolvers.js";
14
+ import { isGatsbyType } from "./type-builders.js";
15
+ import { getConnection, getFilterInput, getSortInput, removeEmptyInputs } from "./types.js";
16
+ import { EnumTypeComposer, GraphQLJSON, InputTypeComposer, InterfaceTypeComposer, ObjectTypeComposer, ScalarTypeComposer, SchemaComposer, UnionTypeComposer } from "graphql-compose";
17
+ import path from "node:path";
18
+ import fs from "node:fs";
19
+ // src/node/schema/index.ts
20
+ let currentSchema = null;
21
+ let currentComposer = null;
22
+ /**
23
+ * The resolver context (createResolverContext) the current schema was built with: queries keep it
24
+ * while createSchemaCustomization runs again (develop's /__refresh clears the customization first)
25
+ */
26
+ let currentContext = null;
27
+ function getSchema() {
28
+ if (!currentSchema) throw new Error("The GraphQL schema has not been built yet");
29
+ return currentSchema;
30
+ }
31
+ function getSchemaComposer() {
32
+ return currentComposer;
33
+ }
34
+ /**
35
+ * Gatsby 5's built-in scalar for gatsby-plugin-image data. Plugins (gatsby-plugin-image,
36
+ * gatsby-transformer-sharp, Contentful, …) declare `gatsbyImageData: GatsbyImageData!` when gatsby
37
+ * has the `graphql-typegen` feature (and JSON! otherwise): it is a JSON value under another name.
38
+ */
39
+ const GraphQLGatsbyImageData = new GraphQLScalarType({
40
+ name: "GatsbyImageData",
41
+ serialize: GraphQLJSON.serialize,
42
+ parseValue: GraphQLJSON.parseValue,
43
+ parseLiteral: GraphQLJSON.parseLiteral
44
+ });
45
+ function addBuiltInTypes(sc) {
46
+ sc.add(GraphQLDate);
47
+ sc.add(GraphQLJSON);
48
+ sc.add(GraphQLGatsbyImageData);
49
+ sc.createObjectTC({
50
+ name: "Internal",
51
+ fields: {
52
+ content: "String",
53
+ contentDigest: "String!",
54
+ description: "String",
55
+ fieldOwners: {
56
+ type: "[String]",
57
+ resolve: rootFree((s) => s.fieldOwners ? Object.keys(s.fieldOwners) : null)
58
+ },
59
+ ignoreType: "Boolean",
60
+ mediaType: "String",
61
+ owner: "String!",
62
+ type: "String!",
63
+ contentFilePath: "String"
64
+ }
65
+ });
66
+ sc.set("Internal", sc.getOTC("Internal"));
67
+ const nodeInterface = sc.createInterfaceTC({
68
+ name: "Node",
69
+ description: "Node Interface",
70
+ fields: {
71
+ id: "ID!",
72
+ parent: {
73
+ type: "Node",
74
+ resolve: parentResolver
75
+ },
76
+ children: {
77
+ type: "[Node!]!",
78
+ resolve: childrenResolver
79
+ },
80
+ internal: "Internal!"
81
+ }
82
+ });
83
+ nodeInterface.setResolveType(nodeTypeOfValue);
84
+ sc.set("Node", nodeInterface);
85
+ }
86
+ /** a resolver that never looks up root nodes nor changes its arguments */
87
+ function rootFreeShared(resolve) {
88
+ return sharedArgs(rootFree(resolve));
89
+ }
90
+ /** the default resolveType of abstract types: the node's type */
91
+ const nodeTypeOfValue = rootFree((value) => value?.internal?.type);
92
+ const parentResolver = rootFreeShared(function parentResolver(source, _args, context) {
93
+ return source.parent ? context.nodeModel.getNodeById({ id: source.parent }) : null;
94
+ });
95
+ const childrenResolver = rootFreeShared(function childrenResolver(source, _args, context) {
96
+ return context.nodeModel.getNodesByIds({ ids: source.children ?? [] });
97
+ });
98
+ function applyTypeDirectives(tc) {
99
+ if (!(tc instanceof ObjectTypeComposer) && !(tc instanceof InterfaceTypeComposer)) return;
100
+ for (const d of tc.getDirectives()) if (d.name === "dontInfer") tc.setExtension("infer", false);
101
+ else if (d.name === "infer") tc.setExtension("infer", true);
102
+ else if (d.name === "mimeTypes") tc.setExtension("mimeTypes", d.args ?? {});
103
+ else if (d.name === "childOf") tc.setExtension("childOf", d.args ?? {});
104
+ else if (d.name === "nodeInterface") tc.setExtension("nodeInterface", true);
105
+ tc.setDirectives(tc.getDirectives().filter((d) => ![
106
+ "dontInfer",
107
+ "infer",
108
+ "mimeTypes",
109
+ "childOf",
110
+ "nodeInterface"
111
+ ].includes(d.name)));
112
+ }
113
+ /**
114
+ * Removes a type composer from the schema composer's storage. graphql-compose registers every
115
+ * composer it creates (`typeMapper.makeSchemaDef`, `createTemp(…, sc)`) under its GraphQL type
116
+ * and itself; a definition that was merged into an existing type (or ignored) must not stay
117
+ * there: buildSchema adds stored implementations of interfaces, so it would end up in the schema
118
+ * as a second type of the same name ("Schema must contain uniquely named types").
119
+ */
120
+ function forgetTypeComposer(sc, tc) {
121
+ const keys = [];
122
+ sc.forEach((value, key) => {
123
+ if (value === tc) keys.push(key);
124
+ });
125
+ for (const key of keys) sc.delete(key);
126
+ }
127
+ /** The type composer registered under `name`, looked up before a new definition is created. */
128
+ function definedType(sc, name) {
129
+ return typeof name === "string" && sc.has(name) ? sc.get(name) : void 0;
130
+ }
131
+ /**
132
+ * Adds a type definition, or merges it into `existing` – the type of that name defined before.
133
+ * (`existing` must be looked up before `incoming` is created: graphql-compose's SDL conversion
134
+ * registers the new composer under the name, replacing the earlier definition.)
135
+ */
136
+ function mergeInto(sc, incoming, pluginName, existing) {
137
+ const name = incoming.getTypeName();
138
+ applyTypeDirectives(incoming);
139
+ if (!existing || existing === incoming) {
140
+ if (pluginName) incoming.setExtension("plugin", pluginName);
141
+ sc.add(incoming);
142
+ sc.set(name, incoming);
143
+ return;
144
+ }
145
+ sc.set(name, existing);
146
+ try {
147
+ mergeIntoExisting(sc, existing, incoming, pluginName);
148
+ } finally {
149
+ forgetTypeComposer(sc, sc.get(name) === incoming ? existing : incoming);
150
+ }
151
+ }
152
+ function mergeIntoExisting(sc, existing, incoming, pluginName) {
153
+ const name = incoming.getTypeName();
154
+ const owner = existing.getExtension?.("plugin");
155
+ if (!(!pluginName || pluginName === "default-site-plugin" || !owner || owner === pluginName || existing.getExtension?.("createdFrom") === "inference")) reporter.warn(`Plugin \`${pluginName}\` has customized the GraphQL type \`${name}\`, which has already been defined by the plugin \`${owner}\`. This could potentially cause conflicts.`);
156
+ if ((existing instanceof ObjectTypeComposer || existing instanceof InterfaceTypeComposer) && (incoming instanceof ObjectTypeComposer || incoming instanceof InterfaceTypeComposer)) {
157
+ for (const fieldName of incoming.getFieldNames()) {
158
+ const config = incoming.getField(fieldName);
159
+ if (existing.hasField(fieldName)) existing.extendField(fieldName, config);
160
+ else existing.setField(fieldName, config);
161
+ }
162
+ if (incoming instanceof ObjectTypeComposer && existing instanceof ObjectTypeComposer) existing.addInterfaces(incoming.getInterfaces().map((i) => i.getTypeName()));
163
+ for (const [k, v] of Object.entries(incoming.getExtensions())) existing.setExtension(k, v);
164
+ if (incoming.getDescription()) existing.setDescription(incoming.getDescription());
165
+ } else if (existing instanceof UnionTypeComposer && incoming instanceof UnionTypeComposer) existing.addTypes(incoming.getTypeNames());
166
+ else if (existing instanceof EnumTypeComposer && incoming instanceof EnumTypeComposer) existing.addFields(incoming.getFields());
167
+ else if (existing instanceof InputTypeComposer && incoming instanceof InputTypeComposer) existing.addFields(incoming.getFields());
168
+ else sc.set(name, incoming);
169
+ }
170
+ function addUserTypes(sc) {
171
+ const { types } = store.getState().schemaCustomization;
172
+ for (const { typeOrTypeDef, plugin } of types) {
173
+ const pluginName = plugin?.name;
174
+ const add = (def) => {
175
+ try {
176
+ if (typeof def === "string") {
177
+ const doc = parse(def);
178
+ for (const node of doc.definitions) {
179
+ if (node.kind.endsWith("Extension")) {
180
+ const tc = sc.typeMapper.makeSchemaDef(node);
181
+ if (tc) applyTypeDirectives(tc);
182
+ continue;
183
+ }
184
+ const existing = definedType(sc, node.name?.value);
185
+ const tc = sc.typeMapper.makeSchemaDef(node);
186
+ if (tc) mergeInto(sc, tc, pluginName, existing);
187
+ }
188
+ } else if (isGatsbyType(def)) {
189
+ let tc;
190
+ const config = { ...def.config };
191
+ const existing = definedType(sc, config.name);
192
+ switch (def.kind) {
193
+ case "OBJECT":
194
+ tc = ObjectTypeComposer.createTemp(config, sc);
195
+ break;
196
+ case "INTERFACE":
197
+ tc = InterfaceTypeComposer.createTemp(config, sc);
198
+ break;
199
+ case "UNION":
200
+ tc = UnionTypeComposer.createTemp(config, sc);
201
+ break;
202
+ case "INPUT_OBJECT":
203
+ tc = InputTypeComposer.createTemp(config, sc);
204
+ break;
205
+ case "ENUM":
206
+ tc = EnumTypeComposer.createTemp(config, sc);
207
+ break;
208
+ case "SCALAR": tc = ScalarTypeComposer.createTemp(config, sc);
209
+ }
210
+ if (tc) mergeInto(sc, tc, pluginName, existing);
211
+ } else if (def && isNamedType(def)) {
212
+ const existing = definedType(sc, def.name);
213
+ mergeInto(sc, sc.createTempTC(def), pluginName, existing);
214
+ } else if (Array.isArray(def)) def.forEach(add);
215
+ } catch (e) {
216
+ reporter.panicOnBuild({
217
+ id: "85901",
218
+ context: { sourceMessage: `Error in createTypes${pluginName ? ` (plugin "${pluginName}")` : ""}: ${e.message}` },
219
+ error: e
220
+ });
221
+ }
222
+ };
223
+ add(typeOrTypeDef);
224
+ }
225
+ }
226
+ function isNodeType(tc) {
227
+ return tc instanceof ObjectTypeComposer && tc.hasInterface("Node");
228
+ }
229
+ function isNodeInterface(tc) {
230
+ if (!(tc instanceof InterfaceTypeComposer) || tc.getTypeName() === "Node") return false;
231
+ return !!tc.getExtension("nodeInterface") || tc.hasInterface?.("Node");
232
+ }
233
+ function addNodeInterfaceFields(tc) {
234
+ tc.addInterfaces(["Node"]);
235
+ tc.setField("id", { type: "ID!" });
236
+ tc.setField("parent", {
237
+ type: "Node",
238
+ resolve: parentResolver
239
+ });
240
+ tc.setField("children", {
241
+ type: "[Node!]!",
242
+ resolve: childrenResolver
243
+ });
244
+ tc.setField("internal", { type: "Internal!" });
245
+ }
246
+ function addThirdPartySchemas(sc) {
247
+ for (const schema of store.getState().schemaCustomization.thirdPartySchemas) {
248
+ const queryType = schema.getQueryType();
249
+ if (!queryType) continue;
250
+ const queryTC = sc.createTempTC(queryType);
251
+ for (const fieldName of queryTC.getFieldNames()) if (queryTC.getFieldTC(fieldName).getTypeName() === queryType.name) queryTC.extendField(fieldName, {
252
+ type: "Query",
253
+ resolve: () => ({})
254
+ });
255
+ sc.Query.addFields(queryTC.getFields());
256
+ for (const [name, type] of Object.entries(schema.getTypeMap())) {
257
+ if (type === queryType || isSpecifiedScalarType(type) || isIntrospectionType(type) || name === "Date" || name === "JSON") continue;
258
+ const tc = sc.createTC(type);
259
+ if (tc instanceof ObjectTypeComposer || tc instanceof InterfaceTypeComposer) {
260
+ for (const fieldName of tc.getFieldNames()) if (tc.getFieldTC(fieldName).getTypeName() === queryType.name) tc.extendField(fieldName, {
261
+ type: "Query",
262
+ resolve: () => ({})
263
+ });
264
+ }
265
+ tc.setExtension("createdFrom", "thirdPartySchema");
266
+ sc.addSchemaMustHaveType(tc);
267
+ }
268
+ }
269
+ }
270
+ function addChildrenFields(sc, metadata) {
271
+ const parentToChildren = /* @__PURE__ */ new Map();
272
+ const add = (parent, child) => {
273
+ let set = parentToChildren.get(parent);
274
+ if (!set) parentToChildren.set(parent, set = /* @__PURE__ */ new Set());
275
+ set.add(child);
276
+ };
277
+ for (const meta of metadata.values()) for (const p of meta.parentTypes) add(p, meta.typeName);
278
+ const mimeTypeChildren = /* @__PURE__ */ new Map();
279
+ sc.forEach((tc) => {
280
+ if (!(tc instanceof ObjectTypeComposer)) return;
281
+ const childOf = tc.getExtension("childOf");
282
+ if (!childOf) return;
283
+ for (const parent of childOf.types ?? []) add(parent, tc.getTypeName());
284
+ for (const mime of childOf.mimeTypes ?? []) {
285
+ let set = mimeTypeChildren.get(mime);
286
+ if (!set) mimeTypeChildren.set(mime, set = /* @__PURE__ */ new Set());
287
+ set.add(tc.getTypeName());
288
+ }
289
+ });
290
+ if (mimeTypeChildren.size) sc.forEach((tc) => {
291
+ if (!(tc instanceof ObjectTypeComposer)) return;
292
+ const declared = tc.getExtension("mimeTypes")?.types ?? [];
293
+ const observed = metadata.get(tc.getTypeName())?.mediaTypes ?? /* @__PURE__ */ new Set();
294
+ for (const mime of [...declared, ...observed]) for (const child of mimeTypeChildren.get(mime) ?? []) add(tc.getTypeName(), child);
295
+ });
296
+ for (const [parent, children] of parentToChildren) {
297
+ if (!sc.has(parent)) continue;
298
+ const tc = sc.getAnyTC(parent);
299
+ if (!(tc instanceof ObjectTypeComposer || tc instanceof InterfaceTypeComposer)) continue;
300
+ for (const child of children) {
301
+ if (!sc.has(child)) continue;
302
+ const childField = fieldNames.convenienceChild(child);
303
+ const childrenField = fieldNames.convenienceChildren(child);
304
+ if (!tc.hasField(childField)) tc.addFields({ [childField]: createChildField(child) });
305
+ if (!tc.hasField(childrenField)) tc.addFields({ [childrenField]: createChildrenField(child) });
306
+ }
307
+ }
308
+ }
309
+ function addTypeToRootQuery(sc, tc) {
310
+ const typeName = tc.getTypeName();
311
+ const filterInput = getFilterInput(sc, tc);
312
+ const sortInput = getSortInput(sc, tc);
313
+ const connection = getConnection(sc, tc);
314
+ const args = {};
315
+ for (const name of filterInput.getFieldNames()) args[name] = filterInput.getField(name);
316
+ sc.Query.addFields({
317
+ [fieldNames.query(typeName)]: {
318
+ type: tc,
319
+ args,
320
+ resolve: rootFree(findOneResolver(typeName))
321
+ },
322
+ [fieldNames.queryAll(typeName)]: {
323
+ type: connection.getTypeNonNull(),
324
+ args: {
325
+ filter: filterInput,
326
+ sort: sortInput.getTypePlural(),
327
+ skip: "Int",
328
+ limit: "Int"
329
+ },
330
+ resolve: rootFree(findManyPaginatedResolver(typeName))
331
+ }
332
+ });
333
+ }
334
+ async function addCustomResolveFunctions(sc) {
335
+ const intermediateSchema = sc.buildSchema();
336
+ const createResolvers = (resolvers, { ignoreNonexistentTypes = false } = {}) => {
337
+ for (const [typeName, fields] of Object.entries(resolvers ?? {})) {
338
+ if (!sc.has(typeName)) {
339
+ if (!ignoreNonexistentTypes) reporter.warn(`\`createResolvers\` passed resolvers for type \`${typeName}\` that doesn't exist in the schema. Use \`createTypes\` to add the type before adding resolvers.`);
340
+ continue;
341
+ }
342
+ const tc = sc.getAnyTC(typeName);
343
+ if (!(tc instanceof ObjectTypeComposer || tc instanceof InterfaceTypeComposer)) continue;
344
+ for (const [fieldName, fieldConfig] of Object.entries(fields)) if (tc.hasField(fieldName)) {
345
+ const original = tc.getFieldConfig(fieldName);
346
+ const originalTypeName = String(original.type);
347
+ const newTypeName = fieldConfig.type ? Array.isArray(fieldConfig.type) ? `[${fieldConfig.type[0]}]` : String(fieldConfig.type) : void 0;
348
+ if (!newTypeName || newTypeName.replace(/!/g, "") === originalTypeName.replace(/!/g, "") || tc.getExtension("createdFrom") === "thirdPartySchema") {
349
+ const newConfig = {};
350
+ if (fieldConfig.type) newConfig.type = fieldConfig.type;
351
+ if (fieldConfig.args) newConfig.args = fieldConfig.args;
352
+ if (fieldConfig.resolve) {
353
+ const originalResolver = original.resolve ?? defaultFieldResolver;
354
+ const resolve = (source, args, context, info) => fieldConfig.resolve(source, args, context, {
355
+ ...info,
356
+ originalResolver
357
+ });
358
+ newConfig.resolve = isRootFree(fieldConfig.resolve) && isRootFree(original.resolve) ? rootFree(resolve) : resolve;
359
+ }
360
+ tc.extendField(fieldName, newConfig);
361
+ } else reporter.warn(`\`createResolvers\` passed resolvers for field \`${typeName}.${fieldName}\` with type \`${newTypeName}\`. Such a field with type \`${originalTypeName}\` already exists on the type. Use \`createTypes\` to override type fields.`);
362
+ } else tc.addFields({ [fieldName]: fieldConfig });
363
+ }
364
+ };
365
+ await apiRunnerNode("createResolvers", {
366
+ intermediateSchema,
367
+ createResolvers,
368
+ traceId: "initial-createResolvers"
369
+ });
370
+ }
371
+ function printTypeDefinitions(sc, directory) {
372
+ const config = store.getState().schemaCustomization.printConfig;
373
+ if (!config) return;
374
+ const target = path.resolve(directory, config.path ?? "schema.gql");
375
+ if (fs.existsSync(target)) {
376
+ reporter.warn(`Printing type definitions aborted. The file "${config.path}" already exists.`);
377
+ return;
378
+ }
379
+ const include = config.include?.types;
380
+ const exclude = config.exclude?.types ?? [];
381
+ const sdl = [];
382
+ sc.forEach((tc) => {
383
+ if (!(tc instanceof ObjectTypeComposer) || tc.getTypeName() === "Query") return;
384
+ const name = tc.getTypeName();
385
+ if (include && !include.includes(name)) return;
386
+ if (exclude.includes(name)) return;
387
+ if (!tc.hasInterface("Node")) return;
388
+ sdl.push(tc.toSDL({ omitDescriptions: true }).replace(/^type (\w+) implements Node/, "type $1 implements Node @dontInfer"));
389
+ });
390
+ fs.writeFileSync(target, `${[...new Set(sdl)].join("\n\n")}\n`);
391
+ reporter.info(`Printed type definitions to ${config.path}`);
392
+ }
393
+ /**
394
+ * Builds the Gatsby compatible GraphQL schema from createTypes definitions,
395
+ * inferred node data, plugin field extensions and resolvers.
396
+ */
397
+ let inferenceSnapshot;
398
+ let lastInferenceMetadata;
399
+ /** inference results of the last schema build (main thread → query workers) */
400
+ function getInferenceMetadata() {
401
+ return lastInferenceMetadata;
402
+ }
403
+ /** use inference results of another thread instead of scanning the nodes (same nodes!) */
404
+ function setInferenceSnapshot(snapshot) {
405
+ inferenceSnapshot = snapshot;
406
+ }
407
+ /**
408
+ * Inference results to start from: types without node changes since (see
409
+ * `getChangedNodeTypes`) are not scanned again. Set after each schema build, and at start-up from
410
+ * the previous build's results when its nodes were restored.
411
+ */
412
+ let inferenceBaseline;
413
+ function setInferenceBaseline(metadata) {
414
+ inferenceBaseline = metadata ? {
415
+ ds: getDataStore(),
416
+ epoch: getStoreEpoch(),
417
+ metadata
418
+ } : void 0;
419
+ }
420
+ async function buildSchema() {
421
+ resetInferenceMemo();
422
+ updateInlineRootsNeeded(void 0);
423
+ const state = store.getState();
424
+ const context = state.schemaCustomization.context;
425
+ const sc = new SchemaComposer();
426
+ addBuiltInTypes(sc);
427
+ const extensions = {
428
+ ...builtInFieldExtensions,
429
+ ...state.schemaCustomization.fieldExtensions
430
+ };
431
+ registerFieldExtensionDirectives(sc, extensions);
432
+ addUserTypes(sc);
433
+ const ds = getDataStore();
434
+ const metadata = /* @__PURE__ */ new Map();
435
+ const typeNames = new Set(ds.getTypes());
436
+ const baseline = inferenceBaseline?.ds === ds && inferenceBaseline.epoch === getStoreEpoch() ? inferenceBaseline.metadata : void 0;
437
+ const changed = getChangedNodeTypes();
438
+ const reusable = (typeName) => {
439
+ if (!baseline || changed.has(typeName)) return void 0;
440
+ const meta = baseline.get(typeName);
441
+ if (!meta || meta.countOnly || meta.nodeCount !== ds.countNodes(typeName)) return void 0;
442
+ return {
443
+ ...meta,
444
+ parentTypes: collectParentTypes(typeName)
445
+ };
446
+ };
447
+ sc.forEach((tc) => {
448
+ if (isNodeType(tc)) typeNames.add(tc.getTypeName());
449
+ });
450
+ for (const typeName of typeNames) {
451
+ const tc = sc.getOrCreateOTC(typeName);
452
+ if (!tc.hasInterface("Node")) tc.addInterfaces(["Node"]);
453
+ const infer = tc.getExtension("infer") !== false;
454
+ const snapshot = inferenceSnapshot?.get(typeName);
455
+ const meta = !infer ? countTypeMetadata(typeName) : (snapshot && !snapshot.countOnly ? snapshot : void 0) ?? reusable(typeName) ?? collectTypeMetadata(typeName);
456
+ metadata.set(typeName, meta);
457
+ if (infer && meta.nodeCount > 0) inferTypeFields(sc, tc, meta, state.config.mapping ?? {});
458
+ addNodeInterfaceFields(tc);
459
+ }
460
+ lastInferenceMetadata = metadata;
461
+ inferenceBaseline = {
462
+ ds,
463
+ epoch: getStoreEpoch(),
464
+ metadata
465
+ };
466
+ clearChangedNodeTypes();
467
+ addThirdPartySchemas(sc);
468
+ for (const typeName of typeNames) {
469
+ const tc = sc.getOTC(typeName);
470
+ const results = await apiRunnerNode("setFieldsOnGraphQLNodeType", {
471
+ type: {
472
+ name: typeName,
473
+ get nodes() {
474
+ return getNodesByType(typeName);
475
+ }
476
+ },
477
+ traceId: "initial-setFieldsOnGraphQLNodeType"
478
+ });
479
+ for (const fields of results) if (fields && typeof fields === "object") tc.addNestedFields(fields);
480
+ }
481
+ addChildrenFields(sc, metadata);
482
+ const all = [];
483
+ sc.forEach((tc) => {
484
+ if (!all.includes(tc)) all.push(tc);
485
+ });
486
+ for (const tc of all) {
487
+ if (isNodeInterface(tc)) {
488
+ if (!tc.hasInterface("Node")) tc.addInterfaces(["Node"]);
489
+ for (const [name, type] of [
490
+ ["id", "ID!"],
491
+ ["parent", "Node"],
492
+ ["children", "[Node!]!"],
493
+ ["internal", "Internal!"]
494
+ ]) if (!tc.hasField(name)) tc.setField(name, { type });
495
+ }
496
+ if (tc instanceof ObjectTypeComposer || tc instanceof InterfaceTypeComposer) {
497
+ if (tc.getTypeName() === "Query") continue;
498
+ processFieldExtensions(tc, extensions);
499
+ }
500
+ if ((tc instanceof InterfaceTypeComposer || tc instanceof UnionTypeComposer) && !tc.getResolveType()) tc.setResolveType(nodeTypeOfValue);
501
+ }
502
+ for (const tc of all) if (isNodeType(tc)) addTypeToRootQuery(sc, tc);
503
+ else if (isNodeInterface(tc)) addTypeToRootQuery(sc, tc);
504
+ removeEmptyInputs(sc);
505
+ await addCustomResolveFunctions(sc);
506
+ printTypeDefinitions(sc, state.program.directory);
507
+ for (const tc of all) {
508
+ if ((tc instanceof ObjectTypeComposer || tc instanceof InterfaceTypeComposer) && tc.getFieldNames().length === 0) continue;
509
+ if (tc instanceof ObjectTypeComposer && tc.getTypeName() !== "Query" && tc.hasInterface("Node")) sc.addSchemaMustHaveType(tc);
510
+ }
511
+ const schema = sc.buildSchema();
512
+ updateInlineRootsNeeded(schema);
513
+ currentSchema = schema;
514
+ currentComposer = sc;
515
+ currentContext = context;
516
+ store.dispatch({
517
+ type: "SET_SCHEMA",
518
+ payload: schema
519
+ });
520
+ store.dispatch({
521
+ type: "SET_SCHEMA_COMPOSER",
522
+ payload: sc
523
+ });
524
+ return schema;
525
+ }
526
+ /** Creates the GraphQL context passed to resolvers. */
527
+ function createGraphQLContext(path, dependencies) {
528
+ const customContext = currentContext ?? store.getState().schemaCustomization.context;
529
+ const nodeModel = new LocalNodeModel({
530
+ schema: getSchema,
531
+ customContext
532
+ }).withContext({
533
+ path,
534
+ dependencies
535
+ });
536
+ return {
537
+ ...customContext,
538
+ nodeModel,
539
+ path
540
+ };
541
+ }
542
+ export { GraphQLInterfaceType, GraphQLObjectType, buildSchema, createGraphQLContext, getInferenceMetadata, getSchema, getSchemaComposer, setInferenceBaseline, setInferenceSnapshot };