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
package/README.md CHANGED
@@ -1,3 +1,855 @@
1
1
  # goatly
2
2
 
3
- This version is an empty placeholder: it has no code. goatly is part of goatly and has no release yet.
3
+ A Gatsby-compatible static site generator built on **Vite 8 (Rolldown)**, **oxc** and **React 18 or 19**.
4
+
5
+ goatly implements Gatsby 5's **Node, SSR and Browser APIs with the same method signatures** (the
6
+ lifecycle, actions, node helpers, GraphQL data layer, `gatsby` exports, page creator and File System
7
+ Route API, Head API, `<Script>`, `gatsby/graphql`, reporter …). Existing sites and unmodified npm
8
+ Gatsby plugins (`gatsby-source-filesystem`, `gatsby-transformer-remark`, `gatsby-plugin-sitemap`, …) run
9
+ on it.
10
+
11
+ It only produces static sites (SSG). In development the requested page is server-rendered
12
+ through Vite and hydrated.
13
+
14
+ Pages render with react-dom 18 or 19. [TanStack Redact](https://github.com/TanStack/redact) can render
15
+ them instead, opt-in and experimental, with
16
+ [`@goatly/redact`](../goatly-redact): smaller browser bundles and faster hydration.
17
+
18
+ ```bash
19
+ # in an existing Gatsby site: install goatly under the name "gatsby"
20
+ npm pkg set 'overrides.gatsby=$gatsby' # for the Gatsby plugins' peer dependency (see Setup)
21
+ npm install gatsby@npm:goatly react@19 react-dom@19 # or react@18 react-dom@18
22
+ npx gatsby develop # or: gatsby build / gatsby serve / gatsby clean
23
+ ```
24
+
25
+ ## What is different from Gatsby
26
+
27
+ | | Gatsby 5 | goatly |
28
+ | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
29
+ | Bundler | webpack (+ Babel) | Vite 8 / Rolldown, oxc transforms, **no Babel, no webpack** |
30
+ | `gatsby-config` / `gatsby-node` | CommonJS; TS/ESM only via workarounds (`.mjs`, compiled TS) | **TypeScript and ESM first-class** (`.ts`, `.mts`, `.tsx`, `.mjs`, `.js`, `.cjs`), incl. enums, extensionless imports, `__dirname`/`import.meta.dirname` |
31
+ | Plugins written in TypeScript | Plugin's `gatsby-*` files must be published as compiled JS: plugin loader only looks for `.js`/`.mjs`/`.cjs` | **Loaded from TypeScript sources**, also from npm (`node_modules`): `gatsby-config.ts`, `gatsby-node.ts`, `gatsby-ssr.tsx`, `gatsby-browser.ts`, `gatsby-worker.ts`, `.tsx` templates and JSX in `.js` files, in `build` and `develop` |
32
+ | Runtime | Node.js (Bun only by running Node) | **Node.js 22 (≥ 22.22.3), 24 (≥ 24.11.1) or newer and Bun (tested with 1.4) natively** (`bun --bun gatsby build`) |
33
+ | Node storage | LMDB (hard-coded) | **Pluggable `datastore`**: by default append-only segment files read through the OS page cache; memory and SQLite stores |
34
+ | Plugin cache | LMDB | Built-in SQLite (`node:sqlite` / `bun:sqlite`), shared by all workers, with no native deps |
35
+ | CSS | CSS Modules, PostCSS, … built in | Whatever Vite does (CSS Modules via `*.module.css`, PostCSS, Sass if installed). Nothing is forced. |
36
+ | Dev server | webpack-dev-server; DEV_SSR renders a **different tree** than the client, so `React.useId()` mismatches | Vite with HMR and React Fast Refresh. Dev SSR and hydration render the **same component tree**, so `useId` matches and there are no hydration warnings |
37
+ | Data changes in develop | websocket refresh | Schema/pages/queries recomputed and pushed over Vite HMR; the page updates **without reload** |
38
+ | React | 18; React 19 via workarounds (`createElement` patching for `Head`) | **18 and 19**. React 19: `Head` renders in the React tree and React hoists it into `<head>`. React 18: rendered separately on the server and synced into `<head>` in the browser, like Gatsby 5 |
39
+ | Browsers | browserslist + polyfills | Modern browsers only (Vite's `baseline-widely-available`), ES modules, `modulepreload` |
40
+ | Rebuilds | incremental queries (page dependency tracking), HTML of changed pages | The same: incremental query running and incremental HTML. With nothing to do, no worker threads are started |
41
+ | `<Script>` | `post-hydrate`, `idle`, `off-main-thread` (Partytown) | `post-hydrate` and `idle`. No Partytown: `off-main-thread` scripts run on the main thread like `idle` |
42
+ | `<Link>` prefetching | Visible links (page-data, JS/CSS) and the whole page on `mouseenter`, right away; nothing on keyboard focus or touch; turned off only by a plugin (`disableCorePrefetching`) | The same by default, plus focus and press (touch screens), and hover after 50 ms. **`prefetch: "viewport" \| "intent" \| false`** in gatsby-config and as a `<Link>` prop; the page-data request of a page whose last link scrolls out of view is cancelled |
43
+ | `<Link>` customization | Only by wrapping it; `getProps` replaces `activeClassName`; links of plugins and themes can't be changed | **`as` prop**, headless **`useLink()`** hook, **`<LinkProvider>`** for site-wide defaults or a replacement of every `<Link>` (see [Customizing `Link`](#customizing-link)) |
44
+ | GraphQL types | `graphqlTypegen` (opt-in): GraphQL Code Generator writes `Queries.*` types, which have to be used by name | **gql.tada built in**: TypeScript infers the result of `graphql(\`...\`)`queries from the site's schema, and tags get`QueryResult<"Name">` |
45
+ | 404 pages | One: `src/pages/404` (`/404.html`) for every unknown URL | **One per site section** (e.g. per language) with `notFoundPages`, in `develop`, `serve`, the build output and client-side navigation; without it, Gatsby's single 404 page |
46
+
47
+ ## Performance
48
+
49
+ A site of 20,000 Markdown posts (21,022 pages, `gatsby-source-filesystem` and
50
+ `gatsby-transformer-remark`, [`examples/benchmark`](../../examples/benchmark)) on a 4-core / 15 GB Linux
51
+ machine, Gatsby 5.16.1 against goatly with its defaults:
52
+
53
+ | 21,022 pages | Gatsby 5.16.1 | goatly on Node | goatly on Bun |
54
+ | -------------------------------------------------- | ------------: | -----------------------: | -----------------------: |
55
+ | **Cold build** (no `.cache`, `public`) | **125.2 s** | **59.3 s** (2.1× faster) | **44.4 s** (2.8× faster) |
56
+ | **Warm build**, nothing changed | **23.6 s** | **4.3 s** (5.4× faster) | **3.8 s** (6.2× faster) |
57
+ | **Warm build**, one post edited | **31.0 s** | **7.7 s** (4.0× faster) | **6.0 s** (5.1× faster) |
58
+ | **Warm build**, post template edited (code change) | **34.1 s** | **10.7 s** (3.2× faster) | **7.0 s** (4.9× faster) |
59
+
60
+ Peak memory (PSS) of a cold build: 4,245 MB with Gatsby, 1,057 MB with goatly on Node and
61
+ 1,592 MB on Bun. More in [Benchmarks](../../docs/benchmarks.md):
62
+
63
+ - [100k+ pages](../../docs/benchmarks.md#large-sites-100k-pages): a cold build of 105,022 pages takes 274 s
64
+ on Node (198 s on Bun) and 1.8 GB, a warm build 21 s.
65
+ - [Data from an API](../../docs/benchmarks.md#data-from-an-api): the same posts from a REST API build cold
66
+ in 11.7 s, and in 28 s with 33 KB pages that reference each other
67
+ ([large profile](../../docs/benchmarks.md#bigger-pages-the-large-profile)).
68
+ - [Page queries](../../docs/benchmarks.md#page-queries) alone, with the compiled query execution.
69
+
70
+ On large sites, query workers follow the memory that is free now (an adaptive pool;
71
+ `GOATLY_WORKERS=<n>` starts a fixed number). The heap limits, budgets and the
72
+ `GOATLY_*` settings that change them:
73
+ [Architecture: memory and the worker pool](../../docs/architecture-memory.md).
74
+
75
+ ### Why it is faster
76
+
77
+ Rolldown builds the bundles **while** page queries run, parallel query workers render the pages
78
+ they queried, a compiled query engine (and **page queries in WebAssembly**) replaces graphql-js'
79
+ `execute`, and incremental query running and incremental HTML skip what didn't change. How each of
80
+ them works: [Architecture: the build pipeline](../../docs/architecture-build-pipeline.md#why-it-is-faster).
81
+
82
+ ## Setup
83
+
84
+ ### Drop-in (recommended)
85
+
86
+ Install goatly **as `gatsby`** so that `import { Link } from "gatsby"`, `gatsby/graphql`, types
87
+ and the `gatsby` CLI resolve to it:
88
+
89
+ ```json
90
+ {
91
+ "dependencies": {
92
+ "gatsby": "npm:goatly@^0.1.1",
93
+ "react": "^19.0.0",
94
+ "react-dom": "^19.0.0"
95
+ },
96
+ "overrides": {
97
+ "gatsby": "$gatsby"
98
+ }
99
+ }
100
+ ```
101
+
102
+ React 18 works too (`"react": "^18.0.0"`, `"react-dom": "^18.0.0"`).
103
+
104
+ `overrides` is for npm. Official Gatsby plugins declare a peer dependency on `gatsby@^5`, which
105
+ goatly's version (0.1.1) does not satisfy; `"$gatsby"` resolves those peer dependencies to
106
+ the `gatsby` of `dependencies`. Without it `npm install` stops with `ERESOLVE`, or, in a site that
107
+ has a `package-lock.json`, only warns and writes a lockfile that the next `npm install` and `npm ci`
108
+ reject. (`--legacy-peer-deps` works too, but it has to be given on every install or set in
109
+ `.npmrc`, and it turns off npm's peer dependency handling for the whole tree.)
110
+
111
+ pnpm 11 and later fail the install (`ERR_PNPM_IGNORED_BUILDS`) while dependencies with install
112
+ scripts are neither allowed nor denied: `msgpackr-extract` (msgpackr's optional native decoder) and
113
+ `lmdb` (a dependency of `gatsby-core-utils`, which Gatsby plugins use).
114
+ Both install prebuilt binaries as optional dependencies, so their scripts need not run. In
115
+ `pnpm-workspace.yaml`:
116
+
117
+ ```yaml
118
+ allowBuilds:
119
+ lmdb: false
120
+ msgpackr-extract: false
121
+ peerDependencyRules:
122
+ allowAny: [gatsby] # the Gatsby plugins' peer dependency (otherwise pnpm warns)
123
+ ```
124
+
125
+ (pnpm 10 only warns; it reads `allowBuilds` from 10.26 on.) Yarn and Bun need neither: Yarn warns
126
+ about the peer dependency, Bun skips the install scripts (except sharp's, which it trusts by default).
127
+
128
+ Sites with gatsby-plugin-sharp or gatsby-plugin-manifest also need `sharp: true` in `allowBuilds`
129
+ (pnpm 10 before 10.26: `onlyBuiltDependencies: [sharp]`): the sharp 0.32 they pin downloads its
130
+ libvips in its install script. When the script doesn't run, the build fails with `Something went
131
+ wrong installing the "sharp" module`. Yarn 4 needs the version in the alias:
132
+ `yarn add gatsby@npm:goatly@^0.1.1`.
133
+
134
+ (pnpm workspaces: `"gatsby": "workspace:goatly@*"`, see [`examples/blog`](../../examples/blog).)
135
+
136
+ Without the alias it also works: install `goatly` and run the `goatly` CLI. Inside the
137
+ bundles `gatsby`, `gatsby-link`, `gatsby-script`, `@reach/router` and `@gatsbyjs/reach-router` are
138
+ aliased automatically. For Node plugins, `require("gatsby/…")` is redirected by a module resolution hook
139
+ (`module.registerHooks` on Node, `Module._resolveFilename` on Bun).
140
+
141
+ ### Requirements
142
+
143
+ - Node.js 22 (≥ 22.22.3), 24 (≥ 24.11.1) or newer, or Bun (tested with 1.4)
144
+ - React 18 or 19 (`react`, `react-dom`)
145
+
146
+ ### CLI
147
+
148
+ ```
149
+ gatsby develop [-H host] [-p port] # dev server with SSR + HMR, GraphiQL at /___graphql
150
+ gatsby build [--prefix-paths] # static build into public/
151
+ gatsby serve [-p port] # serve public/ (client-only routes + 404 pages)
152
+ gatsby clean # delete .cache and public
153
+ gatsby info [--json] # environment report for bug reports
154
+ gatsby --version
155
+ ```
156
+
157
+ `gatsby info` prints the goatly, runtime and OS versions, memory and the heap limit (and where
158
+ it comes from), the site's gatsby-* files, the size of `.cache` and `public`,
159
+ the installed versions of React, Vite, TypeScript and the site's gatsby plugins next to the ranges in
160
+ `package.json`, and the `GOATLY_*`, `NODE_OPTIONS`, `BUN_OPTIONS` and `BUN_JSC_*` settings. It doesn't load gatsby-config, prints the home
161
+ directory as `~` and leaves out `GATSBY_*` variables (they often hold API keys), so the report can be
162
+ pasted into an issue. Unknown commands get a "did you mean" hint and unknown options a warning.
163
+
164
+ With Bun: `bun --bun gatsby build` (gatsby-config/gatsby-node are then loaded by Bun itself).
165
+
166
+ ## goatly specific configuration
167
+
168
+ ```ts
169
+ // gatsby-config.ts
170
+ import type { GatsbyConfig } from "gatsby"
171
+
172
+ const config: GatsbyConfig = {
173
+ // ... all Gatsby options ...
174
+ datastore: sqliteDataStore(), // node storage (see "Node datastore"), default: logFileDataStore()
175
+ reporter: loggerTransport(logger), // where log output goes (see "Logging")
176
+ vite: { css: { preprocessorOptions: { scss: {} } } }, // merged into the Vite config
177
+ renderWorkers: 3, // worker threads for queries + HTML (default: cores - 1)
178
+ parallelQueryRunning: true, // default: on when 500+ queries (2,000+ on large sites) have to run
179
+ inlineCss: false, // Gatsby inlines CSS; goatly links it by default
180
+ inlinePageData: false, // inline page-data into the HTML
181
+ devSSR: true, // server-render in develop
182
+ renderer: undefined, // react-dom 18/19 (default); e.g. redact() from @goatly/redact (experimental)
183
+ gqlTada: undefined, // types for graphql() and QueryResult<"Name">: by default for TypeScript sites using them (see below)
184
+ notFoundPages: ["/de", "/fr"], // 404 pages of site sections (see "Multiple 404 pages")
185
+ prefetch: "viewport", // when <Link> prefetches pages: "viewport" (default, like Gatsby), "intent" or false
186
+ reactCompiler: true, // React Compiler without Babel (Oxc's port, experimental; see "React Compiler")
187
+ }
188
+ export default config
189
+ ```
190
+
191
+ Plugins can extend the Vite config with the `onCreateViteConfig({ stage, getConfig })` Node API. It
192
+ returns a partial config that gets merged.
193
+
194
+ `renderer` names what turns the React elements into HTML and DOM, instead of react-dom: the value a
195
+ renderer package's function returns, such as `redact()` from
196
+ [`@goatly/redact`](../goatly-redact). The renderer interface (`Renderer`, `RendererServer`,
197
+ `RendererClient`, … in `goatly/node`) is experimental and may change between versions.
198
+
199
+ ### Link prefetching
200
+
201
+ Like Gatsby, `<Link>` prefetches the pages it links to once the link is visible: their page-data and
202
+ the JS/CSS of their component (`<link rel=prefetch>`, nothing runs), four pages at a time every 3 s
203
+ when the browser is idle. A page is no longer prefetched when its last visible link scrolls out of
204
+ view, also while its page-data is downloading. On intent the whole page is loaded, ready to render:
205
+ when the pointer stays on a link for 50 ms (Gatsby: right away, on every link the mouse passes over),
206
+ when the link gets focus (keyboard) and when it is pressed (touch screens have no hover). Nothing is
207
+ prefetched for visitors with Save-Data or a 2G connection.
208
+
209
+ Sites whose page-data is large (e.g. list pages linking to many Markdown posts) can prefetch on
210
+ intent only, for the whole site or for single links:
211
+
212
+ ```ts
213
+ // gatsby-config.ts
214
+ prefetch: "intent", // "viewport" (default), "intent" or false
215
+ ```
216
+
217
+ ```tsx
218
+ <Link to="/archive/" prefetch={false}>Archive</Link> {/* never prefetched */}
219
+ <Link to="/blog/" prefetch="viewport">Blog</Link> {/* overrides the site's option */}
220
+ ```
221
+
222
+ `prefetchPathname()` and the `onPrefetchPathname`, `onPostPrefetchPathname` and
223
+ `disableCorePrefetching` Browser APIs work as in Gatsby with every option.
224
+
225
+ ### Customizing `Link`
226
+
227
+ `<Link>` works like Gatsby's. On top of that it can be adjusted at three levels, from a single link
228
+ to every link of the site (also the links of plugins and themes, which a wrapper component can't
229
+ reach):
230
+
231
+ **A single link: `as` and `prefetch`.** `as` renders another element or component than `<a>`. It
232
+ gets `href`, `onClick`, `onMouseEnter`, `onMouseLeave`, `onFocus`, `onPointerDown`, `aria-current` and `className`/`style` with the
233
+ active ones, and the other props of the `<Link>` (typed by the component's props):
234
+
235
+ ```tsx
236
+ import { Link } from "gatsby"
237
+ import { Button } from "@mui/material"
238
+
239
+ ;<Link to="/pricing/" as={Button} variant="contained" prefetch="intent">
240
+ Pricing
241
+ </Link>
242
+ ```
243
+
244
+ `prefetch` overrides the site's option for this link (see [Link prefetching](#link-prefetching)).
245
+ For `"viewport"` the component has to forward its `ref` to the DOM element.
246
+
247
+ **Your own link component: `useLink()`.** The hook has all of `<Link>`'s behavior without its
248
+ markup: path prefix, `trailingSlash`, relative paths, active state, prefetching and client-side
249
+ navigation (plain left clicks without a `target`). Spread `linkProps` on anything that renders an
250
+ `<a>`, and use the state for whatever the design needs (no `getProps` that overrides
251
+ `activeClassName`):
252
+
253
+ ```tsx
254
+ import { useLink } from "gatsby"
255
+
256
+ function NavItem({ to, children }: { to: string; children: React.ReactNode }) {
257
+ const { linkProps, isActive } = useLink({ to, partiallyActive: true })
258
+ return (
259
+ <a {...linkProps} className={isActive ? "nav-item nav-item--active" : "nav-item"}>
260
+ {isActive && <Indicator />}
261
+ {children}
262
+ </a>
263
+ )
264
+ }
265
+ ```
266
+
267
+ It takes `to`, `state`, `replace`, `partiallyActive`, `prefetch`, `target` and the handlers to chain
268
+ (`onClick`, `onMouseEnter`, `onMouseLeave`, `onFocus`, `onPointerDown`), and a `ref` to merge as the second argument. It returns
269
+ `href`, `isCurrent`, `isPartiallyCurrent`, `isActive`, `isExternal`, `location` and `linkProps`.
270
+
271
+ **Every link: `<LinkProvider>`.** Defaults for `prefetch`, `activeClassName`, `activeStyle` and
272
+ `partiallyActive`, or a `component` that renders every `<Link>` below it. A `<Link>` that this
273
+ component renders is the built-in one, so it can wrap it, e.g. to add a locale prefix:
274
+
275
+ ```tsx
276
+ // gatsby-browser.tsx and gatsby-ssr.tsx
277
+ import { forwardRef } from "react"
278
+ import { Link, LinkProvider, type GatsbyLinkProps, type GatsbyBrowser } from "gatsby"
279
+
280
+ const LocalizedLink = forwardRef<HTMLAnchorElement, GatsbyLinkProps>((props, ref) => {
281
+ const locale = useLocale()
282
+ const to = props.to.startsWith("/") ? `/${locale}${props.to}` : props.to
283
+ return <Link {...props} to={to} ref={ref} />
284
+ })
285
+
286
+ export const wrapRootElement: GatsbyBrowser["wrapRootElement"] = ({ element }) => (
287
+ <LinkProvider component={LocalizedLink} activeClassName="active" prefetch="intent">
288
+ {element}
289
+ </LinkProvider>
290
+ )
291
+ ```
292
+
293
+ A provider's `prefetch` overrides gatsby-config's `prefetch` for the links below it. Providers can be nested (the inner one overrides the values it sets), e.g. `prefetch={false}` for a
294
+ long list of links. A link's own props win over the provider's defaults. `useLinkConfig()` returns
295
+ the merged configuration. `navigate()` is not affected by `LinkProvider`.
296
+
297
+ ### React Compiler
298
+
299
+ [React Compiler](https://react.dev/learn/react-compiler) runs without Babel, with Oxc's Rust port of it
300
+ (experimental). Install [`oxc-transform-react`](https://www.npmjs.com/package/oxc-transform-react), and
301
+ on React 18 also `react-compiler-runtime`, then turn it on in gatsby-config:
302
+
303
+ ```bash
304
+ npm install -D oxc-transform-react
305
+ ```
306
+
307
+ ```ts
308
+ // gatsby-config.ts
309
+ const config: GatsbyConfig = {
310
+ reactCompiler: true, // or an object with React Compiler's options:
311
+ // reactCompiler: { compilationMode: "annotation", panicThreshold: "critical_errors" },
312
+ }
313
+ ```
314
+
315
+ A site that already uses `babel-plugin-react-compiler` in its `.babelrc` or `babel.config.*` (or a
316
+ plugin that registers it with `setBabelPlugin`) needs no option: its options are used, and options
317
+ the port has no equivalent for (`logger`, function-valued `environment` settings) are ignored with a
318
+ warning. `reactCompiler: false` turns it off in any case.
319
+
320
+ - **What is compiled**: the site's sources (also JSX in `.js` files) and linked workspace packages,
321
+ but nothing in `node_modules` (React Compiler's default, as with the Babel plugin), so gatsby
322
+ themes and npm plugins only with `sources`: substrings of the path (replacing the default), or a
323
+ function, e.g. `sources: (file) => !file.includes("/node_modules/") || file.includes("/gatsby-theme-")`.
324
+ - **Target**: the installed React (`target: "18"` imports `react-compiler-runtime`); 19 with another
325
+ `renderer` such as Redact, which provides `react/compiler-runtime`.
326
+ - **`outputMode`**: `"client"` (default) uses the compiled output in the browser and the SSR bundle.
327
+ `"ssr"` gives the SSR bundle React Compiler's server output (no memoization, no event handlers or
328
+ effects) and the browser the compiled one. `"lint"` leaves the code unchanged and only prints React
329
+ Compiler's diagnostics: a way to find the components it would skip before turning it on.
330
+ - **Diagnostics** (rule violations, components React Compiler skipped) are printed with
331
+ `reportDiagnostics: true` (on by default in lint mode), once per file and change, with a code
332
+ frame. With `panicThreshold: "critical_errors"` or `"all_errors"`, they fail the build.
333
+ - **Fast Refresh** works with compiled components in `develop`: edits show and state is kept.
334
+ - Compiled files get their TypeScript removed by Oxc's port, not by Vite with the tsconfig's
335
+ settings. Files React Compiler does not change are left to Vite.
336
+
337
+ ### Typed GraphQL (gql.tada)
338
+
339
+ TypeScript can't type Gatsby's `graphql` tagged templates. In goatly, `graphql` is also a
340
+ function, in [gql.tada](https://gql-tada.0no.co)'s form, and TypeScript infers the result of a
341
+ query from the query and the site's schema:
342
+
343
+ ```tsx
344
+ import { graphql, useStaticQuery, type PageProps, type ResultOf } from "gatsby"
345
+
346
+ export default function BlogPost({ data }: PageProps<ResultOf<typeof query>>) {
347
+ return <h1>{data.markdownRemark?.frontmatter?.title}</h1> // string (`title: String!`)
348
+ }
349
+
350
+ export const query = graphql(`
351
+ query BlogPost($id: String!) {
352
+ markdownRemark(id: { eq: $id }) {
353
+ frontmatter {
354
+ title
355
+ }
356
+ ...PostLink
357
+ }
358
+ }
359
+ `)
360
+
361
+ function Seo() {
362
+ const { site } = useStaticQuery(
363
+ graphql(`
364
+ {
365
+ site {
366
+ siteMetadata {
367
+ title
368
+ }
369
+ }
370
+ }
371
+ `),
372
+ )
373
+ // site: { siteMetadata: { title: string | null } | null } | null
374
+ }
375
+ ```
376
+
377
+ - `graphql()` calls are extracted and compiled away like the tags: page queries, static queries
378
+ (`useStaticQuery`, `<StaticQuery>`) and fragments, with the same hashes. Only `graphql` imported
379
+ from `"gatsby"` is compiled – not gql.tada's own `graphql`, e.g. for a client of another API. The
380
+ query must be a string literal (no `${...}`); anything else is a build error.
381
+ - Fragments are global, as in Gatsby: every fragment of the site, its plugins and `.cache/fragments`
382
+ can be spread by name. Fragment documents can also be passed as the second argument, as in gql.tada
383
+ (`graphql(query, [PostLink])`), for the types: the build finds fragments by their names, which are
384
+ global and unique, in the files it scans (`src/` of the site and its plugins). Fragments are not
385
+ masked: results contain their fields, like the data.
386
+ - `ResultOf<typeof query>` and `VariablesOf<typeof query>` (exported by `"gatsby"`) give the types of
387
+ a query's data and variables: `PageProps<ResultOf<typeof query>>`,
388
+ `HeadProps<ResultOf<typeof query>>`. `useStaticQuery` and `<StaticQuery>` infer their data, and
389
+ documents are `StaticQueryDocument`s. Explicit types (`useStaticQuery<Data>(…)`, `PageProps<Data>`)
390
+ still win, and tagged templates keep their untyped results.
391
+ - Gatsby's tags get types by the names of their queries and fragments: `QueryResult<"Name">`,
392
+ `QueryVariables<"Name">` and `FragmentResult<"Name">` (exported by `"gatsby"`), e.g.
393
+ `PageProps<QueryResult<"BlogPostBySlug">>` for `graphql\`query BlogPostBySlug { ... }\``. The tags stay
394
+ as they are, so the code still runs with Gatsby (whose types don't have these names). A name used by
395
+ different queries is left out, with a warning.
396
+ - In Node APIs, the `graphql` helper (`createPages`, …) infers `data` from a query string literal once
397
+ the types exist (without the site's fragments, which aren't available there). As in Gatsby,
398
+ `graphql<Data>(…)` or the type the result is assigned to set the type instead, and strings that aren't
399
+ literals give `data: unknown`. Since the helper has two signatures, a typed stand-in for it
400
+ (`const fake: CreatePagesArgs["graphql"] = async (query: string, variables?: object) => …`) needs
401
+ types for its parameters.
402
+ - The types come from `src/gatsby-graphql-env.d.ts`, which goatly writes after extracting the
403
+ queries in `build` and `develop` (and again in develop when the schema, the fragments or the queries
404
+ change). It is generated for sites with a `tsconfig.json` once they use `graphql()` calls or the types
405
+ above (sites with only tags get no new file), and never over a file goatly did not write.
406
+ Commit it, so that type checks work before the first build: until it exists, documents are typed
407
+ `any` (and the Node API helper's `data` is `unknown`). `gqlTada: false` in gatsby-config turns it
408
+ off, `gqlTada: { typesOutputPath: "types/gatsby-graphql-env.d.ts" }` moves it (your tsconfig must
409
+ include it), and `gqlTada: true` generates it in any case. Its header turns off ESLint, oxlint,
410
+ Biome, Prettier and oxfmt for it. A TypeScript program can only include the file of one site.
411
+ - Custom scalars: `Date` is a `string`, `JSON` is `any`, `GatsbyImageData` is gatsby-plugin-image's
412
+ `IGatsbyImageData` when the plugin is installed, and others are `any` (as in Gatsby's typegen). Declare or override types
413
+ in the global `GatsbyGraphQLScalars` interface:
414
+
415
+ ```ts
416
+ // src/graphql-scalars.d.ts
417
+ declare global {
418
+ interface GatsbyGraphQLScalars {
419
+ JSON: Record<string, unknown>
420
+ }
421
+ }
422
+ export {}
423
+ ```
424
+
425
+ - gql.tada types fields that don't exist as `unknown` (the build reports the invalid query); a
426
+ document it can't parse is a type error at the `graphql()` call.
427
+ - The types need TypeScript ≥ 5.0. gql.tada is not a dependency: its type definitions are included
428
+ (MIT, `types/vendor/`).
429
+ - Gatsby's `graphqlTypegen` (`Queries.*` types) is not generated.
430
+
431
+ ### Multiple 404 pages
432
+
433
+ Gatsby shows every unknown URL the same 404 page, `src/pages/404` (built as `/404.html`). With
434
+ `notFoundPages`, sections of the site get their own, e.g. one per language:
435
+
436
+ ```ts
437
+ // gatsby-config.ts – src/pages/404.tsx (English), src/pages/de/404.tsx, src/pages/fr/404.tsx
438
+ const config: GatsbyConfig = {
439
+ notFoundPages: ["/de", "/fr"], // the 404 page of a section is <section>/404/
440
+ // or: section → its 404 page (any page, also one made with createPage)
441
+ // notFoundPages: { "/de": "/de/404/", "/de-at": "/de/404/", "/fr": "/fr/introuvable/" },
442
+ }
443
+ ```
444
+
445
+ - **Which page.** An unknown URL gets the 404 page of the longest section containing it, by whole
446
+ path segments: `/de/a/b` is in `/de`, `/deutsch/x` and `/de-at/x` are not. All other unknown URLs
447
+ get `/404.html`. Pages and client-only routes (`matchPath`) win. Sections are paths without
448
+ `pathPrefix`.
449
+ - **Everywhere.** `develop` and `serve` answer with status 404 and the section's 404 page. In the
450
+ browser, navigating to a missing page renders the section's 404 page; `location` and the `path`
451
+ prop are the requested URL.
452
+ - **Build output.** The 404 page of a section is also built as `<section>/404.html` (next to
453
+ `public/de/404/index.html`), the file static hosts look for. `.cache/not-found-pages.json` lists
454
+ them (`{ "version": 1, "pages": [{ "prefix", "path", "source", "file" }] }`, longest prefix
455
+ first), for `serve` and hosting plugins.
456
+ - **i18n plugins.** gatsby-plugin-react-i18next, gatsby-plugin-intl and gatsby-theme-i18n create
457
+ `/de/404/` (with a catch-all `matchPath` such as `/de/*`) and `/de/404.html`: with them,
458
+ `notFoundPages: ["/de", "/fr"]` is all it takes. The catch-all `matchPath` of a section's 404 page
459
+ (also of `/de/404/` when the section is set to `/de/404.html`) is no client-only route then, so
460
+ unknown URLs get status 404 instead of 200; the build warns about a `matchPath` that also matches
461
+ URLs outside the page's sections. (Without the option, the build lists the sections that have a
462
+ 404 page; `notFoundPages: []` turns that off.)
463
+ - **Static hosts** serve `/404.html` for unknown URLs. For the sections' pages:
464
+ - Cloudflare Pages and Workers static assets (`not_found_handling: "404-page"`) serve the nearest
465
+ `404.html` up the path: nothing to do.
466
+ - Netlify: `_redirects` rules such as `/de/* /de/404.html 404`, the most specific section first
467
+ (or `createRedirect({ fromPath: "/de/*", toPath: "/de/404.html", statusCode: 404 })` with
468
+ gatsby-plugin-netlify). A client-only route inside a section needs a rule before it
469
+ (`/de/app/* /de/app/ 200`).
470
+ - nginx: `location /de/ { error_page 404 /de/404.html; }`; Apache: `ErrorDocument 404
471
+ /de/404.html` in `static/de/.htaccess`; Vercel: `{ "handle": "filesystem" }, { "src":
472
+ "/de/(.*)", "status": 404, "dest": "/de/404.html" }` in `routes`.
473
+ - Hosts that only serve `/404.html` (GitHub Pages, S3, Firebase): the browser switches to the
474
+ section's 404 page after loading.
475
+
476
+ With `pathPrefix`, the rules include it (`/prefix/de/*`). gatsby-plugin-sitemap excludes only
477
+ `/404` and `/404.html`: add `excludes: ["/**/404", "/**/404.html"]`.
478
+
479
+ ### Node datastore
480
+
481
+ Nodes live in a pluggable datastore. The default, the **logfile store**, appends them to a file in
482
+ `.cache/data/logfile` and reads them back on demand, so they sit in the operating system's page
483
+ cache instead of the build's memory. No required native dependency (msgpackr uses its optional
484
+ prebuilt decoder when it is installed), Node.js and Bun.
485
+
486
+ ```ts
487
+ // gatsby-config.ts
488
+ import { logFileDataStore } from "gatsby/node"
489
+ import { sqliteDataStore } from "@goatly/datastore-sqlite"
490
+
491
+ export default {
492
+ datastore: logFileDataStore({ cacheSize: 20_000 }), // the default, with options
493
+ // datastore: sqliteDataStore(), // the runtime's built-in SQLite
494
+ }
495
+ ```
496
+
497
+ The [SQLite store](../goatly-datastore-sqlite) or a custom store can be set instead.
498
+ Which one fits a site, compared by build times, memory and Docker builds:
499
+ [Choosing a node datastore](../../docs/datastores.md). How the logfile store works:
500
+ [Architecture: the logfile datastore](../../docs/architecture-logfile-datastore.md).
501
+
502
+ Options: `dir` (directory of the segment and index files, default `<cacheDir>/data/logfile`),
503
+ `cacheSize` (decoded nodes per thread).
504
+
505
+ `new LogFileDataStore({ dir, readonly: true })` opens a store without changing its files, and writes
506
+ throw (experimental); [`@goatly/devtools`](../goatly-devtools) uses it.
507
+
508
+ **Every store gives a node the same values.** The logfile and SQLite stores take a
509
+ node's values when it is set (`createNode`, `createNodeField`, …), with the same msgpackr codec
510
+ (structured clone), whether the node is read in the main thread or a query worker, before or after
511
+ it was written:
512
+
513
+ - **Nodes are immutable.** Changing a node object after it was set is not kept, in any store. Don't
514
+ change an object that `getNode()` returns either: depending on the store and its cache, the change
515
+ is kept, kept for a while or lost. Gatsby documents nodes as immutable too.
516
+ - **Values**: plain data, `Date`, `Map`, `Set`, `RegExp`, `Error`, `BigInt`, typed arrays and
517
+ `Buffer`s (decoded as copies) are kept. Class instances lose their prototype, and `-0` and holes
518
+ in sparse arrays come back as `0` and `undefined`. A class instance with a `toJSON()` method is
519
+ stored as what that method returns, e.g. a `URL` as its `href` (a plain object keeps its fields);
520
+ Gatsby's LMDB store encodes nodes with msgpackr too. Functions, symbols and cyclic references
521
+ don't reach the store: `createNode` and `createNodeField` drop them, like Gatsby. A value that
522
+ contains one is rebuilt as plain data first: objects other than arrays, `Date`, `RegExp` and
523
+ `Buffer` become plain objects of their own fields (a `Map`, `Set` or `URL` becomes `{}`, a typed
524
+ array an object of its elements), and repeated references are dropped.
525
+
526
+ Things to know about the logfile store. All but the last apply to the SQLite store too
527
+ (it starts empty after a run that did not persist):
528
+
529
+ - **`getNode()` returns a new object** once the node has left the cache. Do not compare nodes by
530
+ identity.
531
+ - **CPU for memory.** A query that touches every node of a type decodes those nodes, so queries that
532
+ read every node (e.g. `createPages` listing every post) take longer than queries that read a few
533
+ nodes each.
534
+ - In query workers, plugins that call `getNodes()` / `getNodesByType()` get arrays that load nodes
535
+ when an element is read, in chunks and without filling the cache: plugins can keep such a list
536
+ without reading most of it (gatsby-transformer-remark keeps every File node). The main thread,
537
+ where nodes are created and deleted, gets plain arrays.
538
+ - The files are a cache. Only `persist()` changes the persisted state: a run that did not persist (a
539
+ crash, Ctrl+C while sourcing) leaves the nodes of the last one that did. The cache is rebuilt when
540
+ goatly's cache is invalidated and when the format version changes.
541
+
542
+ When a store restores no nodes (before its first `persist()`, and with the SQLite store
543
+ after a run that did not persist), the plugin caches (`cache`, `getCache`) are deleted as well: they
544
+ may describe nodes that are gone, e.g. a source plugin's sync token. Plugins then transform their
545
+ nodes again too. A run's plugin cache writes become permanent when the nodes are next persisted
546
+ (also with a store without `persist()`, at the same points); what a run wrote after it last
547
+ persisted its nodes (a failed build, a crash, develop stopped during a refresh) is reverted at the
548
+ next start, so the plugin caches match the nodes that are restored. A datastore without `load()`
549
+ (e.g. a custom in-memory store) starts empty on every run while the plugin caches are kept, so
550
+ source plugins that keep a sync token in their cache can miss content. goatly warns when such
551
+ a run finds the plugin caches of an earlier run. Use a store that restores its nodes or run
552
+ `gatsby clean` before each run.
553
+
554
+ ### Incremental builds in Docker (buildx)
555
+
556
+ goatly lays out `.cache` for caches that travel between builds as container image layers or
557
+ are synced file by file: an incremental build writes what changed into new files. Keep both
558
+ `.cache` and `public` between builds, e.g. with BuildKit cache mounts (`RUN
559
+ --mount=type=cache,target=/app/.cache --mount=type=cache,target=/app/public …`, copying `public` out
560
+ of the mount in the same `RUN`). Like Gatsby, goatly discards a `.cache` without `public`, and
561
+ it treats an empty `public` like a missing one. What each way of carrying `.cache` to the next build
562
+ transfers, with measurements: [Incremental builds in Docker](../../docs/docker.md).
563
+
564
+ ### Logging (pluggable reporter)
565
+
566
+ All output of goatly and its plugins goes through Gatsby's `reporter` API. Its output is
567
+ pluggable: every call becomes a log entry (`level`, `text`, structured `error` details) or an
568
+ activity event (start/update/end with status, progress and elapsed time) for one or more transports.
569
+
570
+ ```ts
571
+ // gatsby-config.ts
572
+ import winston from "winston"
573
+ import { loggerTransport, jsonTransport, consoleTransport } from "gatsby/reporter"
574
+
575
+ const logger = winston.createLogger({
576
+ transports: [new winston.transports.File({ filename: "build.log" })],
577
+ })
578
+
579
+ export default {
580
+ reporter: [consoleTransport(), loggerTransport(logger)], // console output + a log file
581
+ }
582
+ ```
583
+
584
+ - `consoleTransport()` prints Gatsby-style output and is the default. `jsonTransport()` writes one JSON
585
+ object per line, for CI and log shippers.
586
+ - `loggerTransport(logger)` works with winston, pino, bunyan, consola, `console` or anything with
587
+ `error`/`warn`/`info`/`debug` methods. It detects whether the logger takes the message first
588
+ (winston, consola) or a metadata object first (pino, bunyan), or you set `style`.
589
+ - A transport is an object with `log(entry)` and optionally `activityStart/activityUpdate/activityEnd`
590
+ and `flush()`, which runs before the process exits.
591
+ - You can also set transports with `build({ reporter })` / `develop({ reporter })`, with
592
+ `GOATLY_REPORTER=./my-reporter.mjs` (a module whose default export is the transport(s)), or
593
+ with `reporter.setTransports()`. These take precedence over gatsby-config, which only takes effect
594
+ after the config is loaded.
595
+ - Query and render worker threads forward their output to the main thread's transports.
596
+ - Steps that run for more than 5 seconds log a progress line, at first every 5 seconds, then less
597
+ often (at least once a minute):
598
+ `info run page queries and build static HTML - running for 10s - 5300/8422 62% - 3 workers, 5300/8422 queries`
599
+ - With parallel query running, page queries and HTML rendering are one pipelined step. Below its line
600
+ the build prints its parts as a timeline: worker start-up, page queries, waiting for the bundles
601
+ (if the queries finished first) and HTML. HTML rendering starts as soon as the bundles exist,
602
+ usually while queries still run, so its bar overlaps the queries' bar:
603
+
604
+ ```
605
+ success run page queries and build static HTML - 602.000s - 8422/8422 14/s - 3 workers, 8422 queries
606
+ ├─ █------------------- persist data for the query workers - 0.400s (0%)
607
+ ├─ -█------------------ start query workers - 1.600s (0%) - 3 workers
608
+ ├─ --██████████████████ run page queries - 598.000s (99%) - 8422 queries, 14/s, workers busy 1650.000s in total
609
+ └─ -------█████████████ build static HTML for pages - 402.000s (67%) - 8422 pages, 21/s, 400.000s alongside the queries, 2.000s after them, workers busy 310.000s in total
610
+ ```
611
+
612
+ ## API compatibility
613
+
614
+ **Node APIs** (`gatsby-node`): `onPluginInit`, `onPreInit`, `onPreBootstrap`, `sourceNodes`,
615
+ `onCreateNode` (+ `shouldOnCreateNode`), `createSchemaCustomization`, `setFieldsOnGraphQLNodeType`,
616
+ `createResolvers`, `createPages`, `createPagesStatefully`, `onCreatePage`, `onPreExtractQueries`,
617
+ `onPostBootstrap`, `onPreBuild`, `onPostBuild`, `onCreateDevServer` (Express compatible `app`),
618
+ `resolvableExtensions`, `preprocessSource`, `pluginOptionsSchema` (Joi, incl. `subPlugins()`),
619
+ `onCreateWebpackConfig`, `onCreateBabelConfig` (compatibility shims, see below), plus the new
620
+ `onCreateViteConfig`. Callback-style APIs (three parameters) are supported.
621
+
622
+ **API helpers** (first argument): `actions`, `store`, `emitter`, `reporter`, `cache`, `getCache`,
623
+ `getNode`, `getNodes`, `getNodesByType`, `getNodeAndSavePathDependency`, `loadNodeContent`,
624
+ `createNodeId` (same UUIDs as Gatsby), `createContentDigest` (same digests), `pathPrefix`, `basePath`,
625
+ `schema.build*Type`, `tracing`, `parentSpan`, `traceId`, `graphql` (where Gatsby provides it).
626
+ Plugin cache keys are strings or numbers (`1` and `"1"` are the same key); other keys make
627
+ `cache.get`/`set`/`del` reject with a `TypeError`. Plugin cache values are stored like node values
628
+ ("Every store gives a node the same values" under [Node datastore](#node-datastore)): `cache.set`
629
+ encodes the value right away, so changing the object afterwards changes nothing, and a value that
630
+ can't be encoded makes `cache.set` reject. Don't change an object that `cache.get` returns either:
631
+ the reads of a thread share it, like nodes from `getNode()`. (Gatsby's cache stores JSON, so a
632
+ `Date` comes back as a string there and a `Map` as `{}`.) What a run writes with
633
+ `cache.set`/`del`/`reset` becomes permanent together with its nodes: the next start reverts what a
634
+ run wrote after it last persisted its nodes (files in `cache.directory` are not reverted; see
635
+ [Node datastore](#node-datastore)).
636
+
637
+ **Actions**: `createNode`, `deleteNode`, `touchNode`, `createNodeField`, `createParentChildLink`,
638
+ `createPage`, `deletePage`, `createRedirect`, `createTypes`, `createFieldExtension`,
639
+ `addThirdPartySchema`, `printTypeDefinitions`, `createResolverContext`, `createJobV2` (runs
640
+ `gatsby-worker` jobs), `setPluginStatus`, `setRequestHeaders`, `enableStatefulSourceNodes`,
641
+ `setWebpackConfig`/`replaceWebpackConfig`, `setBabel*`. These follow Gatsby's semantics and
642
+ restrictions: owner checks, type ownership, `TOUCH_NODE` for unchanged digests, cascading
643
+ `onCreateNode`/`onCreatePage`, stale-node deletion by root ancestor, and restricted actions per API.
644
+ The deprecated Jobs API v1 (`createJob`/`setJob`/`endJob`), `unstable_createNodeManifest` (Gatsby
645
+ Cloud previews) and `addRemoteFileAllowedUrl` (Image CDN) can be called and do nothing.
646
+ Completed `createJobV2` jobs are kept between builds, like Gatsby's: a job with the same name, args,
647
+ output directory and input file contents resolves with its earlier result without running again
648
+ (e.g. gatsby-plugin-sharp's images when only a template's query changed), as long as its output
649
+ directory still exists. Inputs are compared by content, so a file that was only touched is not
650
+ processed again (a job with an input that is not a readable file, e.g. a directory, is not kept).
651
+ The records live in the plugin cache, in both cache layouts: they are deleted with it (changed
652
+ plugins, config or gatsby-node, `gatsby clean`), and at the next start, those whose inputs or output
653
+ directory are gone are dropped, as are those superseded by the same job with other args (e.g.
654
+ another image size) in a later build.
655
+
656
+ **GraphQL**: Gatsby 5 schema. That covers inference (dates, `___NODE` links, unions, File links by relative path,
657
+ `mapping`, conflict detection, `childX`/`childrenX`), `@dontInfer`/`@infer`/`@childOf`/`@mimeTypes`/
658
+ `@nodeInterface`, `@link`/`@dateformat`/`@fileByRelativePath`/`@proxy` and custom field extensions,
659
+ `x(...)` / `allX(filter, sort, skip, limit)` with all operators (`eq ne in nin regex glob gt gte lt lte
660
+ elemMatch`), Gatsby 5 nested `sort`, `distinct`/`group`/`min`/`max`/`sum`, `pageInfo`, Node interfaces,
661
+ third-party schemas, `context.nodeModel` (`findAll`, `findOne`, `getNodeById`, `getNodesByIds`, …),
662
+ `info.originalResolver` and fragments.
663
+
664
+ **SitePage nodes** (`allSitePage`, `sitePage`) are created once something reads them: a page or static
665
+ query that selects them, a query or `nodeModel` read of them in a plugin (e.g. gatsby-plugin-sitemap in
666
+ `onPostBuild`), `getNode("SitePage …")`, `getNodesByType("SitePage")`, `getNodes()` or a node action on
667
+ one of them. Until then `createPage` creates none: sites that never read them save a content digest and
668
+ a datastore write per page (a touch on warm builds). The first read creates the nodes of all pages
669
+ created so far, in page order, before it is answered, and a build after one that read them creates them
670
+ from the start. Query workers can't create them: pages whose queries read them there (e.g. through a
671
+ resolver calling `nodeModel.findAll({ type: "SitePage" })`) are built again once the main thread created
672
+ them, in query workers when there are many. As before, `onCreateNode` is not called for SitePage nodes.
673
+ For a plugin that reads them in a way goatly doesn't notice (e.g. `emitter` events of SitePage
674
+ nodes), `GOATLY_LAZY_SITE_PAGE_NODES=false` creates them with every page, as before.
675
+
676
+ **SSR APIs** (`gatsby-ssr`): `onRenderBody`, `onPreRenderHTML`, `replaceRenderer`, `wrapRootElement`,
677
+ `wrapPageElement`, and custom `src/html.js`.
678
+
679
+ **Browser APIs** (`gatsby-browser`): `onClientEntry`, `onInitialClientRender`, `onPreRouteUpdate`,
680
+ `onRouteUpdate`, `onRouteUpdateDelayed`, `shouldUpdateScroll`, `wrapRootElement`, `wrapPageElement`,
681
+ `replaceHydrateFunction`, `onPrefetchPathname`, `onPostPrefetchPathname`, `disableCorePrefetching`,
682
+ `registerServiceWorker` + `onServiceWorker*`, `onCaughtError` + `onUncaughtError` (Gatsby 5.16, React 19).
683
+
684
+ **`gatsby` exports**: `Link`, `navigate`, `withPrefix`, `withAssetPrefix`, `parsePath`, `graphql`,
685
+ `useStaticQuery`, `StaticQuery`, `StaticQueryContext`, `Script` (`post-hydrate`, `idle`),
686
+ `PageRenderer`, `prefetchPathname`, `useScrollRestoration`, and goatly's `useLink`,
687
+ `LinkProvider` and `useLinkConfig` (see [Customizing `Link`](#customizing-link)). Types: `GatsbyConfig`, `GatsbyNode`,
688
+ `GatsbySSR`, `GatsbyBrowser`, `PageProps`, `HeadFC`, `HeadProps`, `ResultOf`, `VariablesOf`, … (`gatsby/graphql`,
689
+ `gatsby/reporter` and `@reach/router` are available too.)
690
+
691
+ **Pages**: `src/pages`, `[param]`/`[...]` client-only routes, `{Type.field}` collection
692
+ routes with `gatsbyPath`, `/404.html` and 404 pages of site sections (`notFoundPages`), `trailingSlash`,
693
+ `pathPrefix`/`assetPrefix` with `--prefix-paths`, `matchPath`, browser redirects, and themes: a theme's
694
+ gatsby-config adds its `plugins` (resolved from the theme) and `siteMetadata` (the site's values win,
695
+ other options log a warning), and its `src/pages` are built.
696
+
697
+ **gatsby-config**: `siteMetadata`, `plugins`, `pathPrefix`, `assetPrefix`, `trailingSlash`, `mapping`,
698
+ `jsxRuntime`/`jsxImportSource`, and in develop `proxy` (through Vite's `server.proxy`) and
699
+ `developMiddleware`. `flags` and `polyfill` have no effect. `headers`, `adapter` and `graphqlTypegen`
700
+ are ignored with a warning.
701
+
702
+ ### Compatibility shims
703
+
704
+ - **`onCreateWebpackConfig`** runs with webpack-like helpers. `resolve.alias` and `DefinePlugin`
705
+ definitions are translated to Vite; loaders and rules are ignored (Vite handles CSS, assets, Sass and PostCSS
706
+ natively). Use `onCreateViteConfig` or `vite` in gatsby-config for anything else.
707
+ - **Babel APIs** are accepted and have no effect, except for two plugins that Oxc has a port of:
708
+ - `babel-plugin-styled-components` (e.g. from `gatsby-plugin-styled-components`): its options drive
709
+ Oxc's styled-components transform, with stable component ids always on so dev SSR and the browser
710
+ generate the same class names.
711
+ - `babel-plugin-react-compiler`, in the site's `.babelrc`/`babel.config.*` or from `setBabelPlugin`:
712
+ turns on React Compiler with its options (see [React Compiler](#react-compiler)).
713
+ - `babel-plugin-parse-static-images` (from `gatsby-plugin-image`): a Vite transform gives each
714
+ `<StaticImage>` the image data that the plugin's `preprocessSource` generated (with the plugin's
715
+ own parser and hashing), or the error the component shows. It works in `.js`, `.jsx` and `.tsx`
716
+ files, also outside `src/` (gatsby-browser/gatsby-ssr files of plugins, themes). In develop a
717
+ changed `StaticImage` or a changed source image gets its new images on the next hot update.
718
+ - **CommonJS `gatsby-browser`/`gatsby-ssr` files** and CJS npm plugins are converted for Vite's dev
719
+ server. `require("./global.css")` works.
720
+ - **JSX in `.js` files** works as in Gatsby, in the site and in the packages of its plugins (which get the
721
+ site's transforms, like Gatsby compiles the packages that use gatsby).
722
+ - **Hydration mismatches** in develop are printed in the terminal (page path, message, component stack),
723
+ not only in the browser console – including React 18's attribute warnings (e.g. `className did not
724
+ match`), which React does not repair: the DOM keeps the server value.
725
+ - **`onCaughtError`/`onUncaughtError`** become React 19's root options of the same name only when a plugin
726
+ or the site implements them, and then behave as in Gatsby: an uncaught error is logged with
727
+ `console.error` before the API runs, a caught one only goes to the API. Gatsby always sets both, so on
728
+ Gatsby with React 19, errors an error boundary caught are never logged and uncaught ones never reach
729
+ `window.onerror`, on every site. Here, sites that don't use the APIs keep React's own error reporting.
730
+ React 18 has no such options and never calls them.
731
+ - **`<html>`/`<body>` inside `Head`** compile to `HtmlAttributes`/`BodyAttributes`, because React 19 treats them
732
+ as document singletons (and React 18 can't render them inside a `Head` either).
733
+ - **`Head` on React 18** works like Gatsby 5: on the server the `Head` export is rendered on its own
734
+ (with the same wrappers and contexts as the page) into `<head>`, with `data-gatsby-head` markers; in
735
+ the browser it renders into a detached element and is synced into `<head>` in the same commit as the
736
+ page. Unlike React 19, scripts and styles of a `Head` export end up in `<head>` too.
737
+ - **`GatsbyImageData`** is a built-in scalar (JSON values), as in Gatsby 5: plugins declare
738
+ `gatsbyImageData: GatsbyImageData!` (gatsby-plugin-image, gatsby-transformer-sharp, CMS source
739
+ plugins).
740
+ - **`/static/` URLs in develop** (files plugins write to `public/static`, e.g. processed images) are
741
+ served before Vite, without its warning about its `publicDir` (the site's `static/`).
742
+ - **CommonJS dependencies of plugin packages** in develop: Vite doesn't pre-bundle plugin packages (so
743
+ the site and their gatsby-browser files share one copy) and doesn't discover what files in
744
+ node_modules import. So the CommonJS packages that a plugin's browser entry imports (its
745
+ `browser` field, `exports` browser condition or `module` field, following relative imports; not
746
+ `main`, which is Node code in source and transformer plugins) are pre-bundled as nested `optimizeDeps.include` entries (`"gatsby-plugin-image > prop-types"`), with
747
+ Vite's interop. The plugins' own CommonJS files are converted to ESM by goatly, and the ES
748
+ modules that import them get what webpack gives: `module.exports`' properties for `import * as ns`
749
+ and for named imports the converter can't see, and `exports.default` for the default import of a
750
+ module compiled from ESM (`__esModule`, e.g. gatsby-plugin-manifest's gatsby-browser importing its
751
+ Babel-compiled helpers).
752
+ - **The cache key** includes the plugin options as gatsby-config sets them, before `onPreInit`: what a
753
+ plugin adds there (gatsby-plugin-manifest's digest of its icon file) doesn't delete the cache.
754
+ - **Jobs** (`createJobV2`, e.g. gatsby-plugin-sharp's image processing) that page queries create are
755
+ finished before `onPostBuild`, like Gatsby. Query workers send theirs to the main thread, like
756
+ Gatsby's worker messaging: it runs them, deduplicated across workers and with one concurrency limit,
757
+ and replies with the result. Like in Gatsby's main process, a `gatsby-worker` function shares the
758
+ main thread's event loop: one that computes synchronously (rather than in native code, like sharp)
759
+ runs one at a time. `process.env.gatsby_executing_command` is set as gatsby-cli sets it, so
760
+ gatsby-plugin-sharp processes images on their first request in develop. Completed jobs are kept
761
+ between builds (see API compatibility).
762
+ - **Resolvers** get the query's variables in their context, like Gatsby: for page queries the page
763
+ (`componentPath`, `path`) and its context.
764
+ - **`gatsby-core-utils` md5File** is replaced by a native implementation (see Performance).
765
+ - **`gatsby-core-utils`' remote file database** (`fetchRemoteFile`, used by `createRemoteFileNode`,
766
+ and its mutexes) is kept in the built-in SQLite (`.cache/data/gatsby-core-utils.sqlite`) instead
767
+ of the `lmdb` 2.5.3 it pins, which doesn't load on Bun.
768
+
769
+ ### Not supported
770
+
771
+ - Rendering modes other than SSG. A page that exports `getServerData` (SSR) fails the build, with steps to
772
+ move its data into the page query or the browser. Deferred pages (`defer: true`, DSG) are built statically.
773
+ - Gatsby Functions, adapters (`adapter` and `headers` in gatsby-config are ignored with a warning), Image CDN.
774
+ - Component shadowing of themes: files in `src/<theme name>/` of the site or of another theme stop the build.
775
+ The error lists the steps to make the theme a local plugin: copy it to `plugins/<name>/`, move its `plugins`
776
+ and `siteMetadata` into your gatsby-config, add `gatsby-plugin-page-creator` for its `src/pages`, point
777
+ imports of the theme package to the copy (e.g. with `vite.resolve.alias`), and apply the shadowed files to
778
+ the copy.
779
+ - `gatsby-plugin-offline`: it needs webpack's `webpack.stats.json`, so the build stops and explains how to
780
+ remove its service worker (`gatsby-plugin-remove-serviceworker`) or keep offline support with your own
781
+ `sw.js` and `registerServiceWorker`.
782
+ - Partytown: `<Script strategy="off-main-thread">` runs the script on the main thread when the
783
+ browser is idle (like `idle`), `forward` and `partytownProxiedURLs` are ignored.
784
+ - Slices: `createSlice` logs a warning and is ignored, a page rendering `<Slice>` fails to build, and
785
+ `<Slice allowEmpty>` renders nothing. Render the slice component directly: pass its `sliceContext`
786
+ as props, and turn its `export const query` into `useStaticQuery` or part of the page query.
787
+ `page-data.json` keeps an empty `slicesMap` (Gatsby's format).
788
+ - A render error inside a `<Suspense>` boundary fails the page, as in Gatsby (React would ship the
789
+ fallback instead).
790
+ - Plugins that depend on webpack/Babel internals other than the ones under
791
+ [Compatibility shims](#compatibility-shims).
792
+ - `graphqlTypegen`: Gatsby's `Queries.*` types are not generated (a warning points to typed `graphql()`
793
+ queries, see [Typed GraphQL](#typed-graphql-gqltada), and to GraphQL Code Generator). GraphiQL loads its
794
+ UI from a CDN.
795
+
796
+ ## How it works
797
+
798
+ ```
799
+ bootstrap: config → plugins (themes, sub-plugins, Joi validation) → onPreInit → cache/datastore → onPluginInit
800
+ → onPreBootstrap → createSchemaCustomization → sourceNodes (+ cascading onCreateNode) → stale node GC
801
+ → schema (inference, extensions, setFieldsOnGraphQLNodeType, createResolvers)
802
+ → createPages → createPagesStatefully (+ onCreatePage) → query extraction (oxc) → onPostBootstrap
803
+ build: onPreBuild → static queries → dirty page queries (node dependencies of the last build)
804
+ → ┬ Vite client + SSR builds (Rolldown)
805
+ └ page queries (main thread, or worker threads with their own data layer)
806
+ → HTML + page-data of changed pages (rendered by the same workers) → onPostBuild
807
+ develop: Vite dev server (middleware mode) + module runner for SSR, page-data on demand,
808
+ data changes → schema/pages/queries refresh → HMR event → page updates in place
809
+ ```
810
+
811
+ [Architecture: the build pipeline](../../docs/architecture-build-pipeline.md) draws this as diagrams and
812
+ explains how page queries, bundles and HTML overlap in one step and what an incremental build runs
813
+ again. More in [`docs/`](../../docs/README.md).
814
+
815
+ - `graphql` tags and `graphql()` calls are compiled away. Static queries become imports of virtual modules containing
816
+ their result, so data changes hot-reload through Vite's module graph. Page queries are removed from
817
+ the bundle. An exported query only runs in a page component. Gatsby warns about every other file
818
+ that exports one; goatly only warns when the site imports such a file (e.g. a component
819
+ that exports `query` where `useStaticQuery` was meant). Templates that no page uses (e.g. for a
820
+ content type without entries in the CMS) are listed only with `--verbose`.
821
+ - The same `Root`/`AppRoot` React tree is used for SSR (build and develop) and hydration.
822
+ - Packages: [`packages/goatly`](.) (CLI, Node core, Vite integration, React
823
+ runtime, the logfile datastore), the datastore
824
+ [`@goatly/datastore-sqlite`](../goatly-datastore-sqlite),
825
+ [`@goatly/wasm`](../goatly-wasm) (`goatly-data.wasm`, the Rust side of the page
826
+ queries, and its loader),
827
+ [`@goatly/redact`](../goatly-redact) (TanStack Redact as the renderer),
828
+ [`@goatly/devtools`](../goatly-devtools) (a Vite DevTools panel that shows
829
+ the live datastore in develop, and a CLI for stores saved on disk; see the
830
+ [DevTools guide](../../docs/devtools.md)),
831
+ [`examples/blog`](../../examples/blog) (TypeScript/ESM site with npm Gatsby plugins),
832
+ [`examples/gallery`](../../examples/gallery) (`gatsby-plugin-image` with `GatsbyImage` and
833
+ `StaticImage`, `gatsby-plugin-sharp`, `gatsby-transformer-sharp`),
834
+ [`examples/benchmark`](../../examples/benchmark) and [`examples/benchmark-api`](../../examples/benchmark-api).
835
+
836
+ ## Development
837
+
838
+ ```bash
839
+ pnpm install
840
+ pnpm build # build the packages (tsdown; goatly-data.wasm with Rust, see below)
841
+ pnpm test # vitest (unit + e2e builds of examples/blog and examples/gallery)
842
+ pnpm typecheck # tsrs (TypeScript 7 in Rust)
843
+ pnpm lint # oxlint
844
+ pnpm fmt # oxfmt
845
+ cd examples/blog && pnpm develop
846
+ ```
847
+
848
+ `pnpm build` compiles `goatly-data.wasm` with `cargo` when Rust and its `wasm32-wasip1-threads` target
849
+ are installed (`rustup target add wasm32-wasip1-threads`). Without them it warns, and builds run
850
+ every page query in JS (CI requires them). The published `@goatly/wasm` package contains the
851
+ compiled module.
852
+
853
+ ## License
854
+
855
+ MIT. Parts of the type definitions and API behaviour follow Gatsby (MIT, © gatsbyjs).