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,406 @@
1
+ import { preparedDocument } from "../query/graphql-runner.js";
2
+ import reporter from "../reporter.js";
3
+ import { lowerQuery } from "./lower.js";
4
+ import { WasmState, countResults, pageVars, recordMismatch, resultJsonOf, sameResult } from "./runner.js";
5
+ import path from "node:path";
6
+ import fs from "node:fs";
7
+ // src/node/wasm-data/host.ts
8
+ /**
9
+ * The WASM data side of the page queries (docs/architecture-wasm-data.md): page queries run in
10
+ * goatly-data.wasm (the package @goatly/wasm) – in the query workers and in the main thread –
11
+ * and in JS where it can't run them.
12
+ *
13
+ * Per build (or per run of query workers): the page queries are lowered to plans (lower.ts); the
14
+ * node store is built in one shared WebAssembly memory from the logfile datastore's segment files
15
+ * and sealed; pages then run in
16
+ * batches, one call per batch, which returns each page's `data` JSON and dependencies (byte for
17
+ * byte what the JS path writes). The JS path stays for everything else:
18
+ * queries the lowering does not support (custom resolvers, SitePage, …), pages WASM answers with
19
+ * a fallback, datastores without a store image, runtimes without shared WebAssembly memory, or a
20
+ * missing module (a warning).
21
+ *
22
+ * `GOATLY_WASM_DATA=0` runs every page query in JS. `=verify` runs the supported pages in
23
+ * both, uses the JS result and writes differences to `.cache/wasm-data-mismatch.jsonl`
24
+ * (`GOATLY_WASM_DATA_STRICT=1`: the build fails on any). `GOATLY_WASM_DATA_FILE`:
25
+ * another goatly-data.wasm.
26
+ */
27
+ /** GOATLY_WASM_DATA: on unless `0` (`false`, `off`); `verify` runs both paths */
28
+ function wasmDataMode(env = process.env) {
29
+ const value = env.GOATLY_WASM_DATA?.trim().toLowerCase();
30
+ if (value === "0" || value === "false" || value === "off") return "off";
31
+ return value === "verify" ? "verify" : "on";
32
+ }
33
+ const runtimes = /* @__PURE__ */ new Map();
34
+ const warned = /* @__PURE__ */ new Set();
35
+ /** the package and its compiled module (once per process and file) */
36
+ function loadRuntime(env) {
37
+ const key = env.GOATLY_WASM_DATA_FILE || "";
38
+ let runtime = runtimes.get(key);
39
+ if (!runtime) {
40
+ runtime = (async () => {
41
+ let lib;
42
+ try {
43
+ lib = await import("@goatly/wasm");
44
+ } catch (e) {
45
+ return {
46
+ unavailable: `the package @goatly/wasm could not be loaded (${e?.message ?? e})`,
47
+ warn: true
48
+ };
49
+ }
50
+ if (!lib.wasmSupported()) return {
51
+ unavailable: "this runtime has no shared WebAssembly memory",
52
+ warn: false
53
+ };
54
+ const file = key || lib.wasmFile;
55
+ try {
56
+ const module = lib.loadDataModule(file);
57
+ if (!module) return {
58
+ unavailable: `${file} is missing (it is built with Rust: pnpm --filter @goatly/wasm build)`,
59
+ warn: true
60
+ };
61
+ return {
62
+ lib,
63
+ module
64
+ };
65
+ } catch (e) {
66
+ return {
67
+ unavailable: `${file} could not be compiled: ${e?.message ?? e}`,
68
+ warn: true
69
+ };
70
+ }
71
+ })();
72
+ runtimes.set(key, runtime);
73
+ }
74
+ return runtime;
75
+ }
76
+ function unavailable(runtime) {
77
+ const message = `Page queries run in JS: ${runtime.unavailable}`;
78
+ if (runtime.warn && !warned.has(message)) {
79
+ warned.add(message);
80
+ reporter.warn(message);
81
+ } else reporter.verbose(`wasm-data: not used: ${runtime.unavailable}`);
82
+ }
83
+ function lowerQueries(schema, queryTexts) {
84
+ const plans = {
85
+ irs: [],
86
+ vars: [],
87
+ reasons: []
88
+ };
89
+ for (const query of queryTexts) {
90
+ const prepared = preparedDocument(query, schema);
91
+ const lowered = prepared.errors.length ? { unsupported: "the query has errors" } : lowerQuery(schema, prepared.document);
92
+ if ("ir" in lowered) {
93
+ plans.irs.push(lowered.ir);
94
+ plans.vars.push(lowered.vars);
95
+ plans.reasons.push("");
96
+ } else {
97
+ plans.irs.push(void 0);
98
+ plans.vars.push(null);
99
+ plans.reasons.push(lowered.unsupported);
100
+ }
101
+ }
102
+ return plans;
103
+ }
104
+ /** each query text once, and each component's index in them */
105
+ function indexQueries(componentQueries) {
106
+ const queryTexts = [];
107
+ const indexes = /* @__PURE__ */ new Map();
108
+ const components = {};
109
+ for (const [componentPath, query] of Object.entries(componentQueries)) {
110
+ let index = indexes.get(query);
111
+ if (index === void 0) indexes.set(query, index = queryTexts.push(query) - 1);
112
+ components[componentPath] = index;
113
+ }
114
+ return {
115
+ queryTexts,
116
+ components
117
+ };
118
+ }
119
+ /** logs why queries run in JS (verbose), by the components that use them */
120
+ function logReasons(reasons, components) {
121
+ reasons.forEach((reason, i) => {
122
+ if (!reason) return;
123
+ const names = Object.entries(components).filter(([, index]) => index === i).map(([c]) => path.basename(c));
124
+ reporter.verbose(`wasm-data: ${names.join(", ")}: in JS: ${reason}`);
125
+ });
126
+ }
127
+ /** the host for an image: its files opened now (undefined: a warning, the queries run in JS) */
128
+ function openHost(lib, module, image, where) {
129
+ try {
130
+ const host = lib.createDataHost({
131
+ module,
132
+ segments: image.segments
133
+ });
134
+ const bytes = image.segments.reduce((sum, s) => sum + s.length, 0);
135
+ reporter.verbose(`wasm-data: reading ${image.segments.length} segment file${image.segments.length === 1 ? "" : "s"} (${(bytes / 1048576).toFixed(0)} MB, ${where})`);
136
+ return host;
137
+ } catch (e) {
138
+ reporter.warn(`Page queries run in JS: goatly-data.wasm failed: ${e?.message ?? e}`);
139
+ return;
140
+ }
141
+ }
142
+ /** builds and seals the store: the plan ids (-1: rejected), false when none was accepted */
143
+ function buildStore(host, image, plans, components, where) {
144
+ try {
145
+ const res = host.build({
146
+ types: image.types,
147
+ structures: image.structures,
148
+ plans: plans.irs
149
+ });
150
+ logReasons(res.reasons.map((r, i) => plans.irs[i] ? r : plans.reasons[i]), components);
151
+ const accepted = res.planIds.filter((id) => id >= 0).length;
152
+ reporter.verbose(`wasm-data: store of ${res.stats.nodes} nodes built in ${(res.ms / 1e3).toFixed(2)}s (${where}), ${(host.committedBytes() / 1048576).toFixed(0)} MB shared memory, ${accepted} of ${plans.irs.length} queries in WASM`);
153
+ return accepted > 0 && res.planIds;
154
+ } catch (e) {
155
+ reporter.warn(`The WASM data side could not build its store – the page queries run in JS: ${e?.message ?? e}`);
156
+ return false;
157
+ }
158
+ }
159
+ function summaryOf(lib, state, where, mode) {
160
+ const ok = Atomics.load(state, WasmState.OK);
161
+ const fallback = Atomics.load(state, WasmState.FALLBACK);
162
+ const traps = Atomics.load(state, WasmState.TRAPS);
163
+ const s = Atomics.load(state, WasmState.MICROS) / 1e6;
164
+ const why = lib.REASONS.map((r, i) => [r, Atomics.load(state, WasmState.REASONS + i)]).filter(([, n]) => n > 0).map(([r, n]) => `${r}: ${n}`);
165
+ return `wasm-data: ${ok} pages in WASM (${where}, ${s.toFixed(2)}s), ${fallback} fallbacks${why.length ? ` (${why.join(", ")})` : ""}${traps ? `, ${traps} trapped` : ""}${mode === "verify" ? `, ${Atomics.load(state, WasmState.MISMATCH)} mismatches` : ""}`;
166
+ }
167
+ const mismatchFileOf = (cacheDir) => path.join(cacheDir, "wasm-data-mismatch.jsonl");
168
+ /**
169
+ * At the start of a build: removes the previous build's mismatches (verify mode). Once per build,
170
+ * not per run of WASM page queries: a build can have several, and each appends to the file.
171
+ */
172
+ function resetWasmMismatches(cacheDir, env = process.env) {
173
+ if (wasmDataMode(env) === "verify") fs.rmSync(mismatchFileOf(cacheDir), { force: true });
174
+ }
175
+ /** the end of a run: its line in the log, and verify mode's mismatches */
176
+ function finish(summary, mode, mismatches, file) {
177
+ reporter.info(summary);
178
+ if (mode !== "verify" || !mismatches) return;
179
+ const message = `wasm-data: ${mismatches} page(s) differ between WASM and JS – see ${file}`;
180
+ if (process.env.GOATLY_WASM_DATA_STRICT === "1") reporter.panic(message);
181
+ reporter.warn(message);
182
+ }
183
+ /** the mode, module and plans when some page to run has a lowered query (else undefined) */
184
+ async function prepare(input, image) {
185
+ const env = input.env ?? process.env;
186
+ const mode = wasmDataMode(env);
187
+ if (mode === "off") return void 0;
188
+ const source = input.ds;
189
+ if (typeof source[image] !== "function") {
190
+ reporter.verbose("wasm-data: not used: the datastore has no image of its nodes (only the logfile store has one)");
191
+ return;
192
+ }
193
+ const plans = lowerQueries(input.schema, input.queryTexts);
194
+ let eligible = 0;
195
+ for (const c of input.components) {
196
+ const index = input.componentQueries[c];
197
+ if (index !== void 0 && plans.irs[index]) eligible++;
198
+ }
199
+ if (!eligible) {
200
+ logReasons(plans.reasons, input.componentQueries);
201
+ return;
202
+ }
203
+ const runtime = await loadRuntime(env);
204
+ if ("unavailable" in runtime) return unavailable(runtime);
205
+ return {
206
+ mode,
207
+ plans,
208
+ mismatchFile: mismatchFileOf(input.cacheDir),
209
+ source,
210
+ ...runtime
211
+ };
212
+ }
213
+ /**
214
+ * The WASM data side of page queries in the main thread (small builds, incremental builds, pages
215
+ * the query workers left): undefined when it is off or none of `components` has a query it
216
+ * supports. The store is built from the datastore's nodes as they are when the first page runs.
217
+ */
218
+ async function prepareMainThreadWasm(input) {
219
+ const { queryTexts, components } = indexQueries(input.componentQueries);
220
+ const prepared = await prepare({
221
+ ...input,
222
+ queryTexts,
223
+ componentQueries: components
224
+ }, "liveImage");
225
+ if (!prepared) return void 0;
226
+ const { mode, plans, mismatchFile, lib, module, source } = prepared;
227
+ const state = new Int32Array(WasmState.PLANS);
228
+ /** undefined: not built yet; null: not available */
229
+ let store;
230
+ const ensureStore = () => {
231
+ if (store !== void 0) return store;
232
+ store = null;
233
+ const image = source.liveImage();
234
+ if (!image) {
235
+ reporter.verbose("wasm-data: not used: the datastore has no image of its nodes");
236
+ return store;
237
+ }
238
+ const host = openHost(lib, module, image, "main thread");
239
+ if (!host) return store;
240
+ const planIds = buildStore(host, image, plans, components, "main thread");
241
+ if (planIds) store = {
242
+ host,
243
+ planIds
244
+ };
245
+ else host.close();
246
+ return store;
247
+ };
248
+ return {
249
+ mode,
250
+ run(pages) {
251
+ const out = /* @__PURE__ */ new Map();
252
+ const batch = [];
253
+ for (const page of pages) {
254
+ const index = components[page.componentPath];
255
+ if (index === void 0 || !plans.irs[index]) continue;
256
+ const built = ensureStore();
257
+ if (!built) return out;
258
+ const planId = built.planIds[index];
259
+ const vars = planId >= 0 ? pageVars(page, plans.vars[index]) : void 0;
260
+ if (vars !== void 0) batch.push({
261
+ page,
262
+ item: {
263
+ planId,
264
+ vars
265
+ }
266
+ });
267
+ }
268
+ for (let from = 0; from < batch.length && store; from += 64) {
269
+ const chunk = batch.slice(from, from + 64);
270
+ const t = performance.now();
271
+ let results;
272
+ try {
273
+ results = store.host.runBatch(chunk.map((p) => p.item));
274
+ } catch (e) {
275
+ Atomics.add(state, WasmState.TRAPS, 1);
276
+ reporter.warn(`The WASM data side failed – the page queries run in JS: ${e?.message ?? e}`);
277
+ store.host.close();
278
+ store = null;
279
+ break;
280
+ }
281
+ countResults(state, results, lib.REASONS, (performance.now() - t) * 1e3);
282
+ results.forEach((r, k) => {
283
+ if (r.status !== 0) return;
284
+ const { page } = chunk[k];
285
+ out.set(page.path, {
286
+ resultJson: resultJsonOf(page, r.data),
287
+ n: r.n,
288
+ c: r.c
289
+ });
290
+ });
291
+ }
292
+ return out;
293
+ },
294
+ compare(page, wasm, js) {
295
+ if (!sameResult(wasm, js)) recordMismatch(state, mismatchFile, {
296
+ path: page.path,
297
+ wasm,
298
+ js
299
+ });
300
+ },
301
+ finish() {
302
+ store?.host.close();
303
+ if (Atomics.load(state, WasmState.OK) + Atomics.load(state, WasmState.FALLBACK) === 0) return;
304
+ finish(summaryOf(lib, state, "main thread", mode), mode, Atomics.load(state, WasmState.MISMATCH), mismatchFile);
305
+ }
306
+ };
307
+ }
308
+ /** workers (and their replacements) of a run that get the WASM data side */
309
+ const GATES = 256;
310
+ /** how often a worker's termination checks whether it is out of its call */
311
+ const STOP_POLL_MS = 5;
312
+ /**
313
+ * The WASM data side of a run of query workers, or undefined (off, or no page to run has a query
314
+ * it supports). The workers read the persisted nodes: the store is built from the same image
315
+ * (`build()`, while they start).
316
+ */
317
+ async function prepareWorkerWasm(input) {
318
+ const prepared = await prepare(input, "persistedImage");
319
+ if (!prepared) return void 0;
320
+ const { mode, plans, mismatchFile, lib, module, source } = prepared;
321
+ const image = source.persistedImage();
322
+ if (!image) {
323
+ reporter.verbose("wasm-data: not used: the datastore's nodes are not persisted");
324
+ return;
325
+ }
326
+ const host = openHost(lib, module, image, "query workers");
327
+ if (!host) return void 0;
328
+ const stateBuffer = new SharedArrayBuffer((WasmState.PLANS + input.queryTexts.length) * 4);
329
+ const state = new Int32Array(stateBuffer);
330
+ for (let i = 0; i < input.queryTexts.length; i++) state[WasmState.PLANS + i] = -1;
331
+ let closed = false;
332
+ const gatesBuffer = new SharedArrayBuffer(GATES * 4);
333
+ const gates = new Int32Array(gatesBuffer);
334
+ let nextGate = 0;
335
+ /** a worker exited (or was terminated) in a call: its allocator lock may be held for good */
336
+ let poisoned = false;
337
+ let givenUp;
338
+ /** the gates of the workers that exited (nothing to wait for) */
339
+ const exited = /* @__PURE__ */ new Set();
340
+ const poison = (why) => {
341
+ if (poisoned) return;
342
+ poisoned = true;
343
+ Atomics.store(state, WasmState.STATUS, 2);
344
+ reporter.warn(`The WASM data side is not used any more – the page queries run in JS: ${why}`);
345
+ givenUp?.();
346
+ };
347
+ const close = () => {
348
+ if (closed) return;
349
+ closed = true;
350
+ host.close();
351
+ };
352
+ return {
353
+ mode,
354
+ workerOptions() {
355
+ if (poisoned || closed || nextGate >= GATES) return void 0;
356
+ try {
357
+ return {
358
+ data: host.workerData(),
359
+ state: stateBuffer,
360
+ planVars: plans.vars,
361
+ verify: mode === "verify",
362
+ mismatchFile,
363
+ gates: gatesBuffer,
364
+ gate: nextGate++
365
+ };
366
+ } catch {
367
+ return;
368
+ }
369
+ },
370
+ stopWorker(options) {
371
+ Atomics.or(gates, options.gate, 2);
372
+ const free = () => poisoned || exited.has(options.gate) || !(Atomics.load(gates, options.gate) & 1);
373
+ if (free()) return void 0;
374
+ return new Promise((resolve) => {
375
+ const check = () => free() ? resolve() : void setTimeout(check, STOP_POLL_MS);
376
+ check();
377
+ });
378
+ },
379
+ workerExited(options) {
380
+ exited.add(options.gate);
381
+ if (Atomics.or(gates, options.gate, 2) & 1) poison("a query worker exited during a call");
382
+ else if (!poisoned) host.releaseWorker(options.data);
383
+ },
384
+ covers(componentPath) {
385
+ const index = input.componentQueries[componentPath];
386
+ if (index === void 0) return true;
387
+ const status = Atomics.load(state, WasmState.STATUS);
388
+ return mode !== "verify" && !poisoned && !!plans.irs[index] && (status === 0 || status === 1 && state[WasmState.PLANS + index] >= 0);
389
+ },
390
+ onGiveUp(fn) {
391
+ givenUp = fn;
392
+ },
393
+ build() {
394
+ const planIds = buildStore(host, image, plans, input.componentQueries, "query workers");
395
+ if (planIds) planIds.forEach((id, i) => state[WasmState.PLANS + i] = id);
396
+ Atomics.store(state, WasmState.STATUS, planIds ? 1 : 2);
397
+ Atomics.notify(state, WasmState.STATUS);
398
+ },
399
+ finish() {
400
+ close();
401
+ finish(summaryOf(lib, state, "query workers", mode), mode, Atomics.load(state, WasmState.MISMATCH), mismatchFile);
402
+ },
403
+ close
404
+ };
405
+ }
406
+ export { indexQueries, prepareMainThreadWasm, prepareWorkerWasm, resetWasmMismatches, wasmDataMode };