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.
- package/README.md +853 -1
- package/bin/goatly.js +91 -0
- package/dist/cli/index.js +234 -0
- package/dist/compat/gatsby-node-entry.js +16 -0
- package/dist/compat/gatsby-package.json +6 -0
- package/dist/compat/md5-file.js +47 -0
- package/dist/compat-apis.json +72 -0
- package/dist/compat-apis.json.js +62 -0
- package/dist/graphql.js +3 -0
- package/dist/node/actions/index.js +619 -0
- package/dist/node/actions/job-store.js +180 -0
- package/dist/node/actions/jobs.js +174 -0
- package/dist/node/api-runner.js +258 -0
- package/dist/node/bootstrap.js +539 -0
- package/dist/node/build/assets.js +110 -0
- package/dist/node/build/incremental.js +208 -0
- package/dist/node/build/index.js +752 -0
- package/dist/node/build/memory-governor.js +448 -0
- package/dist/node/build/output-dirs.js +70 -0
- package/dist/node/build/page-data.js +40 -0
- package/dist/node/build/page-files.js +54 -0
- package/dist/node/build/partitioned-state.js +258 -0
- package/dist/node/build/query-worker.js +536 -0
- package/dist/node/build/query-workers.js +832 -0
- package/dist/node/build/render-worker.js +131 -0
- package/dist/node/build/state.js +24 -0
- package/dist/node/build/timing-breakdown.js +155 -0
- package/dist/node/build/worker-pool.js +236 -0
- package/dist/node/cache-layout.js +99 -0
- package/dist/node/cache.js +1430 -0
- package/dist/node/compat/chokidar-shim.js +148 -0
- package/dist/node/compat/core-utils-lmdb.js +145 -0
- package/dist/node/compat/create-node-id-shim.js +1 -0
- package/dist/node/compat/module-hooks.js +245 -0
- package/dist/node/compat/redux-shim.js +1 -0
- package/dist/node/config/index.js +162 -0
- package/dist/node/config/not-found-pages.js +95 -0
- package/dist/node/datastore/codec.js +144 -0
- package/dist/node/datastore/index.js +127 -0
- package/dist/node/datastore/logfile/cache.js +89 -0
- package/dist/node/datastore/logfile/index.js +1329 -0
- package/dist/node/datastore/logfile/record.js +71 -0
- package/dist/node/datastore/types.js +1 -0
- package/dist/node/develop/express-compat.js +207 -0
- package/dist/node/develop/graphiql.js +22 -0
- package/dist/node/develop/hydration-report.js +41 -0
- package/dist/node/develop/index.js +618 -0
- package/dist/node/develop/local-url.js +10 -0
- package/dist/node/develop/ssr-runner.js +66 -0
- package/dist/node/gql.js +5 -0
- package/dist/node/index.js +15 -0
- package/dist/node/info.js +270 -0
- package/dist/node/internal-plugins/data-bridge.js +196 -0
- package/dist/node/internal-plugins/page-creator.js +318 -0
- package/dist/node/loader/import-module.js +160 -0
- package/dist/node/node-helpers.js +66 -0
- package/dist/node/not-found-pages.js +220 -0
- package/dist/node/plugins/api-list.js +12 -0
- package/dist/node/plugins/load-plugins.js +427 -0
- package/dist/node/plugins/resolve-plugin.js +79 -0
- package/dist/node/plugins/static-exports.js +64 -0
- package/dist/node/query/compile.js +326 -0
- package/dist/node/query/dependencies.js +45 -0
- package/dist/node/query/execute.js +417 -0
- package/dist/node/query/extract.js +372 -0
- package/dist/node/query/gql-tada-introspection.js +124 -0
- package/dist/node/query/graphql-env.js +231 -0
- package/dist/node/query/graphql-runner.js +79 -0
- package/dist/node/redux/actions.js +1 -0
- package/dist/node/redux/index.js +133 -0
- package/dist/node/redux/node-changes.js +128 -0
- package/dist/node/redux/reducers.js +193 -0
- package/dist/node/redux/state.js +71 -0
- package/dist/node/renderer.js +124 -0
- package/dist/node/reporter-transports.js +259 -0
- package/dist/node/reporter.js +497 -0
- package/dist/node/schema/date.js +539 -0
- package/dist/node/schema/extensions.js +315 -0
- package/dist/node/schema/index.js +542 -0
- package/dist/node/schema/infer.js +388 -0
- package/dist/node/schema/inline-objects.js +128 -0
- package/dist/node/schema/naming.js +20 -0
- package/dist/node/schema/node-model.js +207 -0
- package/dist/node/schema/query-engine.js +1808 -0
- package/dist/node/schema/resolver-kinds.js +7 -0
- package/dist/node/schema/resolvers.js +273 -0
- package/dist/node/schema/type-builders.js +45 -0
- package/dist/node/schema/types.js +241 -0
- package/dist/node/serve.js +90 -0
- package/dist/node/site-page-nodes.js +277 -0
- package/dist/node/types.js +1 -0
- package/dist/node/utils/content-digest.js +107 -0
- package/dist/node/utils/create-node-id.js +51 -0
- package/dist/node/utils/env.js +24 -0
- package/dist/node/utils/fs-retry.js +74 -0
- package/dist/node/utils/memory-signals.js +410 -0
- package/dist/node/utils/memory.js +400 -0
- package/dist/node/utils/murmurhash.js +32 -0
- package/dist/node/utils/parser.js +33 -0
- package/dist/node/utils/partition-hash.js +19 -0
- package/dist/node/utils/paths.js +122 -0
- package/dist/node/utils/resolver.js +48 -0
- package/dist/node/utils/runtime.js +5 -0
- package/dist/node/utils/serializable.js +41 -0
- package/dist/node/utils/strings.js +41 -0
- package/dist/node/vite/config.js +289 -0
- package/dist/node/vite/paths.js +12 -0
- package/dist/node/vite/plugin-deps.js +232 -0
- package/dist/node/vite/plugin.js +281 -0
- package/dist/node/vite/react-compiler.js +362 -0
- package/dist/node/vite/source-files.js +83 -0
- package/dist/node/vite/static-image.js +136 -0
- package/dist/node/vite/styled-components.js +73 -0
- package/dist/node/vite/transforms.js +299 -0
- package/dist/node/wasm-data/host.js +406 -0
- package/dist/node/wasm-data/lower.js +406 -0
- package/dist/node/wasm-data/runner.js +79 -0
- package/dist/node/wasm-data/worker.js +95 -0
- package/dist/reporter.js +5 -0
- package/dist/runtime/api-runner.js +81 -0
- package/dist/runtime/app.js +256 -0
- package/dist/runtime/client-entry.js +4 -0
- package/dist/runtime/client.js +383 -0
- package/dist/runtime/default-html.js +31 -0
- package/dist/runtime/head-markup.js +100 -0
- package/dist/runtime/head-sync.js +101 -0
- package/dist/runtime/head-tags.js +45 -0
- package/dist/runtime/hydration-report.js +111 -0
- package/dist/runtime/index.js +12 -0
- package/dist/runtime/link.js +293 -0
- package/dist/runtime/loader.js +449 -0
- package/dist/runtime/not-found.js +61 -0
- package/dist/runtime/page-renderer.js +35 -0
- package/dist/runtime/preamble.js +47 -0
- package/dist/runtime/react-compat.js +14 -0
- package/dist/runtime/renderer-shared.js +10 -0
- package/dist/runtime/renderers/react-client.js +14 -0
- package/dist/runtime/renderers/react-server.js +99 -0
- package/dist/runtime/renderers/react.js +17 -0
- package/dist/runtime/renderers/types.js +1 -0
- package/dist/runtime/root-error-handlers.js +29 -0
- package/dist/runtime/router/history.js +132 -0
- package/dist/runtime/router/index.js +240 -0
- package/dist/runtime/router/utils.js +118 -0
- package/dist/runtime/script.js +110 -0
- package/dist/runtime/scroll.js +40 -0
- package/dist/runtime/slice.js +11 -0
- package/dist/runtime/ssr.js +240 -0
- package/dist/runtime/static-query.js +47 -0
- package/dist/utils.js +4 -0
- package/package.json +105 -3
- package/types/graphql-tada.d.ts +223 -0
- package/types/graphql.d.ts +2 -0
- package/types/index.d.ts +2287 -0
- package/types/node.d.ts +380 -0
- package/types/reporter.d.ts +187 -0
- package/types/router.d.ts +102 -0
- package/types/vendor/gql-tada.d.ts +2529 -0
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
import { parseVmStatAvailableMb, sampleMemoryOnce } from "./memory-signals.js";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import v8 from "node:v8";
|
|
4
|
+
import vm from "node:vm";
|
|
5
|
+
// src/node/utils/memory.ts
|
|
6
|
+
const MB = 1048576;
|
|
7
|
+
/**
|
|
8
|
+
* Memory (MB) the process can still use now (see sampleMemoryOnce): free + reclaimable memory, the
|
|
9
|
+
* lowest of the system's and every cgroup level's headroom on Linux (other processes in a container
|
|
10
|
+
* count, its clean page cache is free), Activity Monitor's "available" on macOS, os.freemem()
|
|
11
|
+
* elsewhere.
|
|
12
|
+
*/
|
|
13
|
+
function availableMemoryMb() {
|
|
14
|
+
return Math.max(0, Math.floor(sampleMemoryOnce().availMb));
|
|
15
|
+
}
|
|
16
|
+
const isBun = typeof process.versions.bun === "string";
|
|
17
|
+
const RUNTIME = isBun ? "bun" : "node";
|
|
18
|
+
/** head room for the main thread (rendering, page-data, Vite) when workers are planned */
|
|
19
|
+
const MAIN_RESERVE_MB = 1024;
|
|
20
|
+
/** estimate for one render worker: the SSR bundle and one batch (measured 15–30 MB) – generous */
|
|
21
|
+
const RENDER_WORKER_MB = 256;
|
|
22
|
+
/** the smallest heap limit a replacement worker is started with (MB of free memory kept) */
|
|
23
|
+
const REPLACEMENT_RESERVE_MB = 512;
|
|
24
|
+
/** the smallest heap budget of a worker thread on Bun (with little free memory) */
|
|
25
|
+
const MIN_BUDGET_MB = 256;
|
|
26
|
+
/** memory (MB) of the machine, or of the container (cgroup limit) when that is smaller */
|
|
27
|
+
function totalMemoryMb() {
|
|
28
|
+
const total = os.totalmem();
|
|
29
|
+
const constrained = typeof process.constrainedMemory === "function" ? process.constrainedMemory() : 0;
|
|
30
|
+
return Math.floor((constrained > 0 && constrained < total ? constrained : total) / MB);
|
|
31
|
+
}
|
|
32
|
+
/** `--max-old-space-size=` as V8 accepts it (`-` or `_` between the words) */
|
|
33
|
+
const MAX_OLD_SPACE_SIZE = /^--max[-_]old[-_]space[-_]size=/;
|
|
34
|
+
/** `--max-old-space-size-percentage=` (Node 22.20+: a share of the memory, wins over the size) */
|
|
35
|
+
const MAX_OLD_SPACE_SIZE_PERCENTAGE = /^--max[-_]old[-_]space[-_]size[-_]percentage=/;
|
|
36
|
+
const unquote = (value) => value.replace(/^"(.*)"$/, "$1");
|
|
37
|
+
/** the value (MB) of the last `--max-old-space-size=<MB>` in `args`, 0: none */
|
|
38
|
+
function maxOldSpaceSizeArg(args) {
|
|
39
|
+
let value = 0;
|
|
40
|
+
for (const arg of args) if (MAX_OLD_SPACE_SIZE.test(arg)) value = Math.round(Number(unquote(arg.slice(arg.indexOf("=") + 1)))) || 0;
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
const nodeOptions = (env) => (env.NODE_OPTIONS ?? "").split(/\s+/).filter(Boolean).map(unquote);
|
|
44
|
+
/**
|
|
45
|
+
* The old generation limit (MB) `--max-old-space-size-percentage=<P>` gives every thread: P% of the
|
|
46
|
+
* memory (or of the container's limit), computed like Node does
|
|
47
|
+
*/
|
|
48
|
+
function percentageLimitMb(args) {
|
|
49
|
+
let percentage = 0;
|
|
50
|
+
for (const arg of args) if (MAX_OLD_SPACE_SIZE_PERCENTAGE.test(arg)) percentage = Number(unquote(arg.slice(arg.indexOf("=") + 1))) || 0;
|
|
51
|
+
const total = os.totalmem();
|
|
52
|
+
const constrained = typeof process.constrainedMemory === "function" ? process.constrainedMemory() : 0;
|
|
53
|
+
return Math.floor((constrained > 0 && constrained < total ? constrained : total) * percentage / 100 / MB);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The heap limit (MB) the user chose for Node: `--max-old-space-size` in NODE_OPTIONS or the node
|
|
57
|
+
* arguments (the latter win), or GOATLY_HEAP_LIMIT=<MB>. The `--max-old-space-size` the bin
|
|
58
|
+
* sets when it restarts Node (GOATLY_RESPAWNED) is not one: the bin only restarts Node when
|
|
59
|
+
* the user chose no limit. On Bun only GOATLY_HEAP_LIMIT counts: Bun ignores V8's flags,
|
|
60
|
+
* also in NODE_OPTIONS.
|
|
61
|
+
*/
|
|
62
|
+
function userHeapLimit(env = process.env, execArgv = process.execArgv, runtime = RUNTIME) {
|
|
63
|
+
if (runtime === "node" && !env.GOATLY_RESPAWNED) {
|
|
64
|
+
const args = [...nodeOptions(env), ...execArgv];
|
|
65
|
+
const share = percentageLimitMb(args);
|
|
66
|
+
if (share > 0) return {
|
|
67
|
+
mb: share,
|
|
68
|
+
source: "--max-old-space-size-percentage"
|
|
69
|
+
};
|
|
70
|
+
const flag = maxOldSpaceSizeArg(args);
|
|
71
|
+
if (flag > 0) return {
|
|
72
|
+
mb: flag,
|
|
73
|
+
source: "--max-old-space-size"
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
const setting = Number(env.GOATLY_HEAP_LIMIT);
|
|
77
|
+
return setting > 0 ? {
|
|
78
|
+
mb: Math.round(setting),
|
|
79
|
+
source: "GOATLY_HEAP_LIMIT"
|
|
80
|
+
} : void 0;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The heap limit (MB) Node gives a thread on this machine when nobody chose one: half the memory, up
|
|
84
|
+
* to about 2 GB (4 GB with 15 GB of memory or more; V8 12). The bin measures it before it restarts
|
|
85
|
+
* Node with a larger limit (GOATLY_NODE_HEAP_MB): afterwards no thread can see it.
|
|
86
|
+
*/
|
|
87
|
+
function nodeDefaultHeapMb(env = process.env, execArgv = process.execArgv) {
|
|
88
|
+
const measured = Number(env.GOATLY_NODE_HEAP_MB);
|
|
89
|
+
if (measured > 0) return Math.round(measured);
|
|
90
|
+
if (!env.GOATLY_RESPAWNED && !userHeapLimit({
|
|
91
|
+
...env,
|
|
92
|
+
GOATLY_HEAP_LIMIT: ""
|
|
93
|
+
}, execArgv)) return Math.round(v8.getHeapStatistics().heap_size_limit / MB);
|
|
94
|
+
const total = totalMemoryMb();
|
|
95
|
+
return Math.min(Math.floor(total / 2), total >= 15360 ? 4096 : 2048) + 48;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The heap limit of `workers` worker threads, in this order:
|
|
99
|
+
* 1. GOATLY_WORKER_HEAP_MB
|
|
100
|
+
* 2. the limit the user chose for Node (see userHeapLimit) – as in plain Node, it applies to every
|
|
101
|
+
* thread
|
|
102
|
+
* 3. otherwise an equal share of the free memory among the workers and the main thread, never less
|
|
103
|
+
* than Node's own default (or `minMb`, e.g. for workers that copy the data layer).
|
|
104
|
+
*
|
|
105
|
+
* A limit is a ceiling, not memory set aside: with `--heap-growing-percent` (configureBuildHeap) a
|
|
106
|
+
* heap stays close to its live size whatever the limit, so a generous limit costs no memory – but a
|
|
107
|
+
* low one fails builds V8 would complete. Without it (GOATLY_HEAP_GROWING_PERCENT=0, or
|
|
108
|
+
* GOATLY_HEAP_LIMIT=off) workers get Node's default.
|
|
109
|
+
* A replacement worker gets twice the limit, then the main thread's (both at most the memory that is
|
|
110
|
+
* free when it starts) unless the user chose a limit.
|
|
111
|
+
*
|
|
112
|
+
* On Bun these are budgets (`soft`, see WorkerHeap): GOATLY_WORKER_HEAP_MB,
|
|
113
|
+
* GOATLY_HEAP_LIMIT, or else the share of the free memory, without Node's default as the
|
|
114
|
+
* floor – a budget fails nothing, and the budgets of workers that stay within them fit into the free
|
|
115
|
+
* memory together, the main thread's reserve left (unless `minMb`, the estimated heap of a worker
|
|
116
|
+
* that copies the data layer, is larger). V8's growth settings don't apply.
|
|
117
|
+
*/
|
|
118
|
+
function planWorkerHeap(options) {
|
|
119
|
+
const env = options.env ?? process.env;
|
|
120
|
+
const execArgv = options.execArgv ?? process.execArgv;
|
|
121
|
+
const runtime = options.runtime ?? RUNTIME;
|
|
122
|
+
const soft = runtime === "bun";
|
|
123
|
+
const fixed = (mb, source, budgetMb) => ({
|
|
124
|
+
limitMb: mb,
|
|
125
|
+
ladder: [
|
|
126
|
+
mb,
|
|
127
|
+
mb,
|
|
128
|
+
mb
|
|
129
|
+
],
|
|
130
|
+
source,
|
|
131
|
+
...soft ? { soft: true } : {},
|
|
132
|
+
...budgetMb !== void 0 && budgetMb < mb ? { budgetMb } : {}
|
|
133
|
+
});
|
|
134
|
+
let available;
|
|
135
|
+
/** an equal share of the free memory among the workers and the main thread (its reserve left) */
|
|
136
|
+
const share = () => {
|
|
137
|
+
available ??= options.availableMb ?? availableMemoryMb();
|
|
138
|
+
const mb = Math.floor((available - MAIN_RESERVE_MB) / (Math.max(1, options.workers) + 1));
|
|
139
|
+
return Math.max(MIN_BUDGET_MB, Math.ceil(options.minMb ?? 0), mb);
|
|
140
|
+
};
|
|
141
|
+
const override = Number(env.GOATLY_WORKER_HEAP_MB);
|
|
142
|
+
if (override > 0) return fixed(Math.round(override), "GOATLY_WORKER_HEAP_MB");
|
|
143
|
+
const user = userHeapLimit(env, execArgv, runtime);
|
|
144
|
+
if (user) return fixed(user.mb, user.source, soft ? void 0 : share());
|
|
145
|
+
if (soft) return fixed(share(), "default");
|
|
146
|
+
const floor = Math.max(options.nodeDefaultMb ?? nodeDefaultHeapMb(env, execArgv), Math.ceil(options.minMb ?? 0));
|
|
147
|
+
const growing = Number(env.GOATLY_HEAP_GROWING_PERCENT ?? 50);
|
|
148
|
+
let first = floor;
|
|
149
|
+
if (env.GOATLY_HEAP_LIMIT !== "off" && growing > 0) first = Math.max(floor, share());
|
|
150
|
+
const start = Number(env.GOATLY_WORKER_HEAP_START_MB);
|
|
151
|
+
if (start > 0) first = Math.round(start);
|
|
152
|
+
const main = options.mainMb ?? Math.round(v8.getHeapStatistics().heap_size_limit / MB);
|
|
153
|
+
const budgetMb = env.GOATLY_HEAP_LIMIT === "off" ? void 0 : share();
|
|
154
|
+
return {
|
|
155
|
+
limitMb: first,
|
|
156
|
+
ladder: [
|
|
157
|
+
first,
|
|
158
|
+
2 * first,
|
|
159
|
+
Math.max(2 * first, main)
|
|
160
|
+
],
|
|
161
|
+
source: "default",
|
|
162
|
+
...budgetMb !== void 0 && budgetMb < first ? { budgetMb } : {}
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/** the heap (MB) a worker measures itself against: its budget, else its limit */
|
|
166
|
+
function workerBudgetMb(heap, limitMb) {
|
|
167
|
+
if (heap.soft) return limitMb;
|
|
168
|
+
return heap.budgetMb !== void 0 && limitMb !== void 0 ? Math.min(heap.budgetMb, limitMb) : limitMb;
|
|
169
|
+
}
|
|
170
|
+
/** e.g. "heap limit 2869 MB (default)", "heap budget 2869 MB (default)" (Bun), for messages */
|
|
171
|
+
function heapText(heap) {
|
|
172
|
+
if (heap.limitMb === void 0) return "no heap limit";
|
|
173
|
+
const budget = heap.budgetMb !== void 0 ? `, budget ${heap.budgetMb} MB` : "";
|
|
174
|
+
return `heap ${heap.soft ? "budget" : "limit"} ${heap.limitMb} MB${budget} (${heap.source})`;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* The heap limit (MB) of a worker of attempt `rung` (0: the first, then replacements): replacements
|
|
178
|
+
* get at most the memory that is free when they start – never less than the first limit.
|
|
179
|
+
*/
|
|
180
|
+
function workerLimitMb(heap, rung) {
|
|
181
|
+
if (heap.limitMb === void 0) return void 0;
|
|
182
|
+
const ladder = heap.ladder;
|
|
183
|
+
const wanted = ladder[Math.min(rung, ladder.length - 1)];
|
|
184
|
+
if (rung === 0 || wanted <= ladder[0]) return ladder[0];
|
|
185
|
+
return Math.max(ladder[0], Math.min(wanted, availableMemoryMb() - REPLACEMENT_RESERVE_MB));
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* What to do when a worker thread keeps running out of memory (for error messages). `triedMb`: the
|
|
189
|
+
* highest heap limit a worker had – building in the main thread is only suggested when its limit is
|
|
190
|
+
* higher.
|
|
191
|
+
*/
|
|
192
|
+
function outOfMemoryHint(heap, triedMb = heap.limitMb ?? 0) {
|
|
193
|
+
if (heap.soft) return "Bun has no heap limit per thread: worker threads only drop their caches when their heaps reach their budgets (GOATLY_WORKER_HEAP_MB=<MB> sets it). Fewer worker threads (`renderWorkers` in gatsby-config, or GOATLY_RENDER_WORKERS=<n>) need less memory.";
|
|
194
|
+
const mainMb = Math.round(v8.getHeapStatistics().heap_size_limit / MB);
|
|
195
|
+
const mainThread = (heap.source === "default" || heap.source === "GOATLY_WORKER_HEAP_MB") && mainMb > triedMb + 256 ? ` \`renderWorkers: 1\` in gatsby-config (or GOATLY_RENDER_WORKERS=1 when it doesn't set renderWorkers) builds all pages in the main thread instead (heap limit ${mainMb} MB).` : "";
|
|
196
|
+
if (heap.source === "GOATLY_WORKER_HEAP_MB") return `The limit comes from GOATLY_WORKER_HEAP_MB: raise it.${mainThread}`;
|
|
197
|
+
if (heap.source !== "default") return `Worker threads get the limit you set with ${heap.source}: raise it, or set GOATLY_WORKER_HEAP_MB=<MB> (worker threads only).${mainThread}`;
|
|
198
|
+
return `That is about as much as a worker thread gets here: the page, or code that runs for it, needs too much memory (e.g. a very large query result, or an endless loop). GOATLY_WORKER_HEAP_MB=<MB> sets the heap limit of worker threads.${mainThread}`;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* what a query worker needs (MB) when its page queries run in WASM, until it reports what it uses
|
|
202
|
+
* (see memory-governor.ts): the nodes are in the main thread's shared store, a worker's heap holds
|
|
203
|
+
* its renderer and its pages' results – measured 35–80 MB of heap (20k–100k pages, ~140 MB at
|
|
204
|
+
* 400k) and ~90 MB of RSS per worker (100k pages); 1.25 × 140 + 32 MB rounded up
|
|
205
|
+
*/
|
|
206
|
+
const WASM_QUERY_WORKER_MB = 256;
|
|
207
|
+
/**
|
|
208
|
+
* How many query workers fit into the available memory. Every worker rebuilds the data layer –
|
|
209
|
+
* about as large as the main thread's heap after bootstrap – unless the datastore is shared
|
|
210
|
+
* between threads (`lazy` stores read nodes on demand).
|
|
211
|
+
*/
|
|
212
|
+
function planQueryWorkers(options) {
|
|
213
|
+
const perWorkerMb = options.sharedDatastore ? 512 : Math.max(512, Math.ceil(options.heapUsedMb * 1.25 + 256));
|
|
214
|
+
const availableMb = options.availableMb ?? availableMemoryMb();
|
|
215
|
+
const fit = Math.max(0, Math.floor((availableMb - MAIN_RESERVE_MB) / perWorkerMb));
|
|
216
|
+
const count = Math.min(options.wanted, fit);
|
|
217
|
+
return {
|
|
218
|
+
count,
|
|
219
|
+
perWorkerMb,
|
|
220
|
+
heap: planWorkerHeap({
|
|
221
|
+
...options,
|
|
222
|
+
availableMb,
|
|
223
|
+
workers: count,
|
|
224
|
+
minMb: options.sharedDatastore ? 0 : Math.ceil(perWorkerMb * 1.5)
|
|
225
|
+
})
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* How many render workers to start for `batches` batches of pages: at most one per batch and as
|
|
230
|
+
* many as fit into the available memory (fewer than 2: render in the main thread).
|
|
231
|
+
*/
|
|
232
|
+
function planRenderWorkers(options) {
|
|
233
|
+
const availableMb = options.availableMb ?? availableMemoryMb();
|
|
234
|
+
const fit = Math.floor((availableMb - MAIN_RESERVE_MB) / RENDER_WORKER_MB);
|
|
235
|
+
const count = Math.max(1, Math.min(options.wanted, options.batches, fit));
|
|
236
|
+
return {
|
|
237
|
+
count,
|
|
238
|
+
heap: planWorkerHeap({
|
|
239
|
+
...options,
|
|
240
|
+
availableMb,
|
|
241
|
+
workers: count
|
|
242
|
+
})
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* V8 settings for a build (Node only, process-wide, read by isolates created afterwards):
|
|
247
|
+
* - a `--max-old-space-size` of the process (e.g. the bin's 75% of the memory) would be every
|
|
248
|
+
* worker's limit and override their `resourceLimits`: reset – every build worker gets explicit
|
|
249
|
+
* limits from planWorkerHeap, which applies a limit the user chose to the workers, too
|
|
250
|
+
* - V8 lets a heap grow to about 4× its live size before a major GC once its limit is 2 GB or more;
|
|
251
|
+
* `--heap-growing-percent` keeps heaps closer to their live size (GOATLY_HEAP_GROWING_PERCENT,
|
|
252
|
+
* 0: V8's default)
|
|
253
|
+
* (Bun: JavaScriptCore's heap growth is kept – limiting it with BUN_JSC_* settings cost more time
|
|
254
|
+
* than it saved memory; a smaller worker budget is the better lever, see planWorkerHeap)
|
|
255
|
+
*/
|
|
256
|
+
function configureBuildHeap() {
|
|
257
|
+
if (isBun) return;
|
|
258
|
+
try {
|
|
259
|
+
v8.setFlagsFromString("--max-old-space-size=0");
|
|
260
|
+
const growing = Number(process.env.GOATLY_HEAP_GROWING_PERCENT ?? 50);
|
|
261
|
+
if (growing > 0) v8.setFlagsFromString(`--heap-growing-percent=${Math.round(growing)}`);
|
|
262
|
+
} catch {}
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* used heap / heap limit of this thread – / `budgetMb` when that is smaller (a worker's share of
|
|
266
|
+
* the free memory, see WorkerHeap). Bun: / `budgetMb`, the worker's budget (0 without one).
|
|
267
|
+
* Its heap in use is the larger of `heapUsed` (the live objects as of the last collection, plus
|
|
268
|
+
* strings and buffers at once) and `heapTotal` (the heap's blocks, garbage included – down to the
|
|
269
|
+
* live objects after `Bun.gc(true)`, see collectGarbage), like V8's used heap. (Not
|
|
270
|
+
* `v8.getHeapStatistics()`: on Bun it walks the whole heap, tens of milliseconds per million
|
|
271
|
+
* objects, and its limit is 10× the process's peak memory.)
|
|
272
|
+
*/
|
|
273
|
+
function heapRatio(budgetMb, runtime = RUNTIME, usage = () => process.memoryUsage()) {
|
|
274
|
+
if (runtime === "bun") {
|
|
275
|
+
if (!budgetMb) return 0;
|
|
276
|
+
const { heapUsed, heapTotal } = usage();
|
|
277
|
+
return Math.max(heapUsed, heapTotal) / (budgetMb * MB);
|
|
278
|
+
}
|
|
279
|
+
const heap = v8.getHeapStatistics();
|
|
280
|
+
const limit = budgetMb && budgetMb * MB < heap.heap_size_limit ? budgetMb * MB : heap.heap_size_limit;
|
|
281
|
+
return heap.used_heap_size / limit;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* The heap (MB) this thread uses: V8's used heap; Bun: the larger of `heapUsed` and `heapTotal`
|
|
285
|
+
* (see heapRatio)
|
|
286
|
+
*/
|
|
287
|
+
function heapUsedMb(runtime = RUNTIME) {
|
|
288
|
+
if (runtime === "bun") {
|
|
289
|
+
const { heapUsed, heapTotal } = process.memoryUsage();
|
|
290
|
+
return Math.max(heapUsed, heapTotal) / MB;
|
|
291
|
+
}
|
|
292
|
+
return v8.getHeapStatistics().used_heap_size / MB;
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Whether a query worker checks its heap (see createHeapGuard): `used` – the heap in use now, `live`
|
|
296
|
+
* – what was left after the last check (shares of the heap limit), `since` – batches since then,
|
|
297
|
+
* `futile` – the last release freed little.
|
|
298
|
+
*/
|
|
299
|
+
function shouldReleaseHeap(used, live, since, spacing, futile = false) {
|
|
300
|
+
return used >= Math.min(.85, Math.max(.7, live + .15)) && (since >= spacing || used >= .85 && !futile);
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Drops what a query worker only keeps for reuse (`release`: query engine caches, plugin cache
|
|
304
|
+
* entries, decoded nodes) when its heap fills up, then collects garbage. Called between batches
|
|
305
|
+
* (nothing in flight): at 70% of the heap limit in use – live + 15% when the last release left more,
|
|
306
|
+
* at most 85% – at most every `spacing` batches (8, doubled up to 64 while releases free less than
|
|
307
|
+
* 10%), at 85% at once (unless the last release freed little). A GC runs first: when it frees
|
|
308
|
+
* enough, the pressure was garbage and the caches stay (checks are spaced out further). Those caches
|
|
309
|
+
* are bounded by entries, not bytes: large nodes or many views of a large type could otherwise run a
|
|
310
|
+
* worker out of memory. On Bun `ratio` measures against the worker's budget (heapRatio), without one
|
|
311
|
+
* it is 0 and nothing is released.
|
|
312
|
+
* (GOATLY_HEAP_GUARD=off|always: internal, for tests)
|
|
313
|
+
*/
|
|
314
|
+
function createHeapGuard(options) {
|
|
315
|
+
const mode = (options.env ?? process.env).GOATLY_HEAP_GUARD;
|
|
316
|
+
const ratio = options.ratio ?? heapRatio;
|
|
317
|
+
const gc = options.gc ?? ((full) => collectGarbage(full));
|
|
318
|
+
let since = 1e400;
|
|
319
|
+
let live = 0;
|
|
320
|
+
let spacing = 8;
|
|
321
|
+
let futile = false;
|
|
322
|
+
let releases = 0;
|
|
323
|
+
let checked = false;
|
|
324
|
+
let checks = 0;
|
|
325
|
+
return {
|
|
326
|
+
get releases() {
|
|
327
|
+
return releases;
|
|
328
|
+
},
|
|
329
|
+
/** heap checks so far (each collected garbage) */
|
|
330
|
+
get checks() {
|
|
331
|
+
return checks;
|
|
332
|
+
},
|
|
333
|
+
/** the share of the heap in use after the last check (garbage collected), 0: none yet */
|
|
334
|
+
get live() {
|
|
335
|
+
return checked ? live : 0;
|
|
336
|
+
},
|
|
337
|
+
/**
|
|
338
|
+
* Forgets what the last checks found (e.g. the budget it measures against was lowered): the
|
|
339
|
+
* next batch is checked
|
|
340
|
+
*/
|
|
341
|
+
rebase() {
|
|
342
|
+
since = 1e400;
|
|
343
|
+
live = 0;
|
|
344
|
+
spacing = 8;
|
|
345
|
+
futile = false;
|
|
346
|
+
checked = false;
|
|
347
|
+
},
|
|
348
|
+
afterBatch() {
|
|
349
|
+
if (mode === "off") return;
|
|
350
|
+
since++;
|
|
351
|
+
let used = ratio();
|
|
352
|
+
if (mode !== "always") {
|
|
353
|
+
if (!shouldReleaseHeap(used, live, since, spacing, futile)) return;
|
|
354
|
+
gc(false);
|
|
355
|
+
used = ratio();
|
|
356
|
+
since = 0;
|
|
357
|
+
checked = true;
|
|
358
|
+
checks++;
|
|
359
|
+
if (used < Math.min(.85, Math.max(.7, live + .15))) {
|
|
360
|
+
live = used;
|
|
361
|
+
spacing = Math.min(64, spacing * 2);
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
options.release();
|
|
366
|
+
gc(true);
|
|
367
|
+
const after = ratio();
|
|
368
|
+
futile = used - after < .1;
|
|
369
|
+
spacing = futile ? Math.min(64, spacing * 2) : 8;
|
|
370
|
+
live = after;
|
|
371
|
+
since = 0;
|
|
372
|
+
checked = true;
|
|
373
|
+
checks++;
|
|
374
|
+
releases++;
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* A full, memory-reducing GC (releases heap pages, not only objects) – e.g. before workers start.
|
|
380
|
+
* `full = false`: a plain major GC.
|
|
381
|
+
*/
|
|
382
|
+
function collectGarbage(full = true) {
|
|
383
|
+
try {
|
|
384
|
+
if (isBun) {
|
|
385
|
+
globalThis.Bun?.gc?.(true);
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
let gc = globalThis.gc;
|
|
389
|
+
if (typeof gc !== "function") {
|
|
390
|
+
v8.setFlagsFromString("--expose-gc");
|
|
391
|
+
gc = vm.runInNewContext("gc");
|
|
392
|
+
}
|
|
393
|
+
gc({
|
|
394
|
+
type: "major",
|
|
395
|
+
execution: "sync",
|
|
396
|
+
...full ? { flavor: "last-resort" } : {}
|
|
397
|
+
});
|
|
398
|
+
} catch {}
|
|
399
|
+
}
|
|
400
|
+
export { RUNTIME, WASM_QUERY_WORKER_MB, availableMemoryMb, collectGarbage, configureBuildHeap, createHeapGuard, heapRatio, heapText, heapUsedMb, maxOldSpaceSizeArg, nodeDefaultHeapMb, outOfMemoryHint, parseVmStatAvailableMb, planQueryWorkers, planRenderWorkers, planWorkerHeap, shouldReleaseHeap, totalMemoryMb, userHeapLimit, workerBudgetMb, workerLimitMb };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// src/node/utils/murmurhash.ts
|
|
2
|
+
/**
|
|
3
|
+
* MurmurHash2 (32-bit) as used by Gatsby (`babel-plugin-remove-graphql-queries`)
|
|
4
|
+
* to compute static query hashes. Kept identical so `staticQueryHashes` match.
|
|
5
|
+
*/
|
|
6
|
+
function murmurhash(str, seed) {
|
|
7
|
+
let l = str.length;
|
|
8
|
+
let h = seed ^ l;
|
|
9
|
+
let i = 0;
|
|
10
|
+
let k;
|
|
11
|
+
while (l >= 4) {
|
|
12
|
+
k = str.charCodeAt(i) & 255 | (str.charCodeAt(++i) & 255) << 8 | (str.charCodeAt(++i) & 255) << 16 | (str.charCodeAt(++i) & 255) << 24;
|
|
13
|
+
k = (k & 65535) * 1540483477 + (((k >>> 16) * 1540483477 & 65535) << 16);
|
|
14
|
+
k ^= k >>> 24;
|
|
15
|
+
k = (k & 65535) * 1540483477 + (((k >>> 16) * 1540483477 & 65535) << 16);
|
|
16
|
+
h = (h & 65535) * 1540483477 + (((h >>> 16) * 1540483477 & 65535) << 16) ^ k;
|
|
17
|
+
l -= 4;
|
|
18
|
+
++i;
|
|
19
|
+
}
|
|
20
|
+
switch (l) {
|
|
21
|
+
case 3: h ^= (str.charCodeAt(i + 2) & 255) << 16;
|
|
22
|
+
case 2: h ^= (str.charCodeAt(i + 1) & 255) << 8;
|
|
23
|
+
case 1:
|
|
24
|
+
h ^= str.charCodeAt(i) & 255;
|
|
25
|
+
h = (h & 65535) * 1540483477 + (((h >>> 16) * 1540483477 & 65535) << 16);
|
|
26
|
+
}
|
|
27
|
+
h ^= h >>> 13;
|
|
28
|
+
h = (h & 65535) * 1540483477 + (((h >>> 16) * 1540483477 & 65535) << 16);
|
|
29
|
+
h ^= h >>> 15;
|
|
30
|
+
return h >>> 0;
|
|
31
|
+
}
|
|
32
|
+
export { murmurhash };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
// src/node/utils/parser.ts
|
|
3
|
+
let utils;
|
|
4
|
+
/**
|
|
5
|
+
* Parses JS/TS with oxc's parser as compiled into rolldown (`rolldown/utils`, the parser the
|
|
6
|
+
* oxc-parser package publishes), taken from the rolldown that Vite runs: a process then loads one
|
|
7
|
+
* rolldown native binding and no parser binding of its own. It is resolved from Vite's location
|
|
8
|
+
* without importing vite (query workers parse plugin API files and never load vite), on first use;
|
|
9
|
+
* `require()` loads that ES module synchronously (Node.js since 22.12, Bun).
|
|
10
|
+
*/
|
|
11
|
+
function parseSync(filename, sourceText, options) {
|
|
12
|
+
utils ??= createRequire(createRequire(import.meta.url).resolve("vite/package.json"))("rolldown/utils");
|
|
13
|
+
return utils.parseSync(filename, sourceText, options);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Walks an AST depth-first: calls `visitor[node.type]` before a node's children and
|
|
17
|
+
* `visitor[`${node.type}:exit`]` after them (as oxc's `Visitor`, which rolldown marks experimental).
|
|
18
|
+
*/
|
|
19
|
+
function walk(node, visitor) {
|
|
20
|
+
if (Array.isArray(node)) {
|
|
21
|
+
for (const child of node) if (child !== null) walk(child, visitor);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
const type = node.type;
|
|
25
|
+
const callbacks = visitor;
|
|
26
|
+
if (typeof type === "string") callbacks[type]?.(node);
|
|
27
|
+
for (const key in node) {
|
|
28
|
+
const value = node[key];
|
|
29
|
+
if (value !== null && typeof value === "object") walk(value, visitor);
|
|
30
|
+
}
|
|
31
|
+
if (typeof type === "string") callbacks[`${type}:exit`]?.(node);
|
|
32
|
+
}
|
|
33
|
+
export { parseSync, walk };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// src/node/utils/partition-hash.ts
|
|
2
|
+
/**
|
|
3
|
+
* A 32-bit hash for spreading keys over partition files: FNV-1a over the UTF-16 code units of the
|
|
4
|
+
* parts (separated by a 0), finished with murmur3's finalizer. The same in every runtime and run.
|
|
5
|
+
* (Without the finalizer, keys that only differ in their last characters, e.g. "node-1", "node-2",
|
|
6
|
+
* fall into a few partitions.)
|
|
7
|
+
*/
|
|
8
|
+
function partitionHash(...parts) {
|
|
9
|
+
let h = 2166136261;
|
|
10
|
+
for (let p = 0; p < parts.length; p++) {
|
|
11
|
+
if (p > 0) h = Math.imul(h, 16777619);
|
|
12
|
+
const s = parts[p];
|
|
13
|
+
for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619);
|
|
14
|
+
}
|
|
15
|
+
h = Math.imul(h ^ h >>> 16, 2246822507);
|
|
16
|
+
h = Math.imul(h ^ h >>> 13, 3266489909);
|
|
17
|
+
return (h ^ h >>> 16) >>> 0;
|
|
18
|
+
}
|
|
19
|
+
export { partitionHash };
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { createContentDigest } from "./content-digest.js";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
// src/node/utils/paths.ts
|
|
4
|
+
/** Convert Windows backslash paths to slash paths. Same semantics as gatsby-core-utils `slash`. */
|
|
5
|
+
function slash(p) {
|
|
6
|
+
if (p.startsWith("\\\\?\\")) return p;
|
|
7
|
+
return p.replace(/\\/g, "/");
|
|
8
|
+
}
|
|
9
|
+
function applyTrailingSlashOption(input, option = "always") {
|
|
10
|
+
if (input === "/") return input;
|
|
11
|
+
const hasTrailingSlash = input.endsWith("/");
|
|
12
|
+
if (option === "always") {
|
|
13
|
+
const lastSegment = input.split("/").pop() ?? "";
|
|
14
|
+
if (hasTrailingSlash || /\.[a-z0-9]+$/i.test(lastSegment)) return input;
|
|
15
|
+
return `${input}/`;
|
|
16
|
+
}
|
|
17
|
+
if (option === "never") return hasTrailingSlash ? input.replace(/\/+$/, "") || "/" : input;
|
|
18
|
+
return input;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The URL path the dev server redirects `pathname` (raw, as requested) to so it has the form the
|
|
22
|
+
* trailingSlash option asks for – or null when it already has it. Never a path starting with `//`
|
|
23
|
+
* or `/\`: browsers read such a `Location` as another host (`//evil.example/`).
|
|
24
|
+
*/
|
|
25
|
+
function trailingSlashRedirect(pathname, option) {
|
|
26
|
+
if (!pathname.startsWith("/") || /^\/[/\\]/.test(pathname)) return null;
|
|
27
|
+
const canonical = applyTrailingSlashOption(pathname, option);
|
|
28
|
+
return canonical !== pathname ? canonical : null;
|
|
29
|
+
}
|
|
30
|
+
/** Normalizes a page path for lookups: ensures a leading slash and strips pathPrefix. */
|
|
31
|
+
function stripPrefix(p, prefix = "") {
|
|
32
|
+
if (!prefix) return p;
|
|
33
|
+
if (p === prefix) return "/";
|
|
34
|
+
if (p.startsWith(`${prefix}/`)) return p.slice(prefix.length);
|
|
35
|
+
return p;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* A page path that `path.join` leaves as it is: `/`, or `/a/b/` with segments that are not empty,
|
|
39
|
+
* don't start with a dot (`.`, `..`) and have no backslash, and whose last one doesn't end with
|
|
40
|
+
* `.html` (that one names the HTML file). The output paths of these pages are concatenated: builds
|
|
41
|
+
* compute them for every page several times (to check, write and clean up its files), and
|
|
42
|
+
* `path.join` normalizes the whole path each time.
|
|
43
|
+
*/
|
|
44
|
+
const PLAIN_PAGE_PATH = /^\/(?:[^/\\.][^/\\]*\/)*$/;
|
|
45
|
+
/** POSIX paths (`path.join` uses backslashes on Windows) */
|
|
46
|
+
const POSIX = path.sep === "/";
|
|
47
|
+
/** the last directory checked by `isPlainDir` (one public directory per build) */
|
|
48
|
+
let plainDir;
|
|
49
|
+
/** an absolute directory that `path.join` leaves as it is (no trailing slash, nothing to resolve) */
|
|
50
|
+
function isPlainDir(dir) {
|
|
51
|
+
if (dir === plainDir && plainDir !== void 0) return true;
|
|
52
|
+
if (!POSIX || !path.isAbsolute(dir) || dir.length < 2 || path.normalize(dir) !== dir) return false;
|
|
53
|
+
if (dir.endsWith("/")) return false;
|
|
54
|
+
plainDir = dir;
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
const isPlain = (dir, pagePath) => isPlainDir(dir) && PLAIN_PAGE_PATH.test(pagePath) && !pagePath.endsWith(".html/");
|
|
58
|
+
/** `/blog/hello/` → `blog/hello/index.html`, `/404.html` → `404.html` */
|
|
59
|
+
function generateHtmlPath(dir, pagePath) {
|
|
60
|
+
if (isPlain(dir, pagePath)) return `${dir}${pagePath}index.html`;
|
|
61
|
+
let outputFileName = pagePath.replace(/^(\/|\\)/, "");
|
|
62
|
+
if (path.extname(outputFileName) !== ".html") outputFileName = path.join(outputFileName, "index.html");
|
|
63
|
+
return path.join(dir, outputFileName);
|
|
64
|
+
}
|
|
65
|
+
/** `/` → `index`, `/blog/` → `blog`, used for page-data paths. */
|
|
66
|
+
function fixedPagePath(pagePath) {
|
|
67
|
+
return pagePath === "/" ? "index" : pagePath;
|
|
68
|
+
}
|
|
69
|
+
function generatePageDataPath(publicDir, pagePath) {
|
|
70
|
+
if (pagePath !== "/" && isPlain(publicDir, pagePath)) return `${publicDir}/page-data${pagePath}page-data.json`;
|
|
71
|
+
return path.join(publicDir, "page-data", fixedPagePath(pagePath).replace(/^\/|\/$/g, ""), "page-data.json");
|
|
72
|
+
}
|
|
73
|
+
/** Gatsby compatible component chunk name, e.g. `component---src-pages-index-tsx`. */
|
|
74
|
+
const chunkNames = /* @__PURE__ */ new Map();
|
|
75
|
+
function generateComponentChunkName(componentPath, directory, kind = "component") {
|
|
76
|
+
const key = `${kind}\0${directory}\0${componentPath}`;
|
|
77
|
+
let cached = chunkNames.get(key);
|
|
78
|
+
if (cached === void 0) {
|
|
79
|
+
cached = computeComponentChunkName(componentPath, directory, kind);
|
|
80
|
+
if (chunkNames.size >= 1e4) chunkNames.clear();
|
|
81
|
+
chunkNames.set(key, cached);
|
|
82
|
+
}
|
|
83
|
+
return cached;
|
|
84
|
+
}
|
|
85
|
+
function computeComponentChunkName(componentPath, directory, kind) {
|
|
86
|
+
const [componentFile, query] = componentPath.split("?__contentFilePath=");
|
|
87
|
+
let name = slash(path.relative(directory, componentFile));
|
|
88
|
+
if (query) name += `-${slash(path.relative(directory, query))}`;
|
|
89
|
+
name = name.replace(/[^a-zA-Z0-9-_]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
|
|
90
|
+
if (name.length > 180) name = `${name.slice(0, 100)}-${simpleHash(name)}`;
|
|
91
|
+
return `${kind}---${name}`;
|
|
92
|
+
}
|
|
93
|
+
function simpleHash(s) {
|
|
94
|
+
let h = 0;
|
|
95
|
+
for (let i = 0; i < s.length; i++) h = Math.imul(31, h) + s.charCodeAt(i) | 0;
|
|
96
|
+
return (h >>> 0).toString(36);
|
|
97
|
+
}
|
|
98
|
+
function isRelativeOrAbsolute(p) {
|
|
99
|
+
return p.startsWith(".") || path.isAbsolute(p);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Page paths whose segments are too long for a file name (`ENAMETOOLONG` when the page's HTML or
|
|
103
|
+
* page-data.json is written). Same as Gatsby's `truncatePath`: such a segment keeps its first 50
|
|
104
|
+
* characters and the rest is replaced by its content digest. createPage stores the page at the
|
|
105
|
+
* shortened path, and deletePage shortens the path it gets the same way. (Idempotent: a shortened
|
|
106
|
+
* segment has 82 characters.)
|
|
107
|
+
*/
|
|
108
|
+
const MAX_PATH_SEGMENT_LENGTH = 255;
|
|
109
|
+
const SLICING_INDEX = 50;
|
|
110
|
+
const pathSegmentRe = /[^/]+/g;
|
|
111
|
+
const countsUtf16Units = process.platform === "darwin" || process.platform === "win32";
|
|
112
|
+
/** The unit segmentLength counts in ("characters" or "bytes") */
|
|
113
|
+
const segmentLengthUnit = countsUtf16Units ? "characters" : "bytes";
|
|
114
|
+
const segmentLength = (segment) => countsUtf16Units ? segment.length : Buffer.byteLength(segment);
|
|
115
|
+
const isNameTooLong = (segment) => segmentLength(segment) > MAX_PATH_SEGMENT_LENGTH;
|
|
116
|
+
function tooLongSegmentsInPath(pagePath) {
|
|
117
|
+
return (pagePath.match(pathSegmentRe) ?? []).filter(isNameTooLong);
|
|
118
|
+
}
|
|
119
|
+
function truncatePath(pagePath) {
|
|
120
|
+
return pagePath.replace(pathSegmentRe, (segment) => isNameTooLong(segment) ? segment.slice(0, SLICING_INDEX) + createContentDigest(segment.slice(SLICING_INDEX)) : segment);
|
|
121
|
+
}
|
|
122
|
+
export { applyTrailingSlashOption, fixedPagePath, generateComponentChunkName, generateHtmlPath, generatePageDataPath, isRelativeOrAbsolute, segmentLength, segmentLengthUnit, slash, stripPrefix, tooLongSegmentsInPath, trailingSlashRedirect, truncatePath };
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { isBun } from "./runtime.js";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
// src/node/utils/resolver.ts
|
|
4
|
+
const EXTENSIONS = [
|
|
5
|
+
".js",
|
|
6
|
+
".json",
|
|
7
|
+
".node"
|
|
8
|
+
];
|
|
9
|
+
let resolvers;
|
|
10
|
+
/**
|
|
11
|
+
* oxc-resolver as compiled into rolldown (`rolldown/experimental`), taken from the rolldown that
|
|
12
|
+
* Vite runs, like the parser (see parser.ts): no native binding of its own. Created on first use.
|
|
13
|
+
* Both resolvers share one cache.
|
|
14
|
+
*/
|
|
15
|
+
function getResolvers() {
|
|
16
|
+
if (resolvers) return resolvers;
|
|
17
|
+
const { ResolverFactory } = createRequire(createRequire(import.meta.url).resolve("vite/package.json"))("rolldown/experimental");
|
|
18
|
+
const runtime = isBun ? ["bun", "node"] : ["node"];
|
|
19
|
+
const options = (kind) => ({
|
|
20
|
+
conditionNames: [
|
|
21
|
+
...runtime,
|
|
22
|
+
kind,
|
|
23
|
+
"module-sync"
|
|
24
|
+
],
|
|
25
|
+
extensions: EXTENSIONS,
|
|
26
|
+
builtinModules: true
|
|
27
|
+
});
|
|
28
|
+
const importResolver = new ResolverFactory(options("import"));
|
|
29
|
+
resolvers = {
|
|
30
|
+
import: importResolver,
|
|
31
|
+
require: importResolver.cloneWithOptions(options("require"))
|
|
32
|
+
};
|
|
33
|
+
return resolvers;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Resolves `specifier` from the directory `fromDir` to a file (its real path), as `import` (the
|
|
37
|
+
* default) or `require` there would, with the package "exports" and "imports" conditions of the
|
|
38
|
+
* runtime. Throws if it cannot be resolved, or if it is a built-in module.
|
|
39
|
+
*/
|
|
40
|
+
function resolveModule(specifier, fromDir, kind = "import") {
|
|
41
|
+
const result = getResolvers()[kind].sync(fromDir, specifier);
|
|
42
|
+
if (result.path) return result.path;
|
|
43
|
+
if (result.builtin) throw new Error(`"${specifier}" is the built-in module ${result.builtin.resolved}, not a file`);
|
|
44
|
+
const error = /* @__PURE__ */ new Error(`Cannot resolve "${specifier}" from ${fromDir}${result.error ? `: ${result.error}` : ""}`);
|
|
45
|
+
error.code = "MODULE_NOT_FOUND";
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
export { resolveModule };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// src/node/utils/runtime.ts
|
|
2
|
+
/** Runtime detection – goatly runs natively on Node.js (22.22.3+, 24.11.1+, >= 25.1) and Bun (>= 1.2). */
|
|
3
|
+
const isBun = typeof globalThis.Bun !== "undefined";
|
|
4
|
+
const runtimeName = isBun ? `bun ${globalThis.Bun.version}` : `node ${process.versions.node}`;
|
|
5
|
+
export { isBun, runtimeName };
|