goatly 0.0.0-stage → 0.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.
Files changed (159) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +854 -2
  3. package/bin/goatly.js +91 -0
  4. package/dist/cli/index.js +234 -0
  5. package/dist/compat/gatsby-node-entry.js +16 -0
  6. package/dist/compat/gatsby-package.json +6 -0
  7. package/dist/compat/md5-file.js +47 -0
  8. package/dist/compat-apis.json +72 -0
  9. package/dist/compat-apis.json.js +62 -0
  10. package/dist/graphql.js +3 -0
  11. package/dist/node/actions/index.js +619 -0
  12. package/dist/node/actions/job-store.js +180 -0
  13. package/dist/node/actions/jobs.js +174 -0
  14. package/dist/node/api-runner.js +258 -0
  15. package/dist/node/bootstrap.js +539 -0
  16. package/dist/node/build/assets.js +110 -0
  17. package/dist/node/build/incremental.js +208 -0
  18. package/dist/node/build/index.js +752 -0
  19. package/dist/node/build/memory-governor.js +448 -0
  20. package/dist/node/build/output-dirs.js +70 -0
  21. package/dist/node/build/page-data.js +40 -0
  22. package/dist/node/build/page-files.js +54 -0
  23. package/dist/node/build/partitioned-state.js +258 -0
  24. package/dist/node/build/query-worker.js +536 -0
  25. package/dist/node/build/query-workers.js +832 -0
  26. package/dist/node/build/render-worker.js +131 -0
  27. package/dist/node/build/state.js +24 -0
  28. package/dist/node/build/timing-breakdown.js +155 -0
  29. package/dist/node/build/worker-pool.js +236 -0
  30. package/dist/node/cache-layout.js +99 -0
  31. package/dist/node/cache.js +1430 -0
  32. package/dist/node/compat/chokidar-shim.js +148 -0
  33. package/dist/node/compat/core-utils-lmdb.js +145 -0
  34. package/dist/node/compat/create-node-id-shim.js +1 -0
  35. package/dist/node/compat/module-hooks.js +245 -0
  36. package/dist/node/compat/redux-shim.js +1 -0
  37. package/dist/node/config/index.js +162 -0
  38. package/dist/node/config/not-found-pages.js +95 -0
  39. package/dist/node/datastore/codec.js +144 -0
  40. package/dist/node/datastore/index.js +127 -0
  41. package/dist/node/datastore/logfile/cache.js +89 -0
  42. package/dist/node/datastore/logfile/index.js +1329 -0
  43. package/dist/node/datastore/logfile/record.js +71 -0
  44. package/dist/node/datastore/types.js +1 -0
  45. package/dist/node/develop/express-compat.js +207 -0
  46. package/dist/node/develop/graphiql.js +22 -0
  47. package/dist/node/develop/hydration-report.js +41 -0
  48. package/dist/node/develop/index.js +618 -0
  49. package/dist/node/develop/local-url.js +10 -0
  50. package/dist/node/develop/ssr-runner.js +66 -0
  51. package/dist/node/gql.js +5 -0
  52. package/dist/node/index.js +15 -0
  53. package/dist/node/info.js +270 -0
  54. package/dist/node/internal-plugins/data-bridge.js +196 -0
  55. package/dist/node/internal-plugins/page-creator.js +318 -0
  56. package/dist/node/loader/import-module.js +160 -0
  57. package/dist/node/node-helpers.js +66 -0
  58. package/dist/node/not-found-pages.js +220 -0
  59. package/dist/node/plugins/api-list.js +12 -0
  60. package/dist/node/plugins/load-plugins.js +427 -0
  61. package/dist/node/plugins/resolve-plugin.js +79 -0
  62. package/dist/node/plugins/static-exports.js +64 -0
  63. package/dist/node/query/compile.js +326 -0
  64. package/dist/node/query/dependencies.js +45 -0
  65. package/dist/node/query/execute.js +417 -0
  66. package/dist/node/query/extract.js +372 -0
  67. package/dist/node/query/gql-tada-introspection.js +124 -0
  68. package/dist/node/query/graphql-env.js +231 -0
  69. package/dist/node/query/graphql-runner.js +79 -0
  70. package/dist/node/redux/actions.js +1 -0
  71. package/dist/node/redux/index.js +133 -0
  72. package/dist/node/redux/node-changes.js +128 -0
  73. package/dist/node/redux/reducers.js +193 -0
  74. package/dist/node/redux/state.js +71 -0
  75. package/dist/node/renderer.js +124 -0
  76. package/dist/node/reporter-transports.js +259 -0
  77. package/dist/node/reporter.js +497 -0
  78. package/dist/node/schema/date.js +539 -0
  79. package/dist/node/schema/extensions.js +315 -0
  80. package/dist/node/schema/index.js +542 -0
  81. package/dist/node/schema/infer.js +388 -0
  82. package/dist/node/schema/inline-objects.js +128 -0
  83. package/dist/node/schema/naming.js +20 -0
  84. package/dist/node/schema/node-model.js +207 -0
  85. package/dist/node/schema/query-engine.js +1808 -0
  86. package/dist/node/schema/resolver-kinds.js +7 -0
  87. package/dist/node/schema/resolvers.js +273 -0
  88. package/dist/node/schema/type-builders.js +45 -0
  89. package/dist/node/schema/types.js +241 -0
  90. package/dist/node/serve.js +90 -0
  91. package/dist/node/site-page-nodes.js +277 -0
  92. package/dist/node/types.js +1 -0
  93. package/dist/node/utils/content-digest.js +107 -0
  94. package/dist/node/utils/create-node-id.js +51 -0
  95. package/dist/node/utils/env.js +24 -0
  96. package/dist/node/utils/fs-retry.js +74 -0
  97. package/dist/node/utils/memory-signals.js +410 -0
  98. package/dist/node/utils/memory.js +400 -0
  99. package/dist/node/utils/murmurhash.js +32 -0
  100. package/dist/node/utils/parser.js +33 -0
  101. package/dist/node/utils/partition-hash.js +19 -0
  102. package/dist/node/utils/paths.js +122 -0
  103. package/dist/node/utils/resolver.js +48 -0
  104. package/dist/node/utils/runtime.js +5 -0
  105. package/dist/node/utils/serializable.js +41 -0
  106. package/dist/node/utils/strings.js +41 -0
  107. package/dist/node/vite/config.js +289 -0
  108. package/dist/node/vite/paths.js +12 -0
  109. package/dist/node/vite/plugin-deps.js +232 -0
  110. package/dist/node/vite/plugin.js +281 -0
  111. package/dist/node/vite/react-compiler.js +362 -0
  112. package/dist/node/vite/source-files.js +83 -0
  113. package/dist/node/vite/static-image.js +136 -0
  114. package/dist/node/vite/styled-components.js +73 -0
  115. package/dist/node/vite/transforms.js +299 -0
  116. package/dist/node/wasm-data/host.js +406 -0
  117. package/dist/node/wasm-data/lower.js +406 -0
  118. package/dist/node/wasm-data/runner.js +79 -0
  119. package/dist/node/wasm-data/worker.js +95 -0
  120. package/dist/reporter.js +5 -0
  121. package/dist/runtime/api-runner.js +81 -0
  122. package/dist/runtime/app.js +256 -0
  123. package/dist/runtime/client-entry.js +4 -0
  124. package/dist/runtime/client.js +383 -0
  125. package/dist/runtime/default-html.js +31 -0
  126. package/dist/runtime/head-markup.js +100 -0
  127. package/dist/runtime/head-sync.js +101 -0
  128. package/dist/runtime/head-tags.js +45 -0
  129. package/dist/runtime/hydration-report.js +111 -0
  130. package/dist/runtime/index.js +12 -0
  131. package/dist/runtime/link.js +293 -0
  132. package/dist/runtime/loader.js +449 -0
  133. package/dist/runtime/not-found.js +61 -0
  134. package/dist/runtime/page-renderer.js +35 -0
  135. package/dist/runtime/preamble.js +47 -0
  136. package/dist/runtime/react-compat.js +14 -0
  137. package/dist/runtime/renderer-shared.js +10 -0
  138. package/dist/runtime/renderers/react-client.js +14 -0
  139. package/dist/runtime/renderers/react-server.js +99 -0
  140. package/dist/runtime/renderers/react.js +17 -0
  141. package/dist/runtime/renderers/types.js +1 -0
  142. package/dist/runtime/root-error-handlers.js +29 -0
  143. package/dist/runtime/router/history.js +132 -0
  144. package/dist/runtime/router/index.js +240 -0
  145. package/dist/runtime/router/utils.js +118 -0
  146. package/dist/runtime/script.js +110 -0
  147. package/dist/runtime/scroll.js +40 -0
  148. package/dist/runtime/slice.js +11 -0
  149. package/dist/runtime/ssr.js +240 -0
  150. package/dist/runtime/static-query.js +47 -0
  151. package/dist/utils.js +4 -0
  152. package/package.json +110 -3
  153. package/types/graphql-tada.d.ts +223 -0
  154. package/types/graphql.d.ts +2 -0
  155. package/types/index.d.ts +2287 -0
  156. package/types/node.d.ts +380 -0
  157. package/types/reporter.d.ts +187 -0
  158. package/types/router.d.ts +102 -0
  159. package/types/vendor/gql-tada.d.ts +2529 -0
@@ -0,0 +1,180 @@
1
+ import { getCache, onPersistCaches } from "../cache.js";
2
+ import { createContentDigest } from "../utils/content-digest.js";
3
+ import { isMainThread } from "node:worker_threads";
4
+ import crypto from "node:crypto";
5
+ import fs from "node:fs";
6
+ // src/node/actions/job-store.ts
7
+ /**
8
+ * Completed jobs (createJobV2), kept between builds – like Gatsby's persisted `jobsV2` state, so a
9
+ * page query that runs again (e.g. after a template change) does not process its images again.
10
+ *
11
+ * Stored in the plugin cache (`getCache`), not in a file of its own: it is the one store that every
12
+ * query worker thread reads and writes (jobs run in the thread whose query created them), it exists
13
+ * in both cache layouts, it is deleted with the other caches whenever they are invalidated, and its
14
+ * writes become permanent with the run's nodes (a record of an interrupted run is reverted with
15
+ * them, like the rest of the run's cache writes).
16
+ *
17
+ * A record is keyed by the job without its inputs' contents (name, input paths, output directory,
18
+ * args, plugin name), and holds the content digest it completed with: a job whose input changed
19
+ * replaces the record of its earlier version instead of adding one. The main thread keeps an index
20
+ * of the records (query workers report theirs to it, see `takeReportedJobs`), each with the run
21
+ * that last wrote or reused it. At the start of the next run (`pruneCompletedJobs`) it deletes the
22
+ * records whose inputs or output directory are gone, and those superseded: a job of the same name,
23
+ * inputs, output directory and plugin with other args (e.g. another image width) was used in a
24
+ * later run. (A page that uses the same image with other args, and whose query did not run again,
25
+ * loses its record that way: it is processed again once its query runs – never a stale result.)
26
+ */
27
+ const JOBS_CACHE = "goatly-jobs";
28
+ const INDEX_KEY = "index";
29
+ /** the main thread's index, once read (`pruneCompletedJobs`) */
30
+ let index;
31
+ /** the current run's number (main thread, once the index was read) */
32
+ let run = 0;
33
+ let indexChanged = false;
34
+ /** entries reported before the index was read (main thread), or not yet reported (workers) */
35
+ let unindexed = [];
36
+ onPersistCaches(() => {
37
+ if (!index || !isMainThread) return;
38
+ addJobIndexEntries(unindexed.splice(0));
39
+ if (!indexChanged) return;
40
+ indexChanged = false;
41
+ const stored = {
42
+ run,
43
+ entries: [...index.values()]
44
+ };
45
+ getCache(JOBS_CACHE).set(INDEX_KEY, stored);
46
+ });
47
+ const cache = () => getCache(JOBS_CACHE);
48
+ function jobRecordKey(job) {
49
+ return createContentDigest(job);
50
+ }
51
+ function jobGroupKey(job) {
52
+ return createContentDigest(job);
53
+ }
54
+ async function readJobRecord(key) {
55
+ try {
56
+ const record = await cache().get(key);
57
+ return record && typeof record.digest === "string" ? record : void 0;
58
+ } catch {
59
+ return;
60
+ }
61
+ }
62
+ async function writeJobRecord(key, record) {
63
+ try {
64
+ await cache().set(key, record);
65
+ } catch {}
66
+ }
67
+ /** a record was written or reused: kept in the index (main thread) or reported to it (workers) */
68
+ function indexJobRecord(entry) {
69
+ if (isMainThread) addJobIndexEntries([entry]);
70
+ else unindexed.push(entry);
71
+ }
72
+ /** a query worker's records since it last reported them (sent to the main thread) */
73
+ function takeReportedJobs() {
74
+ if (!unindexed.length) return void 0;
75
+ const entries = unindexed;
76
+ unindexed = [];
77
+ return entries;
78
+ }
79
+ /** the main thread: records written or reused (by a query worker) */
80
+ function addJobIndexEntries(entries) {
81
+ if (!index) {
82
+ unindexed.push(...entries);
83
+ return;
84
+ }
85
+ for (const entry of entries) index.set(entry.key, {
86
+ ...entry,
87
+ run
88
+ });
89
+ if (entries.length) indexChanged = true;
90
+ }
91
+ /**
92
+ * Reads the index and deletes the records whose output directory or inputs no longer exist, or
93
+ * that are superseded (main thread, once the cache is initialized at the start of a run). Returns
94
+ * the number deleted.
95
+ */
96
+ async function pruneCompletedJobs() {
97
+ index = void 0;
98
+ const c = cache();
99
+ let stored;
100
+ try {
101
+ stored = await c.get(INDEX_KEY);
102
+ } catch {}
103
+ const entries = (Array.isArray(stored?.entries) ? stored.entries : []).filter((e) => e && typeof e.key === "string" && Array.isArray(e.paths));
104
+ const latest = /* @__PURE__ */ new Map();
105
+ for (const e of entries) latest.set(e.group, Math.max(latest.get(e.group) ?? 0, e.run ?? 0));
106
+ const next = /* @__PURE__ */ new Map();
107
+ let pruned = 0;
108
+ for (const entry of entries) if ((entry.run ?? 0) >= latest.get(entry.group) && entry.paths.every((p) => fs.existsSync(p))) next.set(entry.key, entry);
109
+ else {
110
+ await c.del(entry.key);
111
+ pruned++;
112
+ }
113
+ index = next;
114
+ run = (typeof stored?.run === "number" ? stored.run : 0) + 1;
115
+ indexChanged = pruned > 0;
116
+ addJobIndexEntries(unindexed.splice(0));
117
+ return pruned;
118
+ }
119
+ /** the content hashes of input files, by path (valid while size and mtime are the same) */
120
+ const fileHashes = /* @__PURE__ */ new Map();
121
+ const MAX_HASHING = 8;
122
+ let hashing = 0;
123
+ const hashQueue = [];
124
+ async function hashFile(file) {
125
+ if (hashing >= MAX_HASHING) await new Promise((resolve) => hashQueue.push(resolve));
126
+ else hashing++;
127
+ try {
128
+ return await new Promise((resolve, reject) => {
129
+ const h = crypto.createHash("sha1");
130
+ let digest;
131
+ fs.createReadStream(file).on("error", reject).on("data", (chunk) => h.update(chunk)).on("end", () => digest = h.digest("hex")).on("close", () => digest ? resolve(digest) : reject(/* @__PURE__ */ new Error(`${file}: not read`)));
132
+ });
133
+ } finally {
134
+ const next = hashQueue.shift();
135
+ if (next) next();
136
+ else hashing--;
137
+ }
138
+ }
139
+ /**
140
+ * The digest of an input file's content (Gatsby's `createFileHash`: sha1), so a file that was only
141
+ * touched is not processed again. Hashed once per process while its size and mtime stay the same.
142
+ * `undefined` for a path whose content can't be hashed (missing, a directory, unreadable, or an
143
+ * error such as EMFILE): such a job is neither reused from an earlier build nor recorded for a
144
+ * later one (`fallbackDigest` dedupes it within the process).
145
+ */
146
+ function inputFileDigest(file) {
147
+ let stat;
148
+ try {
149
+ stat = fs.statSync(file);
150
+ } catch {
151
+ fileHashes.delete(file);
152
+ return Promise.resolve(void 0);
153
+ }
154
+ if (!stat.isFile()) return Promise.resolve(void 0);
155
+ const known = fileHashes.get(file);
156
+ if (known && known.size === stat.size && known.mtimeMs === stat.mtimeMs) return known.hash;
157
+ const hash = hashFile(file);
158
+ fileHashes.set(file, {
159
+ size: stat.size,
160
+ mtimeMs: stat.mtimeMs,
161
+ hash
162
+ });
163
+ return hash.catch(() => {
164
+ if (fileHashes.get(file)?.hash === hash) fileHashes.delete(file);
165
+ });
166
+ }
167
+ /** the digest of an input `inputFileDigest` can't hash, for this process: path, size and mtime */
168
+ function fallbackDigest(file) {
169
+ try {
170
+ const { size, mtimeMs } = fs.statSync(file);
171
+ return createContentDigest({
172
+ file,
173
+ size,
174
+ mtimeMs
175
+ });
176
+ } catch {
177
+ return createContentDigest(file);
178
+ }
179
+ }
180
+ export { addJobIndexEntries, fallbackDigest, indexJobRecord, inputFileDigest, jobGroupKey, jobRecordKey, pruneCompletedJobs, readJobRecord, takeReportedJobs, writeJobRecord };
@@ -0,0 +1,174 @@
1
+ import { store } from "../redux/index.js";
2
+ import reporter from "../reporter.js";
3
+ import { createContentDigest } from "../utils/content-digest.js";
4
+ import { importModule, normalizeModuleExports } from "../loader/import-module.js";
5
+ import { fallbackDigest, indexJobRecord, inputFileDigest, jobGroupKey, jobRecordKey, readJobRecord, writeJobRecord } from "./job-store.js";
6
+ import path from "node:path";
7
+ import fs from "node:fs";
8
+ import os from "node:os";
9
+ // src/node/actions/jobs.ts
10
+ const pending = /* @__PURE__ */ new Set();
11
+ const inFlight = /* @__PURE__ */ new Map();
12
+ const workerModules = /* @__PURE__ */ new Map();
13
+ /** the failures of jobs that ran (reported here); others – e.g. a plugin without a gatsby-worker – are not */
14
+ const reported = /* @__PURE__ */ new WeakSet();
15
+ let active = 0;
16
+ const queue = [];
17
+ const maxConcurrency = Math.max(1, os.availableParallelism?.() ?? os.cpus().length);
18
+ function acquire() {
19
+ if (active < maxConcurrency) {
20
+ active++;
21
+ return Promise.resolve();
22
+ }
23
+ return new Promise((resolve) => queue.push(() => (active++, resolve())));
24
+ }
25
+ function release() {
26
+ active--;
27
+ queue.shift()?.();
28
+ }
29
+ /** a query worker's: runs its jobs in the main thread (see forwardJobs) */
30
+ let forward;
31
+ /**
32
+ * Sends the jobs of this thread to another one (a query worker's to the main thread, like Gatsby's
33
+ * worker-messaging): there they are de-duplicated across all workers and share one concurrency
34
+ * limit – which also keeps the jobs' memory (e.g. sharp's, native) out of the workers
35
+ */
36
+ function forwardJobs(to) {
37
+ forward = to;
38
+ }
39
+ /**
40
+ * Gatsby Jobs API v2. Jobs are executed by the plugin's `gatsby-worker` module,
41
+ * in-process with bounded concurrency, and de-duplicated by content digest – also with the jobs
42
+ * of earlier builds (see job-store.ts): a job that completed before resolves with its result
43
+ * without running again, as long as its output directory still exists.
44
+ */
45
+ function createJobV2(job, plugin) {
46
+ const flattened = store.getState().flattenedPlugins.find((p) => p.name === plugin?.name);
47
+ if (!flattened?.gatsbyWorkerPath) return Promise.reject(/* @__PURE__ */ new Error(`Plugin "${plugin?.name}" called createJobV2 but has no gatsby-worker file`));
48
+ if (forward) return forward(job, {
49
+ name: flattened.name,
50
+ version: flattened.version
51
+ });
52
+ const promise = (async () => {
53
+ const paths = job.inputPaths.map((p) => path.resolve(p));
54
+ const hashes = await Promise.all(paths.map(inputFileDigest));
55
+ const persist = hashes.every((h) => h !== void 0);
56
+ const inputPaths = paths.map((p, i) => ({
57
+ path: p,
58
+ contentDigest: hashes[i] ?? fallbackDigest(p)
59
+ }));
60
+ const enhanced = {
61
+ id: "",
62
+ name: job.name,
63
+ inputPaths,
64
+ outputDir: job.outputDir,
65
+ args: job.args,
66
+ plugin: {
67
+ name: flattened.name,
68
+ version: flattened.version,
69
+ resolve: flattened.resolve
70
+ },
71
+ contentDigest: ""
72
+ };
73
+ enhanced.contentDigest = createContentDigest({
74
+ name: job.name,
75
+ inputPaths: inputPaths.map((p) => p.contentDigest),
76
+ outputDir: job.outputDir,
77
+ args: job.args,
78
+ plugin: enhanced.plugin
79
+ });
80
+ enhanced.id = enhanced.contentDigest;
81
+ const existing = inFlight.get(enhanced.contentDigest);
82
+ if (existing) return existing;
83
+ const done = store.getState().jobsV2.complete.get(enhanced.contentDigest);
84
+ if (done && fs.existsSync(job.outputDir)) return done.result;
85
+ const run = runJob(enhanced, paths, persist, flattened.gatsbyWorkerPath, plugin);
86
+ inFlight.set(enhanced.contentDigest, run);
87
+ run.finally(() => inFlight.delete(enhanced.contentDigest)).catch(() => {});
88
+ return run;
89
+ })();
90
+ pending.add(promise);
91
+ promise.finally(() => pending.delete(promise)).catch(() => {});
92
+ return promise;
93
+ }
94
+ async function runJob(job, paths, persist, workerPath, plugin) {
95
+ const digest = job.contentDigest;
96
+ const group = {
97
+ name: job.name,
98
+ inputPaths: paths,
99
+ outputDir: job.outputDir,
100
+ plugin: job.plugin.name
101
+ };
102
+ const key = jobRecordKey({
103
+ ...group,
104
+ args: job.args
105
+ });
106
+ const indexEntry = {
107
+ key,
108
+ group: jobGroupKey(group),
109
+ paths: [job.outputDir, ...paths]
110
+ };
111
+ const end = (result) => store.dispatch({
112
+ type: "END_JOB_V2",
113
+ plugin,
114
+ payload: {
115
+ jobContentDigest: digest,
116
+ result
117
+ }
118
+ });
119
+ const record = persist ? await readJobRecord(key) : void 0;
120
+ if (record?.digest === digest && fs.existsSync(job.outputDir)) {
121
+ end(record.result);
122
+ indexJobRecord(indexEntry);
123
+ return record.result;
124
+ }
125
+ store.dispatch({
126
+ type: "CREATE_JOB_V2",
127
+ plugin,
128
+ payload: { job }
129
+ });
130
+ await acquire();
131
+ try {
132
+ let modPromise = workerModules.get(workerPath);
133
+ if (!modPromise) {
134
+ modPromise = importModule(workerPath).then(normalizeModuleExports);
135
+ workerModules.set(workerPath, modPromise);
136
+ }
137
+ const fn = (await modPromise)[job.name];
138
+ if (typeof fn !== "function") throw new Error(`gatsby-worker of "${job.plugin.name}" does not export "${job.name}"`);
139
+ const result = await fn({
140
+ inputPaths: job.inputPaths,
141
+ outputDir: job.outputDir,
142
+ args: job.args
143
+ });
144
+ end(result);
145
+ if (persist) {
146
+ await writeJobRecord(key, {
147
+ digest,
148
+ result
149
+ });
150
+ indexJobRecord(indexEntry);
151
+ }
152
+ return result;
153
+ } catch (e) {
154
+ reporter.error({
155
+ context: { sourceMessage: `Job "${job.name}" of plugin "${job.plugin.name}" failed` },
156
+ error: e
157
+ });
158
+ if (e && typeof e === "object") reported.add(e);
159
+ throw e;
160
+ } finally {
161
+ release();
162
+ }
163
+ }
164
+ /** whether createJobV2 reported this failure of a job (else whoever gets the rejection does) */
165
+ function isReportedJobError(e) {
166
+ return !!e && typeof e === "object" && reported.has(e);
167
+ }
168
+ function hasPendingJobs() {
169
+ return pending.size > 0;
170
+ }
171
+ async function waitUntilAllJobsComplete() {
172
+ while (pending.size) await Promise.allSettled(pending);
173
+ }
174
+ export { createJobV2, forwardJobs, hasPendingJobs, isReportedJobError, waitUntilAllJobsComplete };
@@ -0,0 +1,258 @@
1
+ import { getNode, getNodes, getNodesByType } from "./datastore/index.js";
2
+ import { emitter, store } from "./redux/index.js";
3
+ import reporter, { noopTracer } from "./reporter.js";
4
+ import { getCache } from "./cache.js";
5
+ import { createNodeId } from "./utils/create-node-id.js";
6
+ import { createNodeContentDigest } from "./utils/content-digest.js";
7
+ import { getActionsForApi } from "./actions/index.js";
8
+ import { typeBuilders } from "./schema/type-builders.js";
9
+ import { getNodeAndSavePathDependency, loadNodeContent } from "./node-helpers.js";
10
+ // src/node/api-runner.ts
11
+ /** Tracks asynchronous "cascading" API runs (onCreateNode, onCreatePage) per trace id. */
12
+ const pendingByTrace = /* @__PURE__ */ new Map();
13
+ function trackCascade(traceId, promise) {
14
+ const key = traceId ?? "__global__";
15
+ let set = pendingByTrace.get(key);
16
+ if (!set) {
17
+ set = /* @__PURE__ */ new Set();
18
+ pendingByTrace.set(key, set);
19
+ }
20
+ set.add(promise);
21
+ promise.finally(() => set.delete(promise)).catch(() => {});
22
+ }
23
+ /** no cascading API run (onCreateNode, onCreatePage, …) is in progress */
24
+ function cascadeIdle() {
25
+ for (const set of pendingByTrace.values()) if (set.size > 0) return false;
26
+ return true;
27
+ }
28
+ async function waitForCascade(traceId) {
29
+ const key = traceId ?? "__global__";
30
+ for (;;) {
31
+ const set = pendingByTrace.get(key);
32
+ if (!set || set.size === 0) return;
33
+ await Promise.allSettled(set);
34
+ }
35
+ }
36
+ function getPublicPath() {
37
+ const { config, program } = store.getState();
38
+ const pathPrefix = program.prefixPaths && config.pathPrefix || "";
39
+ const assetPrefix = program.prefixPaths && config.assetPrefix || "";
40
+ if (assetPrefix) return `${assetPrefix}${pathPrefix}`;
41
+ return pathPrefix;
42
+ }
43
+ function createLocalReporter(pluginName) {
44
+ const running = /* @__PURE__ */ new Set();
45
+ const local = Object.create(reporter);
46
+ local.activityTimer = (...args) => {
47
+ const activity = reporter.activityTimer(...args);
48
+ const end = activity.end;
49
+ activity.end = () => {
50
+ running.delete(activity);
51
+ end();
52
+ };
53
+ running.add(activity);
54
+ return activity;
55
+ };
56
+ local.createProgress = (...args) => {
57
+ const progress = reporter.createProgress(...args);
58
+ const end = progress.end;
59
+ progress.end = () => {
60
+ running.delete(progress);
61
+ end();
62
+ };
63
+ running.add(progress);
64
+ return progress;
65
+ };
66
+ local.panicOnBuild = (meta, error) => {
67
+ reporter.panicOnBuild(meta, error);
68
+ };
69
+ local.pluginName = pluginName;
70
+ return {
71
+ reporter: local,
72
+ endAll: () => running.forEach((a) => a.end())
73
+ };
74
+ }
75
+ function getPluginTracing() {
76
+ const parentSpan = noopTracer.startSpan();
77
+ return {
78
+ tracer: noopTracer,
79
+ parentSpan,
80
+ startSpan: () => noopTracer.startSpan()
81
+ };
82
+ }
83
+ /**
84
+ * Builds the first argument passed to every Node API, identical in shape to Gatsby's.
85
+ */
86
+ function buildApiArgs(plugin, api, args) {
87
+ const actions = getActionsForApi(api, plugin, {
88
+ traceId: args.traceId,
89
+ parentSpan: args.parentSpan
90
+ });
91
+ const { config, program } = store.getState();
92
+ const basePath = program.prefixPaths && config.pathPrefix || "";
93
+ const local = createLocalReporter(plugin.name);
94
+ return {
95
+ apiArgs: {
96
+ ...args,
97
+ parentSpan: args.parentSpan ?? noopTracer.startSpan(),
98
+ basePath,
99
+ pathPrefix: getPublicPath(),
100
+ actions,
101
+ loadNodeContent,
102
+ store,
103
+ emitter,
104
+ getCache,
105
+ getNodes,
106
+ getNode,
107
+ getNodesByType,
108
+ reporter: local.reporter,
109
+ getNodeAndSavePathDependency,
110
+ cache: getCache(plugin.name),
111
+ createNodeId: (id) => createNodeId(id, plugin.name),
112
+ createContentDigest: createNodeContentDigest,
113
+ tracing: getPluginTracing(),
114
+ schema: typeBuilders
115
+ },
116
+ endActivities: local.endAll
117
+ };
118
+ }
119
+ async function runPluginApi(plugin, api, args) {
120
+ const fn = plugin.module?.[api];
121
+ if (typeof fn !== "function") return null;
122
+ const { apiArgs, endActivities } = buildApiArgs(plugin, api, args);
123
+ try {
124
+ if (fn.length === 3) return await new Promise((resolve, reject) => {
125
+ try {
126
+ fn(apiArgs, plugin.pluginOptions, (err, value) => err ? reject(err) : resolve(value));
127
+ } catch (e) {
128
+ reject(e);
129
+ }
130
+ });
131
+ return await fn(apiArgs, plugin.pluginOptions);
132
+ } finally {
133
+ endActivities();
134
+ }
135
+ }
136
+ function reportApiError(plugin, api, err) {
137
+ const pluginName = plugin.name === "default-site-plugin" ? "gatsby-node" : plugin.name;
138
+ reporter.panicOnBuild({
139
+ id: "11321",
140
+ context: {
141
+ pluginName,
142
+ api,
143
+ sourceMessage: err?.message ?? String(err)
144
+ },
145
+ error: err
146
+ });
147
+ }
148
+ /**
149
+ * An internal plugin's static predicate for its onCreatePage (on its module, under this symbol):
150
+ * false when the call would do nothing for the page. The runner then leaves the plugin out for that
151
+ * page, and createPage skips the API run when no implementer is left (prod-404-500 is called for
152
+ * every page of every site, nearly always for nothing). A symbol: a gatsby-node can't export it by
153
+ * accident, and it is no Node API (`Object.keys` doesn't list it).
154
+ */
155
+ const ON_CREATE_PAGE_FILTER = Symbol("goatly.onCreatePageFilter");
156
+ /** the plugin's onCreatePage would provably do nothing for `page` */
157
+ function skipsPage(plugin, page) {
158
+ const filter = plugin.module?.[ON_CREATE_PAGE_FILTER];
159
+ if (typeof filter !== "function") return false;
160
+ try {
161
+ return !filter(page);
162
+ } catch {
163
+ return false;
164
+ }
165
+ }
166
+ const implementersMemo = /* @__PURE__ */ new WeakMap();
167
+ function implementingPlugins(api, pluginSource) {
168
+ const all = store.getState().flattenedPlugins;
169
+ let byKey = implementersMemo.get(all);
170
+ if (!byKey) implementersMemo.set(all, byKey = /* @__PURE__ */ new Map());
171
+ const key = pluginSource === void 0 ? api : `${api}\0${pluginSource}`;
172
+ let plugins = byKey.get(key);
173
+ if (!plugins) {
174
+ plugins = all.filter((p) => p.nodeAPIs.includes(api) && p.name !== pluginSource);
175
+ byKey.set(key, plugins);
176
+ }
177
+ return plugins;
178
+ }
179
+ /**
180
+ * onCreatePage for a page createPage just created, a cascade of `traceId`. Nothing is run (nor
181
+ * tracked) when every implementer's filter says it would do nothing for the page: typically only
182
+ * prod-404-500 implements it, and it only acts on 404/500 pages (and sections' 404 pages).
183
+ */
184
+ function runOnCreatePage(page, traceId, parentSpan, pluginSource) {
185
+ if (implementingPlugins("onCreatePage", pluginSource).every((p) => skipsPage(p, page))) return;
186
+ trackCascade(traceId, apiRunnerNode("onCreatePage", {
187
+ page,
188
+ traceId,
189
+ parentSpan
190
+ }, { pluginSource }));
191
+ }
192
+ /**
193
+ * Runs a Node API for all plugins implementing it, sequentially in plugin order
194
+ * (same semantics as Gatsby's `apiRunnerNode`). Returns the array of non-empty results.
195
+ */
196
+ async function apiRunnerNode(api, args = {}, options = {}) {
197
+ let plugins = implementingPlugins(api, options.pluginSource);
198
+ if (api === "onPluginInit") plugins = [...plugins, ...implementingPlugins("unstable_onPluginInit", options.pluginSource)];
199
+ if (api === "sourceNodes" && args.pluginName) plugins = plugins.filter((p) => p.name === args.pluginName);
200
+ if (plugins.length === 0) {
201
+ if (args.waitForCascadingActions) await waitForCascade(args.traceId);
202
+ return [];
203
+ }
204
+ const page = api === "onCreatePage" ? args.page : void 0;
205
+ const results = [];
206
+ try {
207
+ for (const plugin of plugins) {
208
+ if (page && !store.getState().pages.has(page.path)) break;
209
+ if (page && skipsPage(plugin, page)) continue;
210
+ const name = api === "unstable_onPluginInit" ? "onPluginInit" : api;
211
+ const implName = plugin.nodeAPIs.includes(name) ? name : api;
212
+ try {
213
+ const result = await runPluginApi(plugin, implName, args);
214
+ if (result !== void 0 && result !== null && !(typeof result === "object" && Object.keys(result).length === 0)) results.push(result);
215
+ } catch (err) {
216
+ if (err?.isPanic) throw err;
217
+ reportApiError(plugin, api, err);
218
+ }
219
+ }
220
+ } finally {}
221
+ if (args.waitForCascadingActions) await waitForCascade(args.traceId);
222
+ return results;
223
+ }
224
+ /** Runs onCreateNode for a newly created node (respecting shouldOnCreateNode). */
225
+ function runOnCreateNode(node, traceId, parentSpan) {
226
+ const plugins = implementingPlugins("onCreateNode");
227
+ if (plugins.length === 0) return Promise.resolve();
228
+ const run = (async () => {
229
+ for (const plugin of plugins) {
230
+ const mod = plugin.module;
231
+ const should = mod.shouldOnCreateNode ?? mod.unstable_shouldOnCreateNode;
232
+ if (typeof should === "function" && !should({ node }, plugin.pluginOptions)) continue;
233
+ try {
234
+ await runPluginApi(plugin, "onCreateNode", {
235
+ node,
236
+ traceId,
237
+ parentSpan,
238
+ traceTags: {
239
+ nodeId: node.id,
240
+ nodeType: node.internal.type
241
+ }
242
+ });
243
+ } catch (err) {
244
+ if (err?.isPanic) throw err;
245
+ reportApiError(plugin, "onCreateNode", err);
246
+ }
247
+ }
248
+ })();
249
+ trackCascade(traceId, run);
250
+ return run;
251
+ }
252
+ /** Runs a single plugin's API (used e.g. for `loadNodeContent`). */
253
+ async function runSinglePluginApi(pluginName, api, args) {
254
+ const plugin = store.getState().flattenedPlugins.find((p) => p.name === pluginName);
255
+ if (!plugin) return void 0;
256
+ return runPluginApi(plugin, api, args);
257
+ }
258
+ export { ON_CREATE_PAGE_FILTER, apiRunnerNode, buildApiArgs, cascadeIdle, getPluginTracing, runOnCreateNode, runOnCreatePage, runSinglePluginApi, trackCascade, waitForCascade };