goatly 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +874 -1
  2. package/bin/goatly.js +99 -0
  3. package/dist/cli/index.js +234 -0
  4. package/dist/compat/gatsby-node-entry.js +16 -0
  5. package/dist/compat/gatsby-package.json +6 -0
  6. package/dist/compat/md5-file.js +47 -0
  7. package/dist/compat-apis.json +72 -0
  8. package/dist/compat-apis.json.js +62 -0
  9. package/dist/graphql.js +3 -0
  10. package/dist/node/actions/index.js +619 -0
  11. package/dist/node/actions/job-store.js +180 -0
  12. package/dist/node/actions/jobs.js +174 -0
  13. package/dist/node/api-runner.js +258 -0
  14. package/dist/node/bootstrap.js +569 -0
  15. package/dist/node/build/assets.js +110 -0
  16. package/dist/node/build/incremental.js +208 -0
  17. package/dist/node/build/index.js +763 -0
  18. package/dist/node/build/memory-governor.js +450 -0
  19. package/dist/node/build/output-dirs.js +70 -0
  20. package/dist/node/build/page-data.js +40 -0
  21. package/dist/node/build/page-files.js +186 -0
  22. package/dist/node/build/partitioned-state.js +258 -0
  23. package/dist/node/build/query-worker.js +626 -0
  24. package/dist/node/build/query-workers.js +863 -0
  25. package/dist/node/build/render-thread.js +103 -0
  26. package/dist/node/build/render-worker.js +162 -0
  27. package/dist/node/build/state.js +24 -0
  28. package/dist/node/build/timing-breakdown.js +216 -0
  29. package/dist/node/build/work-clock.js +75 -0
  30. package/dist/node/build/worker-pool.js +242 -0
  31. package/dist/node/cache-layout.js +99 -0
  32. package/dist/node/cache.js +1430 -0
  33. package/dist/node/compat/chokidar-shim.js +148 -0
  34. package/dist/node/compat/core-utils-lmdb.js +145 -0
  35. package/dist/node/compat/create-node-id-shim.js +1 -0
  36. package/dist/node/compat/module-hooks.js +245 -0
  37. package/dist/node/compat/redux-shim.js +1 -0
  38. package/dist/node/config/index.js +162 -0
  39. package/dist/node/config/not-found-pages.js +95 -0
  40. package/dist/node/datastore/codec.js +144 -0
  41. package/dist/node/datastore/index.js +127 -0
  42. package/dist/node/datastore/logfile/cache.js +89 -0
  43. package/dist/node/datastore/logfile/index.js +1329 -0
  44. package/dist/node/datastore/logfile/record.js +71 -0
  45. package/dist/node/datastore/types.js +1 -0
  46. package/dist/node/develop/express-compat.js +207 -0
  47. package/dist/node/develop/graphiql.js +22 -0
  48. package/dist/node/develop/hydration-report.js +41 -0
  49. package/dist/node/develop/index.js +618 -0
  50. package/dist/node/develop/local-url.js +10 -0
  51. package/dist/node/develop/ssr-runner.js +66 -0
  52. package/dist/node/gql.js +5 -0
  53. package/dist/node/index.js +15 -0
  54. package/dist/node/info.js +270 -0
  55. package/dist/node/internal-plugins/data-bridge.js +196 -0
  56. package/dist/node/internal-plugins/page-creator.js +318 -0
  57. package/dist/node/loader/import-module.js +160 -0
  58. package/dist/node/node-helpers.js +66 -0
  59. package/dist/node/not-found-pages.js +220 -0
  60. package/dist/node/plugins/api-list.js +12 -0
  61. package/dist/node/plugins/load-plugins.js +427 -0
  62. package/dist/node/plugins/resolve-plugin.js +79 -0
  63. package/dist/node/plugins/static-exports.js +64 -0
  64. package/dist/node/query/compile.js +326 -0
  65. package/dist/node/query/dependencies.js +45 -0
  66. package/dist/node/query/execute.js +417 -0
  67. package/dist/node/query/extract.js +372 -0
  68. package/dist/node/query/gql-tada-introspection.js +124 -0
  69. package/dist/node/query/graphql-env.js +231 -0
  70. package/dist/node/query/graphql-runner.js +79 -0
  71. package/dist/node/redux/actions.js +1 -0
  72. package/dist/node/redux/index.js +133 -0
  73. package/dist/node/redux/node-changes.js +128 -0
  74. package/dist/node/redux/reducers.js +193 -0
  75. package/dist/node/redux/state.js +71 -0
  76. package/dist/node/renderer.js +124 -0
  77. package/dist/node/reporter-transports.js +259 -0
  78. package/dist/node/reporter.js +497 -0
  79. package/dist/node/schema/date.js +539 -0
  80. package/dist/node/schema/extensions.js +315 -0
  81. package/dist/node/schema/index.js +542 -0
  82. package/dist/node/schema/infer.js +388 -0
  83. package/dist/node/schema/inline-objects.js +128 -0
  84. package/dist/node/schema/naming.js +20 -0
  85. package/dist/node/schema/node-model.js +207 -0
  86. package/dist/node/schema/query-engine.js +1808 -0
  87. package/dist/node/schema/resolver-kinds.js +7 -0
  88. package/dist/node/schema/resolvers.js +273 -0
  89. package/dist/node/schema/type-builders.js +45 -0
  90. package/dist/node/schema/types.js +241 -0
  91. package/dist/node/serve.js +90 -0
  92. package/dist/node/site-page-nodes.js +277 -0
  93. package/dist/node/types.js +1 -0
  94. package/dist/node/utils/content-digest.js +107 -0
  95. package/dist/node/utils/cpus.js +104 -0
  96. package/dist/node/utils/create-node-id.js +51 -0
  97. package/dist/node/utils/env.js +25 -0
  98. package/dist/node/utils/fs-retry.js +74 -0
  99. package/dist/node/utils/memory-signals.js +441 -0
  100. package/dist/node/utils/memory.js +657 -0
  101. package/dist/node/utils/murmurhash.js +32 -0
  102. package/dist/node/utils/parser.js +33 -0
  103. package/dist/node/utils/partition-hash.js +19 -0
  104. package/dist/node/utils/paths.js +122 -0
  105. package/dist/node/utils/resolver.js +48 -0
  106. package/dist/node/utils/runtime.js +5 -0
  107. package/dist/node/utils/serializable.js +41 -0
  108. package/dist/node/utils/strings.js +41 -0
  109. package/dist/node/vite/config.js +289 -0
  110. package/dist/node/vite/paths.js +12 -0
  111. package/dist/node/vite/plugin-deps.js +232 -0
  112. package/dist/node/vite/plugin.js +283 -0
  113. package/dist/node/vite/react-compiler.js +362 -0
  114. package/dist/node/vite/source-files.js +83 -0
  115. package/dist/node/vite/static-image.js +136 -0
  116. package/dist/node/vite/styled-components.js +73 -0
  117. package/dist/node/vite/transforms.js +330 -0
  118. package/dist/node/wasm-data/host.js +406 -0
  119. package/dist/node/wasm-data/lower.js +406 -0
  120. package/dist/node/wasm-data/runner.js +79 -0
  121. package/dist/node/wasm-data/worker.js +95 -0
  122. package/dist/reporter.js +5 -0
  123. package/dist/runtime/api-runner.js +81 -0
  124. package/dist/runtime/app.js +256 -0
  125. package/dist/runtime/client-entry.js +4 -0
  126. package/dist/runtime/client.js +383 -0
  127. package/dist/runtime/default-html.js +31 -0
  128. package/dist/runtime/head-markup.js +100 -0
  129. package/dist/runtime/head-sync.js +101 -0
  130. package/dist/runtime/head-tags.js +45 -0
  131. package/dist/runtime/hydration-report.js +111 -0
  132. package/dist/runtime/index.js +12 -0
  133. package/dist/runtime/link.js +293 -0
  134. package/dist/runtime/loader.js +449 -0
  135. package/dist/runtime/not-found.js +61 -0
  136. package/dist/runtime/page-renderer.js +35 -0
  137. package/dist/runtime/preamble.js +47 -0
  138. package/dist/runtime/react-compat.js +14 -0
  139. package/dist/runtime/renderer-shared.js +10 -0
  140. package/dist/runtime/renderers/react-client.js +14 -0
  141. package/dist/runtime/renderers/react-server.js +99 -0
  142. package/dist/runtime/renderers/react.js +17 -0
  143. package/dist/runtime/renderers/types.js +1 -0
  144. package/dist/runtime/root-error-handlers.js +29 -0
  145. package/dist/runtime/router/history.js +132 -0
  146. package/dist/runtime/router/index.js +240 -0
  147. package/dist/runtime/router/utils.js +118 -0
  148. package/dist/runtime/script.js +110 -0
  149. package/dist/runtime/scroll.js +40 -0
  150. package/dist/runtime/slice.js +11 -0
  151. package/dist/runtime/ssr.js +240 -0
  152. package/dist/runtime/static-query.js +47 -0
  153. package/dist/utils.js +4 -0
  154. package/package.json +105 -3
  155. package/types/graphql-tada.d.ts +223 -0
  156. package/types/graphql.d.ts +2 -0
  157. package/types/index.d.ts +2287 -0
  158. package/types/node.d.ts +389 -0
  159. package/types/reporter.d.ts +187 -0
  160. package/types/router.d.ts +102 -0
  161. package/types/vendor/gql-tada.d.ts +2529 -0
@@ -0,0 +1,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 };
@@ -0,0 +1,41 @@
1
+ // src/node/utils/serializable.ts
2
+ /**
3
+ * How values are prepared before they are stored (nodes in createNode / createNodeField, plugin
4
+ * cache values in `cache.set`): values without functions, symbols or cycles are stored as they are,
5
+ * others are copied without them first, like in Gatsby.
6
+ */
7
+ /**
8
+ * Whether a value has no function, symbol or cycle. Maps, Sets and binary data aren't looked into.
9
+ */
10
+ function isSerializable(value, seen = /* @__PURE__ */ new Set()) {
11
+ if (value === null) return true;
12
+ const t = typeof value;
13
+ if (t === "function" || t === "symbol") return false;
14
+ if (t !== "object") return true;
15
+ if (seen.has(value)) return false;
16
+ if (value instanceof Date || value instanceof RegExp) return true;
17
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return true;
18
+ seen.add(value);
19
+ for (const v of Array.isArray(value) ? value : Object.values(value)) if (v !== void 0 && !isSerializable(v, seen)) return false;
20
+ seen.delete(value);
21
+ return true;
22
+ }
23
+ /**
24
+ * A copy without functions and symbols (`undefined` for such a value itself). An object that occurs
25
+ * a second time (a cycle or a shared reference) is dropped, and objects other than arrays, `Date`,
26
+ * `RegExp` and `Buffer` become plain objects of their own enumerable fields.
27
+ */
28
+ function sanitize(value, seen = /* @__PURE__ */ new WeakSet()) {
29
+ if (value === null || typeof value !== "object") return typeof value === "function" || typeof value === "symbol" ? void 0 : value;
30
+ if (value instanceof Date || value instanceof RegExp || Buffer.isBuffer(value)) return value;
31
+ if (seen.has(value)) return void 0;
32
+ seen.add(value);
33
+ if (Array.isArray(value)) return value.map((v) => sanitize(v, seen));
34
+ const out = {};
35
+ for (const [k, v] of Object.entries(value)) {
36
+ const s = sanitize(v, seen);
37
+ if (s !== void 0) out[k] = s;
38
+ }
39
+ return out;
40
+ }
41
+ export { isSerializable, sanitize };
@@ -0,0 +1,41 @@
1
+ import { isBun } from "./runtime.js";
2
+ // src/node/utils/strings.ts
3
+ /**
4
+ * Strings that msgpackr decodes from nodes are slices of larger strings: its native string
5
+ * extractor (msgpackr-extract, loaded on Node and on Bun) decodes a run of a record's short ASCII
6
+ * strings as one string of up to 6,000 characters and hands out slices of it. V8 keeps a slice of 13
7
+ * or more characters as a reference to that string, JavaScriptCore every substring of 3 or more
8
+ * characters. A structure that outlives the node and keeps one of its strings (an id, a date, a
9
+ * slug) keeps the whole run alive: 1–6 KB per node instead of a few dozen bytes.
10
+ */
11
+ const SHARED_FROM = isBun ? 3 : 13;
12
+ /** (V8: see detachString) */
13
+ const internTable = Object.create(null);
14
+ /**
15
+ * `value` without the memory of the string it came from (for strings kept longer than the node they
16
+ * were read from, e.g. the query engine's views and indexes). V8: a property lookup internalizes its
17
+ * key, turning a slice into a reference to a flat copy in the string table, which equal strings
18
+ * share (a type's views and indexes keep the same ids and values many times; 35% less heap kept
19
+ * after the page queries of 200k posts than with a copy of each). JavaScriptCore keeps the base of
20
+ * a slice it atomizes, and of a slice of a new string: a JSON round trip copies.
21
+ */
22
+ const detachString = isBun ? (value) => value.length < SHARED_FROM ? value : JSON.parse(JSON.stringify(value)) : (value) => {
23
+ if (value.length >= SHARED_FROM) Reflect.has(internTable, value);
24
+ return value;
25
+ };
26
+ /**
27
+ * A copy of plain data (strings, arrays, plain objects) whose strings share no memory with the ones
28
+ * it came from (see detachString). Other objects (Dates, Buffers, class instances) are kept as they
29
+ * are.
30
+ */
31
+ function detachValue(value, depth = 0) {
32
+ if (typeof value === "string") return detachString(value);
33
+ if (value === null || typeof value !== "object" || depth > 64) return value;
34
+ if (Array.isArray(value)) return value.map((v) => detachValue(v, depth + 1));
35
+ const proto = Object.getPrototypeOf(value);
36
+ if (proto !== Object.prototype && proto !== null) return value;
37
+ const out = {};
38
+ for (const key in value) out[key] = detachValue(value[key], depth + 1);
39
+ return out;
40
+ }
41
+ export { detachString, detachValue };
@@ -0,0 +1,289 @@
1
+ import { store } from "../redux/index.js";
2
+ import reporter from "../reporter.js";
3
+ import { apiRunnerNode } from "../api-runner.js";
4
+ import { VIRTUAL, goatlyVitePlugin } from "./plugin.js";
5
+ import { findStaticImageBabelPlugin, staticImagePlugin } from "./static-image.js";
6
+ import { findStyledComponentsBabelOptions, styledComponentsPlugin } from "./styled-components.js";
7
+ import { createReactCompilerTransform, resolveReactCompiler } from "./react-compiler.js";
8
+ import { clientEntry, routerIndex, runtimeDir, runtimeIndex, ssrEntry } from "./paths.js";
9
+ import { slash } from "../utils/paths.js";
10
+ import { proxyToVite } from "../config/index.js";
11
+ import { getRenderer } from "../renderer.js";
12
+ import { SSR_BUILD_DIR } from "../cache-layout.js";
13
+ import { nodeModulesPluginNames, nodeModulesPlugins, nonSourceNodeModulesRe } from "./source-files.js";
14
+ import { pluginCommonJsDeps } from "./plugin-deps.js";
15
+ import path from "node:path";
16
+ import { mergeConfig } from "vite";
17
+ import react from "@vitejs/plugin-react";
18
+ // src/node/vite/config.ts
19
+ /** Values exposed to the bundle like Gatsby's DefinePlugin globals. */
20
+ function getDefines(stage) {
21
+ const { config, program } = store.getState();
22
+ const prefixPaths = program.prefixPaths;
23
+ const basePath = prefixPaths && config.pathPrefix || "";
24
+ const assetPrefix = prefixPaths && config.assetPrefix || "";
25
+ const pathPrefix = assetPrefix ? `${assetPrefix}${basePath}` : basePath;
26
+ const defines = {
27
+ __PATH_PREFIX__: JSON.stringify(pathPrefix),
28
+ __BASE_PATH__: JSON.stringify(basePath),
29
+ __ASSET_PREFIX__: JSON.stringify(assetPrefix),
30
+ __TRAILING_SLASH__: JSON.stringify(config.trailingSlash),
31
+ __PREFETCH__: JSON.stringify(config.prefetch ?? "viewport"),
32
+ "process.env.BUILD_STAGE": JSON.stringify(stage),
33
+ "process.env.GATSBY_SLICES": JSON.stringify(false),
34
+ __DEV__: JSON.stringify(!stage.startsWith("build"))
35
+ };
36
+ for (const [key, value] of Object.entries(process.env)) if (key.startsWith("GATSBY_") && value !== void 0) defines[`process.env.${key}`] = JSON.stringify(value);
37
+ return defines;
38
+ }
39
+ /**
40
+ * Compatibility shim for `onCreateWebpackConfig`: plugins are called with webpack-like
41
+ * helpers and the parts of the config that have a Vite equivalent (resolve.alias,
42
+ * DefinePlugin definitions) are translated. Everything else is ignored.
43
+ */
44
+ async function runWebpackCompat(stage) {
45
+ if (store.getState().flattenedPlugins.filter((p) => p.nodeAPIs.includes("onCreateWebpackConfig")).length === 0) return {
46
+ alias: {},
47
+ define: {}
48
+ };
49
+ store.dispatch({
50
+ type: "REPLACE_WEBPACK_CONFIG",
51
+ payload: {}
52
+ });
53
+ const marker = (kind) => (...args) => ({
54
+ __goatlyWebpackPlugin: kind,
55
+ args
56
+ });
57
+ const rule = (kind) => (options = {}) => ({
58
+ __goatlyRule: kind,
59
+ options
60
+ });
61
+ const pluginsHelper = new Proxy({}, { get: (_t, kind) => marker(kind) });
62
+ const rulesHelper = new Proxy({}, { get: (_t, kind) => rule(kind) });
63
+ const loadersHelper = new Proxy({}, { get: (_t, kind) => (options) => ({
64
+ loader: kind,
65
+ options
66
+ }) });
67
+ const config = {
68
+ mode: stage.startsWith("build") ? "production" : "development",
69
+ resolve: {
70
+ alias: {},
71
+ extensions: []
72
+ },
73
+ module: { rules: [] },
74
+ plugins: []
75
+ };
76
+ await apiRunnerNode("onCreateWebpackConfig", {
77
+ stage,
78
+ getConfig: () => config,
79
+ rules: rulesHelper,
80
+ loaders: loadersHelper,
81
+ plugins: pluginsHelper
82
+ });
83
+ const webpack = store.getState().webpack;
84
+ const alias = {};
85
+ const define = {};
86
+ const rawAlias = webpack?.resolve?.alias;
87
+ if (rawAlias && typeof rawAlias === "object" && !Array.isArray(rawAlias)) {
88
+ for (const [k, v] of Object.entries(rawAlias)) if (typeof v === "string") alias[k.replace(/\$$/, "")] = v;
89
+ }
90
+ for (const p of webpack?.plugins ?? []) if (p?.__goatlyWebpackPlugin === "define" && p.args?.[0]) Object.assign(define, p.args[0]);
91
+ else if (p?.definitions) Object.assign(define, p.definitions);
92
+ const ignored = Object.keys(webpack ?? {}).filter((k) => !["resolve", "plugins"].includes(k));
93
+ if (ignored.length) reporter.verbose(`onCreateWebpackConfig: ignoring webpack-only settings (${ignored.join(", ")})`);
94
+ return {
95
+ alias,
96
+ define
97
+ };
98
+ }
99
+ async function runViteConfigApi(stage, base) {
100
+ const results = await apiRunnerNode("onCreateViteConfig", {
101
+ stage,
102
+ getConfig: () => base
103
+ });
104
+ let merged = base;
105
+ for (const r of results) if (r && typeof r === "object") merged = mergeConfig(merged, r);
106
+ return merged;
107
+ }
108
+ /** Aliases from onCreateWebpackConfig, except for specifiers the renderer provides. */
109
+ function webpackAliases(aliases, owned, rendererName) {
110
+ return Object.entries(aliases).filter(([find]) => {
111
+ if (!owned?.includes(find)) return true;
112
+ reporter.verbose(`onCreateWebpackConfig: ignoring the alias for "${find}" (the renderer "${rendererName}" provides it)`);
113
+ return false;
114
+ }).map(([find, replacement]) => ({
115
+ find,
116
+ replacement
117
+ }));
118
+ }
119
+ async function createViteConfig({ stage, ctx }) {
120
+ const { config, program } = store.getState();
121
+ const directory = program.directory;
122
+ const isBuild = stage.startsWith("build");
123
+ const isSSR = stage === "build-html" || stage === "develop-html";
124
+ const prefix = program.prefixPaths ? `${config.assetPrefix || ""}${config.pathPrefix || ""}` : "";
125
+ const webpackCompat = await runWebpackCompat(stage);
126
+ await apiRunnerNode("onCreateBabelConfig", { stage });
127
+ const styledComponentsBabel = findStyledComponentsBabelOptions(stage);
128
+ const staticImageBabel = findStaticImageBabelPlugin(stage);
129
+ const renderer = getRenderer();
130
+ const rendererConfig = await renderer.vite?.({
131
+ stage,
132
+ isBuild,
133
+ root: directory
134
+ }) ?? {};
135
+ const alias = [
136
+ {
137
+ find: /^gatsby$/,
138
+ replacement: runtimeIndex
139
+ },
140
+ {
141
+ find: /^gatsby-link$/,
142
+ replacement: runtimeIndex
143
+ },
144
+ {
145
+ find: /^gatsby-script$/,
146
+ replacement: runtimeIndex
147
+ },
148
+ {
149
+ find: /^goatly$/,
150
+ replacement: runtimeIndex
151
+ },
152
+ {
153
+ find: /^@reach\/router$/,
154
+ replacement: routerIndex
155
+ },
156
+ {
157
+ find: /^@gatsbyjs\/reach-router$/,
158
+ replacement: routerIndex
159
+ },
160
+ {
161
+ find: /^goatly\/router$/,
162
+ replacement: routerIndex
163
+ },
164
+ {
165
+ find: /^(?:goatly|gatsby)\/runtime\/(.+?)(?:\.js)?$/,
166
+ replacement: `${slash(runtimeDir)}/$1.js`
167
+ },
168
+ ...webpackAliases(webpackCompat.alias, rendererConfig.ownedSpecifiers, renderer.name)
169
+ ];
170
+ const dirRe = (dir) => new RegExp(`^${slash(dir).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/`);
171
+ const runtimeRe = dirRe(runtimeDir);
172
+ const rendererRuntimeRes = [...new Set(Object.values(renderer.runtime).map((file) => path.dirname(file)))].map(dirRe);
173
+ const reactCompilerOptions = await resolveReactCompiler(stage, renderer.name);
174
+ const reactCompiler = reactCompilerOptions ? await createReactCompilerTransform(reactCompilerOptions, directory) : void 0;
175
+ const pluginDeps = isBuild ? void 0 : pluginCommonJsDeps(nodeModulesPlugins(), directory);
176
+ const reactPlugin = react({
177
+ jsxRuntime: config.jsxRuntime,
178
+ jsxImportSource: config.jsxImportSource,
179
+ include: /\.(mdx|[jt]sx?|mjs)$/,
180
+ exclude: [
181
+ /\/node_modules\//,
182
+ runtimeRe,
183
+ ...rendererRuntimeRes
184
+ ]
185
+ });
186
+ let viteConfig = {
187
+ configFile: false,
188
+ root: directory,
189
+ base: `${prefix}/`,
190
+ mode: isBuild ? "production" : "development",
191
+ publicDir: path.join(directory, "static"),
192
+ cacheDir: path.join(program.cacheDir, "vite"),
193
+ logLevel: process.env.GOATLY_VITE_LOG ? "info" : "warn",
194
+ clearScreen: false,
195
+ appType: "custom",
196
+ envPrefix: ["GATSBY_", "VITE_"],
197
+ define: {
198
+ ...getDefines(stage),
199
+ ...webpackCompat.define
200
+ },
201
+ resolve: {
202
+ alias,
203
+ dedupe: rendererConfig.dedupe
204
+ },
205
+ oxc: {
206
+ include: /\.(m?ts|[jt]sx)$/,
207
+ exclude: [nonSourceNodeModulesRe(), runtimeRe],
208
+ jsx: {
209
+ runtime: config.jsxRuntime === "classic" ? "classic" : "automatic",
210
+ importSource: config.jsxImportSource
211
+ }
212
+ },
213
+ plugins: [
214
+ ...staticImageBabel ? [staticImagePlugin(staticImageBabel)] : [],
215
+ goatlyVitePlugin({
216
+ ...ctx,
217
+ jsxRuntime: config.jsxRuntime,
218
+ jsxImportSource: config.jsxImportSource,
219
+ reactCompiler,
220
+ precompiledDirs: [runtimeRe, ...rendererRuntimeRes]
221
+ }),
222
+ ...styledComponentsBabel ? [styledComponentsPlugin(styledComponentsBabel)] : [],
223
+ reactPlugin,
224
+ ...rendererConfig.plugins ?? []
225
+ ],
226
+ optimizeDeps: {
227
+ exclude: [
228
+ "goatly",
229
+ "gatsby",
230
+ VIRTUAL.renderer,
231
+ VIRTUAL.rendererServer,
232
+ VIRTUAL.rendererClient,
233
+ ...nodeModulesPluginNames()
234
+ ],
235
+ entries: [],
236
+ include: pluginDeps
237
+ },
238
+ server: {
239
+ middlewareMode: true,
240
+ hmr: true,
241
+ watch: { ignored: [
242
+ "**/.cache/**",
243
+ "**/public/**",
244
+ "**/*.goatly-*.mjs"
245
+ ] },
246
+ proxy: stage === "develop" ? proxyToVite(config.proxy) : void 0
247
+ },
248
+ ssr: {
249
+ noExternal: isBuild ? true : nodeModulesPluginNames(),
250
+ external: rendererConfig.ssrExternal
251
+ },
252
+ build: isSSR ? {
253
+ ssr: ssrEntry,
254
+ outDir: path.join(program.cacheDir, SSR_BUILD_DIR),
255
+ emptyOutDir: true,
256
+ copyPublicDir: false,
257
+ minify: false,
258
+ sourcemap: false,
259
+ reportCompressedSize: false,
260
+ rolldownOptions: { output: {
261
+ format: "esm",
262
+ entryFileNames: "render-page.mjs",
263
+ chunkFileNames: "chunks/[name]-[hash].mjs"
264
+ } }
265
+ } : {
266
+ outDir: program.publicDir,
267
+ emptyOutDir: false,
268
+ manifest: true,
269
+ assetsDir: "assets",
270
+ sourcemap: false,
271
+ reportCompressedSize: false,
272
+ modulePreload: { polyfill: false },
273
+ rolldownOptions: { input: { app: clientEntry } }
274
+ }
275
+ };
276
+ if (config.vite) {
277
+ const user = typeof config.vite === "function" ? await config.vite({
278
+ command: isBuild ? "build" : "serve",
279
+ stage
280
+ }) : config.vite;
281
+ if (user) viteConfig = mergeConfig(viteConfig, user);
282
+ }
283
+ viteConfig = await runViteConfigApi(stage, viteConfig);
284
+ return viteConfig;
285
+ }
286
+ function pageComponentEntries() {
287
+ return [...store.getState().components.keys()].map((c) => slash(c.split("?")[0]));
288
+ }
289
+ export { createViteConfig, getDefines, pageComponentEntries };
@@ -0,0 +1,12 @@
1
+ import path from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ // src/node/vite/paths.ts
4
+ const here = path.dirname(fileURLToPath(import.meta.url));
5
+ /** `dist/` (or `src/` when running from source in tests) */
6
+ const packageSrcRoot = path.resolve(here, "../..");
7
+ const runtimeDir = path.join(packageSrcRoot, "runtime");
8
+ const clientEntry = path.join(runtimeDir, "client-entry.js");
9
+ const ssrEntry = path.join(runtimeDir, "ssr.js");
10
+ const runtimeIndex = path.join(runtimeDir, "index.js");
11
+ const routerIndex = path.join(runtimeDir, "router", "index.js");
12
+ export { clientEntry, packageSrcRoot, routerIndex, runtimeDir, runtimeIndex, ssrEntry };