goatly 0.1.0 → 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 (158) hide show
  1. package/README.md +853 -1
  2. package/bin/goatly.js +91 -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 +539 -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 +752 -0
  18. package/dist/node/build/memory-governor.js +448 -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 +54 -0
  22. package/dist/node/build/partitioned-state.js +258 -0
  23. package/dist/node/build/query-worker.js +536 -0
  24. package/dist/node/build/query-workers.js +832 -0
  25. package/dist/node/build/render-worker.js +131 -0
  26. package/dist/node/build/state.js +24 -0
  27. package/dist/node/build/timing-breakdown.js +155 -0
  28. package/dist/node/build/worker-pool.js +236 -0
  29. package/dist/node/cache-layout.js +99 -0
  30. package/dist/node/cache.js +1430 -0
  31. package/dist/node/compat/chokidar-shim.js +148 -0
  32. package/dist/node/compat/core-utils-lmdb.js +145 -0
  33. package/dist/node/compat/create-node-id-shim.js +1 -0
  34. package/dist/node/compat/module-hooks.js +245 -0
  35. package/dist/node/compat/redux-shim.js +1 -0
  36. package/dist/node/config/index.js +162 -0
  37. package/dist/node/config/not-found-pages.js +95 -0
  38. package/dist/node/datastore/codec.js +144 -0
  39. package/dist/node/datastore/index.js +127 -0
  40. package/dist/node/datastore/logfile/cache.js +89 -0
  41. package/dist/node/datastore/logfile/index.js +1329 -0
  42. package/dist/node/datastore/logfile/record.js +71 -0
  43. package/dist/node/datastore/types.js +1 -0
  44. package/dist/node/develop/express-compat.js +207 -0
  45. package/dist/node/develop/graphiql.js +22 -0
  46. package/dist/node/develop/hydration-report.js +41 -0
  47. package/dist/node/develop/index.js +618 -0
  48. package/dist/node/develop/local-url.js +10 -0
  49. package/dist/node/develop/ssr-runner.js +66 -0
  50. package/dist/node/gql.js +5 -0
  51. package/dist/node/index.js +15 -0
  52. package/dist/node/info.js +270 -0
  53. package/dist/node/internal-plugins/data-bridge.js +196 -0
  54. package/dist/node/internal-plugins/page-creator.js +318 -0
  55. package/dist/node/loader/import-module.js +160 -0
  56. package/dist/node/node-helpers.js +66 -0
  57. package/dist/node/not-found-pages.js +220 -0
  58. package/dist/node/plugins/api-list.js +12 -0
  59. package/dist/node/plugins/load-plugins.js +427 -0
  60. package/dist/node/plugins/resolve-plugin.js +79 -0
  61. package/dist/node/plugins/static-exports.js +64 -0
  62. package/dist/node/query/compile.js +326 -0
  63. package/dist/node/query/dependencies.js +45 -0
  64. package/dist/node/query/execute.js +417 -0
  65. package/dist/node/query/extract.js +372 -0
  66. package/dist/node/query/gql-tada-introspection.js +124 -0
  67. package/dist/node/query/graphql-env.js +231 -0
  68. package/dist/node/query/graphql-runner.js +79 -0
  69. package/dist/node/redux/actions.js +1 -0
  70. package/dist/node/redux/index.js +133 -0
  71. package/dist/node/redux/node-changes.js +128 -0
  72. package/dist/node/redux/reducers.js +193 -0
  73. package/dist/node/redux/state.js +71 -0
  74. package/dist/node/renderer.js +124 -0
  75. package/dist/node/reporter-transports.js +259 -0
  76. package/dist/node/reporter.js +497 -0
  77. package/dist/node/schema/date.js +539 -0
  78. package/dist/node/schema/extensions.js +315 -0
  79. package/dist/node/schema/index.js +542 -0
  80. package/dist/node/schema/infer.js +388 -0
  81. package/dist/node/schema/inline-objects.js +128 -0
  82. package/dist/node/schema/naming.js +20 -0
  83. package/dist/node/schema/node-model.js +207 -0
  84. package/dist/node/schema/query-engine.js +1808 -0
  85. package/dist/node/schema/resolver-kinds.js +7 -0
  86. package/dist/node/schema/resolvers.js +273 -0
  87. package/dist/node/schema/type-builders.js +45 -0
  88. package/dist/node/schema/types.js +241 -0
  89. package/dist/node/serve.js +90 -0
  90. package/dist/node/site-page-nodes.js +277 -0
  91. package/dist/node/types.js +1 -0
  92. package/dist/node/utils/content-digest.js +107 -0
  93. package/dist/node/utils/create-node-id.js +51 -0
  94. package/dist/node/utils/env.js +24 -0
  95. package/dist/node/utils/fs-retry.js +74 -0
  96. package/dist/node/utils/memory-signals.js +410 -0
  97. package/dist/node/utils/memory.js +400 -0
  98. package/dist/node/utils/murmurhash.js +32 -0
  99. package/dist/node/utils/parser.js +33 -0
  100. package/dist/node/utils/partition-hash.js +19 -0
  101. package/dist/node/utils/paths.js +122 -0
  102. package/dist/node/utils/resolver.js +48 -0
  103. package/dist/node/utils/runtime.js +5 -0
  104. package/dist/node/utils/serializable.js +41 -0
  105. package/dist/node/utils/strings.js +41 -0
  106. package/dist/node/vite/config.js +289 -0
  107. package/dist/node/vite/paths.js +12 -0
  108. package/dist/node/vite/plugin-deps.js +232 -0
  109. package/dist/node/vite/plugin.js +281 -0
  110. package/dist/node/vite/react-compiler.js +362 -0
  111. package/dist/node/vite/source-files.js +83 -0
  112. package/dist/node/vite/static-image.js +136 -0
  113. package/dist/node/vite/styled-components.js +73 -0
  114. package/dist/node/vite/transforms.js +299 -0
  115. package/dist/node/wasm-data/host.js +406 -0
  116. package/dist/node/wasm-data/lower.js +406 -0
  117. package/dist/node/wasm-data/runner.js +79 -0
  118. package/dist/node/wasm-data/worker.js +95 -0
  119. package/dist/reporter.js +5 -0
  120. package/dist/runtime/api-runner.js +81 -0
  121. package/dist/runtime/app.js +256 -0
  122. package/dist/runtime/client-entry.js +4 -0
  123. package/dist/runtime/client.js +383 -0
  124. package/dist/runtime/default-html.js +31 -0
  125. package/dist/runtime/head-markup.js +100 -0
  126. package/dist/runtime/head-sync.js +101 -0
  127. package/dist/runtime/head-tags.js +45 -0
  128. package/dist/runtime/hydration-report.js +111 -0
  129. package/dist/runtime/index.js +12 -0
  130. package/dist/runtime/link.js +293 -0
  131. package/dist/runtime/loader.js +449 -0
  132. package/dist/runtime/not-found.js +61 -0
  133. package/dist/runtime/page-renderer.js +35 -0
  134. package/dist/runtime/preamble.js +47 -0
  135. package/dist/runtime/react-compat.js +14 -0
  136. package/dist/runtime/renderer-shared.js +10 -0
  137. package/dist/runtime/renderers/react-client.js +14 -0
  138. package/dist/runtime/renderers/react-server.js +99 -0
  139. package/dist/runtime/renderers/react.js +17 -0
  140. package/dist/runtime/renderers/types.js +1 -0
  141. package/dist/runtime/root-error-handlers.js +29 -0
  142. package/dist/runtime/router/history.js +132 -0
  143. package/dist/runtime/router/index.js +240 -0
  144. package/dist/runtime/router/utils.js +118 -0
  145. package/dist/runtime/script.js +110 -0
  146. package/dist/runtime/scroll.js +40 -0
  147. package/dist/runtime/slice.js +11 -0
  148. package/dist/runtime/ssr.js +240 -0
  149. package/dist/runtime/static-query.js +47 -0
  150. package/dist/utils.js +4 -0
  151. package/package.json +105 -3
  152. package/types/graphql-tada.d.ts +223 -0
  153. package/types/graphql.d.ts +2 -0
  154. package/types/index.d.ts +2287 -0
  155. package/types/node.d.ts +380 -0
  156. package/types/reporter.d.ts +187 -0
  157. package/types/router.d.ts +102 -0
  158. package/types/vendor/gql-tada.d.ts +2529 -0
@@ -0,0 +1,536 @@
1
+ import { WorkerControl } from "./memory-governor.js";
2
+ import { performance } from "node:perf_hooks";
3
+ import { isMainThread, parentPort, workerData } from "node:worker_threads";
4
+ // src/node/build/query-worker.ts
5
+ /**
6
+ * Query worker (parallel query running): loads the datastore (e.g. the logfile store's index), runs
7
+ * page queries (recording their data dependencies) and – as soon as the main thread sent the
8
+ * renderer config – renders each batch right after querying it. Until then results are buffered,
9
+ * as many as the main thread allows (it stops sending queries when the buffer reaches its share of
10
+ * the heap), and rendered in chunks the main thread asks for. Pages with a still valid query result
11
+ * (incremental builds) are rendered from their existing page-data.json when their HTML is outdated
12
+ * (the main thread sends them once the bundles exist). Pages are rendered in chunks of at most
13
+ * RENDER_CHUNK pages or RENDER_CHUNK_CHARS characters of page data, and the worker drops its caches
14
+ * when its heap fills up (createHeapGuard).
15
+ */
16
+ /** pages and characters of page data rendered at a time (cached results are read per chunk, too) */
17
+ const RENDER_CHUNK = 64;
18
+ const RENDER_CHUNK_CHARS = 8388608;
19
+ /** page queries of a batch running at a time (Gatsby: 4) */
20
+ const QUERY_CONCURRENCY = 8;
21
+ async function main(data) {
22
+ const port = parentPort;
23
+ try {
24
+ const { bootstrapWorker } = await import("../bootstrap.js");
25
+ const { runGraphQL } = await import("../query/graphql-runner.js");
26
+ const { generateHtmlPath, generatePageDataPath } = await import("../utils/paths.js");
27
+ const { AssetResolver } = await import("./assets.js");
28
+ const { createRenderer } = await import("./render-worker.js");
29
+ const { createDirectoryMaker, outputDirs } = await import("./output-dirs.js");
30
+ const { finishCaches, persistCaches, releaseCaches } = await import("../cache.js");
31
+ const { getDataStore, nodeTypeOf } = await import("../datastore/index.js");
32
+ const { forwardJobs } = await import("../actions/jobs.js");
33
+ const jobs = /* @__PURE__ */ new Map();
34
+ let jobIds = 0;
35
+ forwardJobs((job, plugin) => {
36
+ const jobId = jobIds++;
37
+ let resolve, reject;
38
+ const promise = new Promise((res, rej) => (resolve = res, reject = rej));
39
+ jobs.set(jobId, {
40
+ promise,
41
+ resolve,
42
+ reject
43
+ });
44
+ try {
45
+ port.postMessage({
46
+ type: "job",
47
+ jobId,
48
+ job,
49
+ plugin
50
+ });
51
+ } catch (e) {
52
+ jobs.delete(jobId);
53
+ return Promise.reject(e);
54
+ }
55
+ return promise;
56
+ });
57
+ port.on("message", (msg) => {
58
+ if (msg.type !== "job-done" && msg.type !== "job-failed") return;
59
+ const waiting = jobs.get(msg.jobId);
60
+ if (!waiting) return;
61
+ jobs.delete(msg.jobId);
62
+ if (msg.type === "job-done") return waiting.resolve(msg.result);
63
+ if (msg.reported) waiting.promise.catch(() => {});
64
+ waiting.reject(Object.assign(new Error(msg.message), { stack: msg.stack }));
65
+ });
66
+ const { clearQueryEngineCaches, setSlimNodesHeap } = await import("../schema/query-engine.js");
67
+ const { createHeapGuard, heapRatio, heapUsedMb } = await import("../utils/memory.js");
68
+ const { reporter } = await import("../reporter.js");
69
+ const { QueryDependencies } = await import("../query/dependencies.js");
70
+ const { hashString, htmlDigest, htmlRemovedEachBuild, readCachedResult, serializeDependencies } = await import("./incremental.js");
71
+ const { createSitePageDeferrals, sitePageNodesWereRead } = await import("../site-page-nodes.js");
72
+ const wasmModule = data.wasmData ? await import("../wasm-data/worker.js") : void 0;
73
+ const wasm = wasmModule && data.wasmData ? wasmModule.createWasmRunner(data.wasmData) : void 0;
74
+ await bootstrapWorker({
75
+ directory: data.directory,
76
+ prefixPaths: data.prefixPaths,
77
+ inferenceFile: data.inferenceFile,
78
+ renderer: data.renderer,
79
+ sitePageNodes: data.sitePageNodes,
80
+ cacheRun: data.cacheRun
81
+ });
82
+ const control = data.control ? new Int32Array(data.control) : void 0;
83
+ /** the heap (MB) this worker measures itself against: the budget it was given, if any */
84
+ const budget = () => control && Atomics.load(control, WorkerControl.BUDGET) || data.heapBudgetMb;
85
+ const v8 = await import("node:v8");
86
+ let limitMb;
87
+ const heapLimitMb = () => limitMb ??= v8.getHeapStatistics().heap_size_limit / 1048576;
88
+ let slimFor = budget() ?? heapLimitMb();
89
+ setSlimNodesHeap(slimFor);
90
+ /** publishes the heap in use (the adaptive pool sizes budgets and picks workers by it) */
91
+ const publish = () => {
92
+ if (!control) return;
93
+ Atomics.store(control, WorkerControl.HEAP, Math.round(heapUsedMb()));
94
+ if (wasm) Atomics.store(control, WorkerControl.WASM, Math.round(wasm.threadBytes() / 1048576));
95
+ Atomics.add(control, WorkerControl.BEAT, 1);
96
+ };
97
+ const deferrals = createSitePageDeferrals();
98
+ let job;
99
+ let renderer;
100
+ /** creates the output directories of the pages this worker renders */
101
+ let dirs;
102
+ let assets;
103
+ /** the renderer could not be set up: every page fails with this error */
104
+ let setupError;
105
+ /** results waiting for the renderer bundle, by page path (`resultJson` unset: cached result) */
106
+ const buffered = /* @__PURE__ */ new Map();
107
+ let bufferedBytes = 0;
108
+ /** estimated heap bytes of a page's results: its Page clone and `chars` of JSON (1–2 bytes each) */
109
+ const resultBytes = (chars) => 1024 + 2 * chars;
110
+ const itemBytes = (item) => resultBytes(item.resultJson?.length ?? 0);
111
+ /** characters of cached results render() read (they count towards a batch's bytes) */
112
+ let readChars = 0;
113
+ const ratio = () => heapRatio(budget());
114
+ const guard = createHeapGuard({
115
+ ratio,
116
+ release() {
117
+ clearQueryEngineCaches();
118
+ releaseCaches();
119
+ getDataStore().trimCache?.();
120
+ }
121
+ });
122
+ /** the budget the guard measured against at its last check (or rebase) */
123
+ let guardBudget = budget();
124
+ /**
125
+ * Checks the heap after a batch (see createHeapGuard) against the current budget: a budget cut
126
+ * by the adaptive pool – also step by step – is checked at once; the slim nodes follow it, too
127
+ */
128
+ const checkHeap = () => {
129
+ const now = budget();
130
+ let rebased = false;
131
+ if (now !== void 0 && guardBudget !== void 0 && now < .9 * guardBudget) {
132
+ guard.rebase();
133
+ rebased = true;
134
+ }
135
+ const forSlim = now ?? heapLimitMb();
136
+ if (Math.abs(forSlim - slimFor) >= .25 * slimFor) setSlimNodesHeap(slimFor = forSlim);
137
+ const checks = guard.checks;
138
+ guard.afterBatch();
139
+ const checked = guard.checks !== checks;
140
+ if (rebased || checked || (now ?? 0) > (guardBudget ?? 0)) guardBudget = now;
141
+ if (control && checked) Atomics.store(control, WorkerControl.LIVE, Math.round(heapUsedMb()));
142
+ publish();
143
+ };
144
+ const clock = () => performance.timeOrigin + performance.now();
145
+ const emptySpan = () => ({
146
+ ms: 0,
147
+ start: 1e400,
148
+ end: -1e400
149
+ });
150
+ const timings = {
151
+ query: emptySpan(),
152
+ render: emptySpan()
153
+ };
154
+ const track = (span, start, end = clock(), ms = end - start) => {
155
+ span.ms += ms;
156
+ span.start = Math.min(span.start, start);
157
+ span.end = Math.max(span.end, end);
158
+ };
159
+ const emptyResult = () => ({
160
+ rendered: 0,
161
+ skipped: 0,
162
+ digests: {},
163
+ errors: []
164
+ });
165
+ const queryOutput = () => ({
166
+ queries: [],
167
+ errors: [],
168
+ deferred: []
169
+ });
170
+ /** runs a page query (undefined: the page is left to the main thread, see `deferrals`) */
171
+ async function runQuery(page, out) {
172
+ const index = data.componentQueries[page.componentPath];
173
+ const query = index === void 0 ? void 0 : data.queryTexts[index];
174
+ let resultData;
175
+ let error;
176
+ const deps = new QueryDependencies();
177
+ if (query) {
178
+ if (deferrals.skip(index)) {
179
+ out.deferred.push(page.path);
180
+ return;
181
+ }
182
+ const start = deferrals.start();
183
+ const res = await runGraphQL(query, {
184
+ ...page,
185
+ ...page.context
186
+ }, page.path, deps, { plainObjects: true });
187
+ if (deferrals.missed(start, index)) {
188
+ out.deferred.push(page.path);
189
+ return;
190
+ }
191
+ if (res.errors?.length) error = {
192
+ pagePath: page.path,
193
+ message: res.errors.map((e) => e.message).join("\n")
194
+ };
195
+ resultData = res.data;
196
+ }
197
+ if (error) out.errors.push(error);
198
+ const resultJson = JSON.stringify({
199
+ data: resultData,
200
+ pageContext: page.context
201
+ });
202
+ const resultHash = hashString(resultJson);
203
+ const { n, c } = serializeDependencies(deps, nodeTypeOf);
204
+ out.queries.push([
205
+ page.path,
206
+ resultHash,
207
+ n,
208
+ c
209
+ ]);
210
+ return {
211
+ page,
212
+ resultHash,
213
+ resultJson
214
+ };
215
+ }
216
+ /**
217
+ * Runs the pages of `items` whose queries the WASM data side supports, WASM_BATCH per call,
218
+ * into `ran` (pages it can't answer stay unset: they run in JS). Verify mode: their queries
219
+ * run in JS, too, the JS result is used and a different WASM result is reported.
220
+ */
221
+ async function runWasm(runner, { WASM_BATCH, resultJsonOf, sameResult }, items, ran, out) {
222
+ /** the items handled here */
223
+ const done = /* @__PURE__ */ new Set();
224
+ const pending = [];
225
+ for (let i = 0; i < items.length; i++) {
226
+ const item = items[i];
227
+ if (item.resultHash !== void 0) continue;
228
+ const index = data.componentQueries[item.page.componentPath];
229
+ if (index === void 0 || deferrals.skip(index)) continue;
230
+ const page = runner.page(item.page, index);
231
+ if (page) pending.push({
232
+ i,
233
+ page
234
+ });
235
+ }
236
+ for (let from = 0; from < pending.length; from += WASM_BATCH) {
237
+ const chunk = pending.slice(from, from + WASM_BATCH);
238
+ const results = runner.run(chunk.map((p) => p.page));
239
+ if (!results) break;
240
+ for (let k = 0; k < chunk.length; k++) {
241
+ const r = results[k];
242
+ if (r.status !== 0) continue;
243
+ const { i } = chunk[k];
244
+ done.add(i);
245
+ const item = items[i];
246
+ const { page } = item;
247
+ const resultJson = resultJsonOf(page, r.data);
248
+ if (runner.verify) {
249
+ const js = queryOutput();
250
+ const result = await runQuery(page, js);
251
+ out.queries.push(...js.queries);
252
+ out.errors.push(...js.errors);
253
+ out.deferred.push(...js.deferred);
254
+ ran[i] = result && {
255
+ ...result,
256
+ previous: item.previous
257
+ };
258
+ if (!result) continue;
259
+ const record = js.queries[0];
260
+ const jsResult = {
261
+ resultJson: result.resultJson,
262
+ n: record?.[2],
263
+ c: record?.[3],
264
+ errors: js.errors.length
265
+ };
266
+ if (!sameResult({
267
+ resultJson,
268
+ n: r.n,
269
+ c: r.c
270
+ }, jsResult)) runner.mismatch({
271
+ path: page.path,
272
+ wasm: {
273
+ resultJson,
274
+ n: r.n,
275
+ c: r.c
276
+ },
277
+ js: jsResult
278
+ });
279
+ continue;
280
+ }
281
+ const resultHash = hashString(resultJson);
282
+ out.queries.push([
283
+ page.path,
284
+ resultHash,
285
+ r.n,
286
+ r.c
287
+ ]);
288
+ ran[i] = {
289
+ page,
290
+ resultHash,
291
+ resultJson,
292
+ previous: item.previous
293
+ };
294
+ }
295
+ publish();
296
+ }
297
+ return done;
298
+ }
299
+ async function render(items, queryOut) {
300
+ const out = emptyResult();
301
+ if (!job || !items.length) return out;
302
+ if (!renderer || !assets) {
303
+ for (const { page } of items) {
304
+ const message = setupError?.message ?? "the renderer is not set up";
305
+ out.errors.push({
306
+ pagePath: page.path,
307
+ message,
308
+ stack: setupError?.stack
309
+ });
310
+ }
311
+ return out;
312
+ }
313
+ const start = clock();
314
+ /** queries that ran after all (missing cached results) count as query time */
315
+ let queryMs = 0;
316
+ let tasks = [];
317
+ let taskChars = 0;
318
+ const renderTasks = async () => {
319
+ if (!tasks.length) return;
320
+ const chunk = tasks;
321
+ tasks = [];
322
+ taskChars = 0;
323
+ await dirs?.ensure(outputDirs(chunk));
324
+ const res = await renderer.renderBatch(chunk);
325
+ publish();
326
+ out.rendered += res.rendered;
327
+ out.errors.push(...res.errors);
328
+ };
329
+ for (let item of items) {
330
+ const { page } = item;
331
+ let digest = htmlDigest(page, item.resultHash);
332
+ if (job.previousSsrHash === job.ssrHash && item.previous === digest && !htmlRemovedEachBuild(page.path)) {
333
+ out.digests[page.path] = digest;
334
+ out.skipped++;
335
+ continue;
336
+ }
337
+ const htmlFile = generateHtmlPath(job.publicDir, page.path);
338
+ const pageDataFile = generatePageDataPath(job.publicDir, page.path);
339
+ const cached = item.resultJson === void 0 ? readCachedResult(job.publicDir, page) : void 0;
340
+ let resultJson = item.resultJson ?? cached?.resultJson;
341
+ if (cached) readChars += cached.resultJson.length;
342
+ if (resultJson === void 0) {
343
+ const t = clock();
344
+ const ran = await runQuery(page, queryOut);
345
+ const tEnd = clock();
346
+ track(timings.query, t, tEnd);
347
+ queryMs += tEnd - t;
348
+ if (!ran) continue;
349
+ item = {
350
+ ...ran,
351
+ previous: item.previous
352
+ };
353
+ resultJson = item.resultJson;
354
+ digest = htmlDigest(page, item.resultHash);
355
+ }
356
+ out.digests[page.path] = digest;
357
+ const fixed = page.path === "/" ? "index" : page.path.replace(/^\/|\/$/g, "");
358
+ tasks.push({
359
+ pagePath: page.path,
360
+ componentChunkName: page.componentChunkName,
361
+ matchPath: page.matchPath,
362
+ resultJson,
363
+ assets: assets.forComponents([page.componentPath]),
364
+ pageDataUrl: `${job.pagePrefix}/page-data/${fixed}/page-data.json`,
365
+ htmlFile,
366
+ pageDataFile,
367
+ pageDataStaticQueryHashes: cached?.staticQueryHashes,
368
+ filesExist: job.outputFiles === "any" || job.outputFiles === "listed" && item.previous !== void 0
369
+ });
370
+ taskChars += resultJson.length;
371
+ if (tasks.length >= RENDER_CHUNK || taskChars >= RENDER_CHUNK_CHARS) await renderTasks();
372
+ }
373
+ await renderTasks();
374
+ const end = clock();
375
+ track(timings.render, start, end, end - start - queryMs);
376
+ return out;
377
+ }
378
+ const reply = (id, result = {}) => port.postMessage({
379
+ type: "batch",
380
+ id,
381
+ buffered: false,
382
+ bytes: 0,
383
+ bufferedBytes,
384
+ heapRatio: ratio(),
385
+ timings,
386
+ queries: [],
387
+ queryErrors: [],
388
+ render: emptyResult(),
389
+ deferred: [],
390
+ sitePagesRead: sitePageNodesWereRead(),
391
+ ...result
392
+ });
393
+ const outputOf = (out) => ({
394
+ queries: out.queries,
395
+ queryErrors: out.errors,
396
+ deferred: out.deferred
397
+ });
398
+ async function handle(msg) {
399
+ if (msg.type === "query") {
400
+ const out = queryOutput();
401
+ const tQuery = clock();
402
+ const ran = Array.from({ length: msg.items.length });
403
+ const done = wasm && wasmModule ? await runWasm(wasm, wasmModule, msg.items, ran, out) : void 0;
404
+ let next = 0;
405
+ const runNext = async () => {
406
+ while (next < msg.items.length) {
407
+ const i = next++;
408
+ if (done?.has(i)) continue;
409
+ const item = msg.items[i];
410
+ if (item.resultHash !== void 0) {
411
+ ran[i] = {
412
+ page: item.page,
413
+ resultHash: item.resultHash,
414
+ previous: item.previous
415
+ };
416
+ continue;
417
+ }
418
+ const result = await runQuery(item.page, out);
419
+ publish();
420
+ ran[i] = result && {
421
+ ...result,
422
+ previous: item.previous
423
+ };
424
+ }
425
+ };
426
+ await Promise.all(Array.from({ length: Math.min(QUERY_CONCURRENCY, msg.items.length) }, runNext));
427
+ const items = ran.filter((item) => item !== void 0);
428
+ if (out.queries.length || out.deferred.length) track(timings.query, tQuery);
429
+ let bytes = 0;
430
+ for (const item of items) bytes += itemBytes(item);
431
+ if (job) {
432
+ readChars = 0;
433
+ const result = await render(items, out);
434
+ bytes += 2 * readChars;
435
+ checkHeap();
436
+ reply(msg.id, {
437
+ bytes,
438
+ ...outputOf(out),
439
+ render: result
440
+ });
441
+ return;
442
+ }
443
+ for (const item of items) {
444
+ buffered.set(item.page.path, item.resultJson === void 0 ? item : {
445
+ ...item,
446
+ page: {
447
+ ...item.page,
448
+ context: {}
449
+ }
450
+ });
451
+ bufferedBytes += itemBytes(item);
452
+ }
453
+ checkHeap();
454
+ reply(msg.id, {
455
+ buffered: true,
456
+ bytes,
457
+ ...outputOf(out)
458
+ });
459
+ return;
460
+ }
461
+ if (msg.type === "render") {
462
+ const tSetup = clock();
463
+ job = msg.job;
464
+ dirs = void 0;
465
+ try {
466
+ assets = new AssetResolver(job.manifest, job.root, job.base);
467
+ renderer = await createRenderer(job.renderer);
468
+ dirs = createDirectoryMaker(job.publicDir);
469
+ } catch (e) {
470
+ setupError = e instanceof Error ? e : new Error(String(e));
471
+ }
472
+ track(timings.render, tSetup);
473
+ reply(msg.id);
474
+ return;
475
+ }
476
+ if (msg.type === "flush") {
477
+ const items = [];
478
+ for (const pagePath of msg.paths) {
479
+ const item = buffered.get(pagePath);
480
+ if (!item) continue;
481
+ buffered.delete(pagePath);
482
+ bufferedBytes -= itemBytes(item);
483
+ items.push(item);
484
+ }
485
+ const out = queryOutput();
486
+ const result = await render(items, out);
487
+ checkHeap();
488
+ reply(msg.id, {
489
+ ...outputOf(out),
490
+ render: result
491
+ });
492
+ return;
493
+ }
494
+ if (msg.type === "finish") {
495
+ wasm?.detach();
496
+ persistCaches();
497
+ finishCaches();
498
+ if (guard.releases) reporter.verbose(`query worker ${data.workerId} dropped its caches ${guard.releases} time(s): its heap was full${budget() ? ` (budget ${data.heapBudgetMb && data.heapBudgetMb !== budget() ? `${data.heapBudgetMb} → ` : ""}${budget()} MB)` : ""}`);
499
+ port.postMessage({
500
+ type: "finished",
501
+ id: msg.id,
502
+ timings
503
+ });
504
+ }
505
+ }
506
+ let queue = Promise.resolve();
507
+ port.on("message", (msg) => {
508
+ if (msg.type === "job-done" || msg.type === "job-failed") return;
509
+ queue = queue.then(() => handle(msg).catch((e) => {
510
+ const error = {
511
+ pagePath: "(worker)",
512
+ message: e?.message ?? String(e),
513
+ stack: e?.stack
514
+ };
515
+ reply(msg.id, { render: {
516
+ ...emptyResult(),
517
+ errors: [error]
518
+ } });
519
+ if (msg.type === "finish") port.postMessage({
520
+ type: "finished",
521
+ id: msg.id,
522
+ timings
523
+ });
524
+ }));
525
+ });
526
+ publish();
527
+ port.postMessage({ type: "ready" });
528
+ } catch (e) {
529
+ port.postMessage({
530
+ type: "error",
531
+ error: e?.stack ?? String(e)
532
+ });
533
+ }
534
+ }
535
+ if (!isMainThread && parentPort && workerData?.__goatlyQueryWorker) main(workerData);
536
+ export {};