goatly 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.md +853 -1
  2. package/bin/goatly.js +91 -0
  3. package/dist/cli/index.js +234 -0
  4. package/dist/compat/gatsby-node-entry.js +16 -0
  5. package/dist/compat/gatsby-package.json +6 -0
  6. package/dist/compat/md5-file.js +47 -0
  7. package/dist/compat-apis.json +72 -0
  8. package/dist/compat-apis.json.js +62 -0
  9. package/dist/graphql.js +3 -0
  10. package/dist/node/actions/index.js +619 -0
  11. package/dist/node/actions/job-store.js +180 -0
  12. package/dist/node/actions/jobs.js +174 -0
  13. package/dist/node/api-runner.js +258 -0
  14. package/dist/node/bootstrap.js +539 -0
  15. package/dist/node/build/assets.js +110 -0
  16. package/dist/node/build/incremental.js +208 -0
  17. package/dist/node/build/index.js +752 -0
  18. package/dist/node/build/memory-governor.js +448 -0
  19. package/dist/node/build/output-dirs.js +70 -0
  20. package/dist/node/build/page-data.js +40 -0
  21. package/dist/node/build/page-files.js +54 -0
  22. package/dist/node/build/partitioned-state.js +258 -0
  23. package/dist/node/build/query-worker.js +536 -0
  24. package/dist/node/build/query-workers.js +832 -0
  25. package/dist/node/build/render-worker.js +131 -0
  26. package/dist/node/build/state.js +24 -0
  27. package/dist/node/build/timing-breakdown.js +155 -0
  28. package/dist/node/build/worker-pool.js +236 -0
  29. package/dist/node/cache-layout.js +99 -0
  30. package/dist/node/cache.js +1430 -0
  31. package/dist/node/compat/chokidar-shim.js +148 -0
  32. package/dist/node/compat/core-utils-lmdb.js +145 -0
  33. package/dist/node/compat/create-node-id-shim.js +1 -0
  34. package/dist/node/compat/module-hooks.js +245 -0
  35. package/dist/node/compat/redux-shim.js +1 -0
  36. package/dist/node/config/index.js +162 -0
  37. package/dist/node/config/not-found-pages.js +95 -0
  38. package/dist/node/datastore/codec.js +144 -0
  39. package/dist/node/datastore/index.js +127 -0
  40. package/dist/node/datastore/logfile/cache.js +89 -0
  41. package/dist/node/datastore/logfile/index.js +1329 -0
  42. package/dist/node/datastore/logfile/record.js +71 -0
  43. package/dist/node/datastore/types.js +1 -0
  44. package/dist/node/develop/express-compat.js +207 -0
  45. package/dist/node/develop/graphiql.js +22 -0
  46. package/dist/node/develop/hydration-report.js +41 -0
  47. package/dist/node/develop/index.js +618 -0
  48. package/dist/node/develop/local-url.js +10 -0
  49. package/dist/node/develop/ssr-runner.js +66 -0
  50. package/dist/node/gql.js +5 -0
  51. package/dist/node/index.js +15 -0
  52. package/dist/node/info.js +270 -0
  53. package/dist/node/internal-plugins/data-bridge.js +196 -0
  54. package/dist/node/internal-plugins/page-creator.js +318 -0
  55. package/dist/node/loader/import-module.js +160 -0
  56. package/dist/node/node-helpers.js +66 -0
  57. package/dist/node/not-found-pages.js +220 -0
  58. package/dist/node/plugins/api-list.js +12 -0
  59. package/dist/node/plugins/load-plugins.js +427 -0
  60. package/dist/node/plugins/resolve-plugin.js +79 -0
  61. package/dist/node/plugins/static-exports.js +64 -0
  62. package/dist/node/query/compile.js +326 -0
  63. package/dist/node/query/dependencies.js +45 -0
  64. package/dist/node/query/execute.js +417 -0
  65. package/dist/node/query/extract.js +372 -0
  66. package/dist/node/query/gql-tada-introspection.js +124 -0
  67. package/dist/node/query/graphql-env.js +231 -0
  68. package/dist/node/query/graphql-runner.js +79 -0
  69. package/dist/node/redux/actions.js +1 -0
  70. package/dist/node/redux/index.js +133 -0
  71. package/dist/node/redux/node-changes.js +128 -0
  72. package/dist/node/redux/reducers.js +193 -0
  73. package/dist/node/redux/state.js +71 -0
  74. package/dist/node/renderer.js +124 -0
  75. package/dist/node/reporter-transports.js +259 -0
  76. package/dist/node/reporter.js +497 -0
  77. package/dist/node/schema/date.js +539 -0
  78. package/dist/node/schema/extensions.js +315 -0
  79. package/dist/node/schema/index.js +542 -0
  80. package/dist/node/schema/infer.js +388 -0
  81. package/dist/node/schema/inline-objects.js +128 -0
  82. package/dist/node/schema/naming.js +20 -0
  83. package/dist/node/schema/node-model.js +207 -0
  84. package/dist/node/schema/query-engine.js +1808 -0
  85. package/dist/node/schema/resolver-kinds.js +7 -0
  86. package/dist/node/schema/resolvers.js +273 -0
  87. package/dist/node/schema/type-builders.js +45 -0
  88. package/dist/node/schema/types.js +241 -0
  89. package/dist/node/serve.js +90 -0
  90. package/dist/node/site-page-nodes.js +277 -0
  91. package/dist/node/types.js +1 -0
  92. package/dist/node/utils/content-digest.js +107 -0
  93. package/dist/node/utils/create-node-id.js +51 -0
  94. package/dist/node/utils/env.js +24 -0
  95. package/dist/node/utils/fs-retry.js +74 -0
  96. package/dist/node/utils/memory-signals.js +410 -0
  97. package/dist/node/utils/memory.js +400 -0
  98. package/dist/node/utils/murmurhash.js +32 -0
  99. package/dist/node/utils/parser.js +33 -0
  100. package/dist/node/utils/partition-hash.js +19 -0
  101. package/dist/node/utils/paths.js +122 -0
  102. package/dist/node/utils/resolver.js +48 -0
  103. package/dist/node/utils/runtime.js +5 -0
  104. package/dist/node/utils/serializable.js +41 -0
  105. package/dist/node/utils/strings.js +41 -0
  106. package/dist/node/vite/config.js +289 -0
  107. package/dist/node/vite/paths.js +12 -0
  108. package/dist/node/vite/plugin-deps.js +232 -0
  109. package/dist/node/vite/plugin.js +281 -0
  110. package/dist/node/vite/react-compiler.js +362 -0
  111. package/dist/node/vite/source-files.js +83 -0
  112. package/dist/node/vite/static-image.js +136 -0
  113. package/dist/node/vite/styled-components.js +73 -0
  114. package/dist/node/vite/transforms.js +299 -0
  115. package/dist/node/wasm-data/host.js +406 -0
  116. package/dist/node/wasm-data/lower.js +406 -0
  117. package/dist/node/wasm-data/runner.js +79 -0
  118. package/dist/node/wasm-data/worker.js +95 -0
  119. package/dist/reporter.js +5 -0
  120. package/dist/runtime/api-runner.js +81 -0
  121. package/dist/runtime/app.js +256 -0
  122. package/dist/runtime/client-entry.js +4 -0
  123. package/dist/runtime/client.js +383 -0
  124. package/dist/runtime/default-html.js +31 -0
  125. package/dist/runtime/head-markup.js +100 -0
  126. package/dist/runtime/head-sync.js +101 -0
  127. package/dist/runtime/head-tags.js +45 -0
  128. package/dist/runtime/hydration-report.js +111 -0
  129. package/dist/runtime/index.js +12 -0
  130. package/dist/runtime/link.js +293 -0
  131. package/dist/runtime/loader.js +449 -0
  132. package/dist/runtime/not-found.js +61 -0
  133. package/dist/runtime/page-renderer.js +35 -0
  134. package/dist/runtime/preamble.js +47 -0
  135. package/dist/runtime/react-compat.js +14 -0
  136. package/dist/runtime/renderer-shared.js +10 -0
  137. package/dist/runtime/renderers/react-client.js +14 -0
  138. package/dist/runtime/renderers/react-server.js +99 -0
  139. package/dist/runtime/renderers/react.js +17 -0
  140. package/dist/runtime/renderers/types.js +1 -0
  141. package/dist/runtime/root-error-handlers.js +29 -0
  142. package/dist/runtime/router/history.js +132 -0
  143. package/dist/runtime/router/index.js +240 -0
  144. package/dist/runtime/router/utils.js +118 -0
  145. package/dist/runtime/script.js +110 -0
  146. package/dist/runtime/scroll.js +40 -0
  147. package/dist/runtime/slice.js +11 -0
  148. package/dist/runtime/ssr.js +240 -0
  149. package/dist/runtime/static-query.js +47 -0
  150. package/dist/utils.js +4 -0
  151. package/package.json +105 -3
  152. package/types/graphql-tada.d.ts +223 -0
  153. package/types/graphql.d.ts +2 -0
  154. package/types/index.d.ts +2287 -0
  155. package/types/node.d.ts +380 -0
  156. package/types/reporter.d.ts +187 -0
  157. package/types/router.d.ts +102 -0
  158. package/types/vendor/gql-tada.d.ts +2529 -0
@@ -0,0 +1,83 @@
1
+ import { store } from "../redux/index.js";
2
+ import { slash } from "../utils/paths.js";
3
+ import fs from "node:fs";
4
+ // src/node/vite/source-files.ts
5
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6
+ const isWindows = process.platform === "win32";
7
+ /**
8
+ * The slashed real path(s) of a directory, as they can appear in Vite's module ids. On Windows,
9
+ * fs.realpathSync keeps 8.3 short names (C:/Users/RUNNER~1, e.g. in %TEMP%) while
10
+ * fs.realpathSync.native expands them (C:/Users/runneradmin), and Vite resolves with either (the JS
11
+ * one until `net use` has answered, then the native one), so both forms are returned there.
12
+ */
13
+ function realDirs(dir) {
14
+ let real;
15
+ try {
16
+ real = slash(fs.realpathSync(dir));
17
+ } catch {
18
+ return [dir];
19
+ }
20
+ if (!isWindows) return [real];
21
+ try {
22
+ const native = slash(fs.realpathSync.native(dir));
23
+ return native === real ? [real] : [real, native];
24
+ } catch {
25
+ return [real];
26
+ }
27
+ }
28
+ /** Windows paths are case-insensitive (NTFS), and their spelling can differ between sources */
29
+ const comparable = (p) => isWindows ? p.toLowerCase() : p;
30
+ /**
31
+ * Directories of the site's plugins that are installed in node_modules: slashed real paths, like the
32
+ * module ids Vite uses (a plugin configured by path, or a `plugins/` entry, can be a symlink into
33
+ * node_modules/.pnpm).
34
+ */
35
+ function nodeModulesPluginDirs() {
36
+ return store.getState().flattenedPlugins.map((p) => p.resolve).filter((dir) => typeof dir === "string").flatMap(realDirs).filter((dir) => dir.includes("/node_modules/"));
37
+ }
38
+ /** The site's plugins installed in node_modules: package name and (real, slashed) directory. */
39
+ function nodeModulesPlugins() {
40
+ const plugins = /* @__PURE__ */ new Map();
41
+ for (const plugin of store.getState().flattenedPlugins) {
42
+ if (typeof plugin.resolve !== "string") continue;
43
+ const dir = realDirs(plugin.resolve)[0];
44
+ if (dir.includes("/node_modules/")) plugins.set(plugin.name, dir);
45
+ }
46
+ return [...plugins].map(([name, dir]) => ({
47
+ name,
48
+ dir
49
+ }));
50
+ }
51
+ /**
52
+ * Package names of the site's plugins installed in node_modules (by real path, as above). The dev
53
+ * server renders them through Vite with the site's transforms instead of loading their sources with
54
+ * Node, which can't run JSX or extensionless imports, and doesn't pre-bundle them, because
55
+ * gatsby-browser files import their modules by path (a pre-bundled copy would duplicate them, e.g.
56
+ * React contexts). Builds bundle every package anyway.
57
+ */
58
+ function nodeModulesPluginNames() {
59
+ const names = /* @__PURE__ */ new Set();
60
+ for (const plugin of store.getState().flattenedPlugins) if (typeof plugin.resolve === "string" && realDirs(plugin.resolve).some((dir) => dir.includes("/node_modules/"))) names.add(plugin.name);
61
+ return [...names];
62
+ }
63
+ /**
64
+ * Whether `file` is compiled like the site's own sources (TypeScript, JSX in `.js`, `<html>`/`<body>`
65
+ * in `Head`, styled-components): everything outside node_modules (incl. linked workspace
66
+ * packages), gatsby themes, and the files of plugins installed from npm (e.g. their
67
+ * `gatsby-browser.ts`/`gatsby-ssr.tsx`), but not the plugins' own dependencies.
68
+ */
69
+ function isSourceFile(file, pluginDirs = nodeModulesPluginDirs()) {
70
+ file = comparable(file);
71
+ if (!file.includes("/node_modules/")) return true;
72
+ if (file.slice(file.lastIndexOf("/node_modules/")).startsWith("/node_modules/gatsby-theme-")) return true;
73
+ return pluginDirs.map(comparable).some((dir) => file.startsWith(`${dir}/`) && !file.slice(dir.length).includes("/node_modules/"));
74
+ }
75
+ /**
76
+ * The same rule as {@link isSourceFile}, as one RegExp matching the node_modules files that are *not*
77
+ * compiled (Vite's `oxc.exclude` only takes patterns).
78
+ */
79
+ function nonSourceNodeModulesRe(pluginDirs = nodeModulesPluginDirs()) {
80
+ const plugins = pluginDirs.length ? `(?!(?:${pluginDirs.map(escapeRe).join("|")})/(?!(?:.*/)?node_modules/))` : "";
81
+ return new RegExp(`^${plugins}.*/node_modules/(?!gatsby-theme-|.*/node_modules/)`, isWindows ? "i" : "");
82
+ }
83
+ export { isSourceFile, nodeModulesPluginDirs, nodeModulesPluginNames, nodeModulesPlugins, nonSourceNodeModulesRe };
@@ -0,0 +1,136 @@
1
+ import { runPreprocessSource } from "../query/compile.js";
2
+ import { store } from "../redux/index.js";
3
+ import { slash } from "../utils/paths.js";
4
+ import { isSourceFile, nodeModulesPluginDirs } from "./source-files.js";
5
+ import { createRequire } from "node:module";
6
+ import path from "node:path";
7
+ import fs from "node:fs";
8
+ import { MagicString } from "magic-string";
9
+ // src/node/vite/static-image.ts
10
+ const BABEL_PLUGIN_RE = /(^|[\\/])babel-plugin-parse-static-images(\.js)?$/;
11
+ /**
12
+ * The `cacheDir` and package of gatsby-plugin-image's `babel-plugin-parse-static-images`, which its
13
+ * onCreateBabelConfig registers via `setBabelPlugin` (for every stage).
14
+ */
15
+ function findStaticImageBabelPlugin(stage) {
16
+ const stages = store.getState().babelrc.stages;
17
+ const candidates = [stage, ...Object.keys(stages).filter((s) => s !== stage)];
18
+ for (const s of candidates) {
19
+ const match = (stages[s]?.plugins ?? []).find((p) => typeof p?.name === "string" && BABEL_PLUGIN_RE.test(p.name));
20
+ if (match?.options?.cacheDir) return {
21
+ pluginFile: match.name,
22
+ cacheDir: match.options.cacheDir
23
+ };
24
+ }
25
+ return null;
26
+ }
27
+ /** gatsby-plugin-image's own parser and helpers, so the hashes match its preprocessSource */
28
+ function loadHelpers(pluginFile) {
29
+ const req = createRequire(pluginFile);
30
+ const traverse = req("@babel/traverse");
31
+ return {
32
+ traverse: traverse.default ?? traverse,
33
+ babelParseToAst: req("./node-apis/parser").babelParseToAst,
34
+ ...req("./babel-helpers")
35
+ };
36
+ }
37
+ /**
38
+ * Replaces gatsby-plugin-image's `babel-plugin-parse-static-images` (goatly runs no Babel):
39
+ * gives each `<StaticImage>` the image data that the plugin's `preprocessSource` generated during
40
+ * query extraction, as an `__imageData` prop (imported from `.cache/caches/gatsby-plugin-image`),
41
+ * or an `__error` prop that the component shows. Props whose value isn't known at build time are
42
+ * reported like Gatsby does. `preprocessSource` runs for each file first (once per contents, shared
43
+ * with query extraction): for files outside src/, and for files that changed in develop.
44
+ */
45
+ function staticImagePlugin(options) {
46
+ const pluginDirs = nodeModulesPluginDirs();
47
+ const ownDir = `${slash(path.dirname(path.dirname(options.pluginFile)))}/`;
48
+ let helpers;
49
+ return {
50
+ name: "goatly:static-image",
51
+ enforce: "pre",
52
+ configureServer(server) {
53
+ fs.mkdirSync(options.cacheDir, { recursive: true });
54
+ const timers = /* @__PURE__ */ new Map();
55
+ const watcher = fs.watch(options.cacheDir, (_event, name) => {
56
+ if (!name?.endsWith(".json")) return;
57
+ const file = slash(path.join(options.cacheDir, name));
58
+ clearTimeout(timers.get(file));
59
+ timers.set(file, setTimeout(() => {
60
+ timers.delete(file);
61
+ for (const env of Object.values(server.environments)) for (const mod of env.moduleGraph.getModulesByFile(file) ?? []) {
62
+ env.moduleGraph.invalidateModule(mod);
63
+ if (env.name === "client") env.reloadModule(mod);
64
+ }
65
+ }, 50));
66
+ });
67
+ const close = server.close.bind(server);
68
+ server.close = async () => {
69
+ watcher.close();
70
+ for (const timer of timers.values()) clearTimeout(timer);
71
+ timers.clear();
72
+ return close();
73
+ };
74
+ },
75
+ transform: {
76
+ filter: {
77
+ id: /\.(m?[jt]sx?|[mc]ts|cjs)(\?|$)/,
78
+ code: "StaticImage"
79
+ },
80
+ async handler(code, id) {
81
+ const file = id.split("?")[0];
82
+ if (!code.includes("gatsby-plugin-image") || file.startsWith(ownDir)) return null;
83
+ if (!isSourceFile(file, pluginDirs)) return null;
84
+ helpers ??= loadHelpers(options.pluginFile);
85
+ const { traverse, babelParseToAst, evaluateImageAttributes, hashOptions } = helpers;
86
+ const found = [];
87
+ traverse(babelParseToAst(code, file), { JSXOpeningElement(nodePath) {
88
+ if (!nodePath.get("name").referencesImport("gatsby-plugin-image", "StaticImage")) return;
89
+ const unresolved = [];
90
+ const props = evaluateImageAttributes(nodePath, (prop) => unresolved.push(prop));
91
+ props.filename = slash(file);
92
+ found.push({
93
+ at: nodePath.node.name.end,
94
+ hash: hashOptions(props),
95
+ props,
96
+ error: unresolved.length ? `Could not find values for the following props at build time: ${unresolved.join(", ")}` : void 0
97
+ });
98
+ } });
99
+ if (!found.length) return null;
100
+ const dataFile = (hash) => path.join(options.cacheDir, `${hash}.json`);
101
+ const contents = await fs.promises.readFile(file, "utf8").catch(() => code);
102
+ await runPreprocessSource(file, contents);
103
+ const s = new MagicString(code);
104
+ const imports = [];
105
+ for (const [i, image] of found.entries()) {
106
+ if (image.error) this.warn(`[gatsby-plugin-image] ${image.error}`);
107
+ const json = dataFile(image.hash);
108
+ const hasData = image.props.src !== void 0 && fs.existsSync(json);
109
+ let attrs = "";
110
+ if (!hasData) {
111
+ const message = `No data found for image "${image.props.src}"\n${image.error ?? ""}${image.props.src === void 0 ? "" : `Could not read image data file "${json}". This may mean that the images in "${file}" were not processed.`}`;
112
+ this.warn(`[gatsby-plugin-image] ${message}`);
113
+ attrs = ` __error={${JSON.stringify(message)}}`;
114
+ } else {
115
+ const name = `__goatlyStaticImage${i}`;
116
+ imports.push(`import ${name} from ${JSON.stringify(slash(json))};`);
117
+ if (image.error) attrs += ` __error={${JSON.stringify(image.error)}}`;
118
+ attrs += ` __imageData={${name}}`;
119
+ this.addWatchFile(json);
120
+ }
121
+ s.appendLeft(image.at, attrs);
122
+ }
123
+ const start = code.startsWith("#!") ? code.indexOf("\n") + 1 : 0;
124
+ if (imports.length) s.appendLeft(start, imports.join(""));
125
+ return {
126
+ code: s.toString(),
127
+ map: s.generateMap({
128
+ hires: "boundary",
129
+ source: file
130
+ })
131
+ };
132
+ }
133
+ }
134
+ };
135
+ }
136
+ export { findStaticImageBabelPlugin, staticImagePlugin };
@@ -0,0 +1,73 @@
1
+ import { store } from "../redux/index.js";
2
+ import { isSourceFile, nodeModulesPluginDirs } from "./source-files.js";
3
+ import { transformWithOxc } from "vite";
4
+ // src/node/vite/styled-components.ts
5
+ const BABEL_PLUGIN_RE = /(^|[\\/])babel-plugin-styled-components([\\/]|$)/;
6
+ /**
7
+ * Options of `babel-plugin-styled-components` registered via `setBabelPlugin` (e.g. by
8
+ * gatsby-plugin-styled-components) for `stage`. Several registrations merge their options in
9
+ * order, like Gatsby's reducer. Without one for `stage`, another stage's apply: `setBabelPlugin`
10
+ * without a stage registers for "develop" only.
11
+ */
12
+ function findStyledComponentsBabelOptions(stage) {
13
+ const stages = store.getState().babelrc.stages;
14
+ const candidates = [stage, ...Object.keys(stages).filter((s) => s !== stage)];
15
+ for (const s of candidates) {
16
+ const matches = (stages[s]?.plugins ?? []).filter((p) => typeof p?.name === "string" && BABEL_PLUGIN_RE.test(p.name));
17
+ if (matches.length) return Object.assign({}, ...matches.map((p) => p.options ?? {}));
18
+ }
19
+ return null;
20
+ }
21
+ /** Maps babel-plugin-styled-components options to Oxc's built-in styled-components transform. */
22
+ function toOxcStyledComponentsOptions(babel) {
23
+ return {
24
+ displayName: babel.displayName ?? true,
25
+ fileName: babel.fileName ?? true,
26
+ minify: babel.minify ?? true,
27
+ pure: babel.pure ?? false,
28
+ ...babel.namespace ? { namespace: babel.namespace } : {},
29
+ ...babel.topLevelImportPaths?.length ? { topLevelImportPaths: babel.topLevelImportPaths } : {},
30
+ ...babel.meaninglessFileNames ? { meaninglessFileNames: babel.meaninglessFileNames } : {},
31
+ ssr: true,
32
+ transpileTemplateLiterals: false
33
+ };
34
+ }
35
+ function langFor(file) {
36
+ if (/\.[mc]?ts$/.test(file)) return "ts";
37
+ if (file.endsWith(".tsx")) return "tsx";
38
+ return "jsx";
39
+ }
40
+ /**
41
+ * Replaces `babel-plugin-styled-components` (goatly runs no Babel): adds `displayName` and a
42
+ * stable `componentId` to every styled component, like Gatsby did. Applies to the files Gatsby ran
43
+ * the site's Babel config on: everything outside node_modules (incl. linked workspace packages),
44
+ * gatsby themes and the files of plugins installed from npm.
45
+ */
46
+ function styledComponentsPlugin(babelOptions) {
47
+ const options = toOxcStyledComponentsOptions(babelOptions);
48
+ const importPaths = ["styled-components", ...options.topLevelImportPaths ?? []];
49
+ const pluginDirs = nodeModulesPluginDirs();
50
+ return {
51
+ name: "goatly:styled-components",
52
+ enforce: "pre",
53
+ transform: {
54
+ filter: { id: /\.(m?[jt]sx?|[mc]ts|cjs)(\?|$)/ },
55
+ async handler(code, id) {
56
+ const file = id.split("?")[0];
57
+ if (!isSourceFile(file, pluginDirs)) return null;
58
+ if (!importPaths.some((p) => code.includes(p))) return null;
59
+ const out = await transformWithOxc(code, file, {
60
+ lang: langFor(file),
61
+ jsx: "preserve",
62
+ sourcemap: true,
63
+ plugins: { styledComponents: options }
64
+ });
65
+ return {
66
+ code: out.code,
67
+ map: out.map
68
+ };
69
+ }
70
+ }
71
+ };
72
+ }
73
+ export { findStyledComponentsBabelOptions, styledComponentsPlugin, toOxcStyledComponentsOptions };
@@ -0,0 +1,299 @@
1
+ import { extractFromSource } from "../query/extract.js";
2
+ import { getStaticExports } from "../plugins/static-exports.js";
3
+ import { parseSync, walk } from "../utils/parser.js";
4
+ import path from "node:path";
5
+ import { MagicString } from "magic-string";
6
+ // src/node/vite/transforms.ts
7
+ /**
8
+ * Transforms `graphql` documents (tags and `graphql()` calls): static queries become imports of
9
+ * their result module, page queries and fragments are replaced by their hash. `exportsPageQuery`:
10
+ * the module exports a page query (which only runs if the module is a page component).
11
+ */
12
+ function transformGraphQLTags(code, id, opts) {
13
+ const file = id.split("?")[0];
14
+ const extraction = extractFromSource(file, code);
15
+ if (extraction.error || extraction.tags.length === 0) return null;
16
+ const s = new MagicString(code);
17
+ const imports = /* @__PURE__ */ new Set();
18
+ let exportsPageQuery = false;
19
+ for (const tag of extraction.tags) {
20
+ if (tag.kind === "page" && tag.exportName) exportsPageQuery = true;
21
+ if (extraction.tags.some((o) => o !== tag && o.start <= tag.start && tag.end <= o.end)) continue;
22
+ if (tag.kind === "static") {
23
+ const local = `__goatly_sq_${tag.hash}`;
24
+ imports.add(`import ${local} from ${JSON.stringify(`${opts.virtualPrefix}${tag.hash}`)};`);
25
+ s.overwrite(tag.start, tag.end, local);
26
+ } else s.overwrite(tag.start, tag.end, JSON.stringify(tag.hash));
27
+ }
28
+ s.prepend(`${[...imports].join("\n")}\n`);
29
+ return {
30
+ code: s.toString(),
31
+ map: s.generateMap({
32
+ hires: "boundary",
33
+ source: file
34
+ }),
35
+ exportsPageQuery
36
+ };
37
+ }
38
+ function langFor(file) {
39
+ const ext = path.extname(file);
40
+ if (ext === ".ts" || ext === ".mts" || ext === ".cts") return "ts";
41
+ if (ext === ".tsx") return "tsx";
42
+ return "jsx";
43
+ }
44
+ /**
45
+ * Rewrites `<html ...>` / `<body ...>` JSX (used inside `Head` exports) to components that set
46
+ * document attributes. React 19 would otherwise treat them as document singletons, React 18 would
47
+ * render real `<html>`/`<body>` elements inside the Head container. Children of react-helmet's (or
48
+ * react-helmet-async's) `<Helmet>` stay: it reads them as props instead of rendering them.
49
+ */
50
+ function transformHtmlBodyJsx(code, id, headTagsModule) {
51
+ if (!/<(html|body)[\s/>]/.test(code)) return null;
52
+ const file = id.split("?")[0];
53
+ let program;
54
+ try {
55
+ program = parseSync(file, code, { lang: langFor(file) }).program;
56
+ } catch {
57
+ return null;
58
+ }
59
+ const s = new MagicString(code);
60
+ let changed = false;
61
+ const visit = (node) => {
62
+ if (!node || typeof node !== "object") return;
63
+ if (Array.isArray(node)) {
64
+ node.forEach(visit);
65
+ return;
66
+ }
67
+ if (node.type === "JSXElement" && node.openingElement?.name?.name === "Helmet") return;
68
+ if ((node.type === "JSXOpeningElement" || node.type === "JSXClosingElement") && node.name?.type === "JSXIdentifier") {
69
+ const name = node.name.name;
70
+ if (name === "html" || name === "body") {
71
+ s.overwrite(node.name.start, node.name.end, name === "html" ? "__GoatlyHtmlAttributes" : "__GoatlyBodyAttributes");
72
+ changed = true;
73
+ }
74
+ }
75
+ for (const key in node) {
76
+ if (key === "start" || key === "end" || key === "type") continue;
77
+ const v = node[key];
78
+ if (v && typeof v === "object") visit(v);
79
+ }
80
+ };
81
+ visit(program);
82
+ if (!changed) return null;
83
+ s.prepend(`import { HtmlAttributes as __GoatlyHtmlAttributes, BodyAttributes as __GoatlyBodyAttributes } from ${JSON.stringify(headTagsModule)};\n`);
84
+ return {
85
+ code: s.toString(),
86
+ map: s.generateMap({
87
+ hires: "boundary",
88
+ source: file
89
+ })
90
+ };
91
+ }
92
+ /** What `require(x)` returns, given `import * as ns from x` (CommonJS, ESM and asset modules). */
93
+ const REQUIRE_INTEROP = `function __goatly_interop(ns) { if (ns && ns.default !== undefined && Object.keys(ns).filter((k) => k !== "default" && k !== "__esModule").length === 0) return ns.default; return ns && ns.__esModule ? ns : (ns && ns.default && typeof ns.default === "object" ? Object.assign({}, ns.default, ns) : ns) }`;
94
+ /**
95
+ * Converts a CommonJS gatsby-browser / gatsby-ssr file (`exports.onRouteUpdate = ...`,
96
+ * `require("./global.css")`) into ESM so Vite can serve it unbundled in development. Export names
97
+ * found statically (`exports.a = `, `module.exports = { a, b }`) also become named exports, so
98
+ * ESM modules can `import { a } from` it, as with bundlers.
99
+ */
100
+ function transformCommonJsApiFile(code, file) {
101
+ const named = file ? getStaticExports(file, code).filter((name) => /^[A-Za-z_$][\w$]*$/.test(name) && name !== "default" && name !== "__esModule") : [];
102
+ const calls = findStaticRequires(code, file ?? "module.cjs", "commonjs");
103
+ if (!calls) return null;
104
+ const imports = [];
105
+ const s = new MagicString(code);
106
+ calls.forEach((call, i) => {
107
+ const local = `__goatly_req_${i}`;
108
+ imports.push(`import * as ${local}__ns from ${JSON.stringify(call.spec)};`);
109
+ imports.push(`const ${local} = __goatly_interop(${local}__ns);`);
110
+ s.overwrite(call.start, call.end, local);
111
+ });
112
+ return `${imports.join("\n")}
113
+ ${REQUIRE_INTEROP}
114
+ const module = { exports: {} };
115
+ (function (exports, module) {
116
+ ${s.toString()}
117
+ }).call(module.exports, module.exports, module);
118
+ export default module.exports;
119
+ ${named.map((name, i) => `const __goatly_export_${i} = module.exports[${JSON.stringify(name)}];`).join("\n")}
120
+ ${named.length ? `export { ${named.map((name, i) => `__goatly_export_${i} as ${name}`).join(", ")} };` : ""}
121
+ `;
122
+ }
123
+ /**
124
+ * Rewrites `require("x")` calls in an ES module (e.g. `import React from "react"` next to
125
+ * `require("./global.css")` or `const logo = require("./logo.png")`, which webpack accepted) to
126
+ * imports, so the module also runs unbundled in development, where `require` is not defined (in
127
+ * the browser and in Vite's SSR module runner). Only calls with a static string are rewritten; the
128
+ * imports are hoisted, so the required modules are evaluated before the module, not at the call.
129
+ * Scopes that bind `require` themselves are left alone.
130
+ */
131
+ function transformRequireInEsm(code, id) {
132
+ if (!/\brequire\s*\(/.test(code)) return null;
133
+ const file = id.split("?")[0];
134
+ const calls = findStaticRequires(code, file, "module");
135
+ if (!calls?.length) return null;
136
+ const s = new MagicString(code);
137
+ const locals = /* @__PURE__ */ new Map();
138
+ const imports = [];
139
+ for (const call of calls) {
140
+ let local = locals.get(call.spec);
141
+ if (!local) {
142
+ local = `__goatly_esm_req_${locals.size}`;
143
+ locals.set(call.spec, local);
144
+ imports.push(`import * as ${local}__ns from ${JSON.stringify(call.spec)};`);
145
+ imports.push(`const ${local} = __goatly_interop(${local}__ns);`);
146
+ }
147
+ s.overwrite(call.start, call.end, local);
148
+ }
149
+ s.prepend(`${imports.join("\n")}\n${REQUIRE_INTEROP}\n`);
150
+ return {
151
+ code: s.toString(),
152
+ map: s.generateMap({
153
+ hires: "boundary",
154
+ source: file
155
+ })
156
+ };
157
+ }
158
+ /**
159
+ * `import * as ns` of a converted CommonJS module, as Rolldown's `__toESM` builds it: the exports
160
+ * object of a transpiled ES module (`__esModule`), else `module.exports`' own properties (also
161
+ * non-enumerable ones, and its prototype's, e.g. a class instance's methods) plus `default`
162
+ */
163
+ const CJS_NAMESPACE = `function __goatly_cjs_ns(m) { if (m && m.__esModule) return m; if (m === null || (typeof m !== "object" && typeof m !== "function")) return { default: m }; const ns = Object.create(Object.getPrototypeOf(m)); for (const k of Object.getOwnPropertyNames(m)) if (k !== "default") Object.defineProperty(ns, k, { get: () => m[k], enumerable: true }); Object.defineProperty(ns, "default", { value: m, enumerable: true }); return ns }`;
164
+ /**
165
+ * Rewrites imports of CommonJS modules in an ES module served unbundled in development (the
166
+ * packages of plugins, which Vite does not pre-bundle, and their dependencies). The dev server
167
+ * converts those CommonJS modules to ESM with `module.exports` as the default export and only the
168
+ * export names it finds statically, so `import * as PropTypes from "prop-types"` (whose
169
+ * `module.exports` is a function call) would get only `default`, and `import { a } from` a name set
170
+ * dynamically would not link. Like webpack and Rolldown, a namespace import gets `module.exports`'
171
+ * properties plus `default`, named imports of names the module doesn't export statically read
172
+ * `module.exports`' properties, and the default import of a module compiled from ESM
173
+ * (`__esModule`) is `exports.default`. Only those bindings become constants (initialized where the
174
+ * import was); the others stay import bindings. `cjsExports(spec)`: `null` when `spec` doesn't
175
+ * resolve to such a CommonJS module.
176
+ */
177
+ async function transformCjsImportsInEsm(code, id, cjsExports) {
178
+ if (!/\bimport\s*(?:[\w$]+\s*(?:,|from\b)|[*{])/.test(code)) return null;
179
+ const file = id.split("?")[0];
180
+ let parsed;
181
+ try {
182
+ parsed = parseSync(file, code, {
183
+ lang: langFor(file),
184
+ sourceType: "module"
185
+ });
186
+ } catch {
187
+ return null;
188
+ }
189
+ if (parsed.errors?.length) return null;
190
+ const s = new MagicString(code);
191
+ const importedName = (sp) => sp.imported.name ?? sp.imported.value;
192
+ let changed = false;
193
+ for (const [i, stmt] of parsed.program.body.entries()) {
194
+ if (stmt.type !== "ImportDeclaration" || stmt.importKind === "type") continue;
195
+ const specifiers = stmt.specifiers.filter((sp) => sp.importKind !== "type");
196
+ const namespace = specifiers.find((sp) => sp.type === "ImportNamespaceSpecifier");
197
+ const defaults = specifiers.filter((sp) => sp.type === "ImportDefaultSpecifier" || sp.type === "ImportSpecifier" && importedName(sp) === "default");
198
+ const named = specifiers.filter((sp) => sp.type === "ImportSpecifier" && importedName(sp) !== "default");
199
+ if (!namespace && !named.length && !defaults.length) continue;
200
+ const target = await cjsExports(stmt.source.value);
201
+ if (!target) continue;
202
+ const dynamic = named.filter((sp) => !target.names.includes(importedName(sp)));
203
+ if (!namespace && !dynamic.length && !(target.esModule && defaults.length)) continue;
204
+ const liveDefault = !target.esModule && defaults.find((sp) => sp.type === "ImportDefaultSpecifier");
205
+ const local = liveDefault ? liveDefault.local.name : `__goatly_cjs_${i}`;
206
+ const kept = named.filter((sp) => !dynamic.includes(sp));
207
+ if (!target.esModule) kept.push(...defaults.filter((sp) => sp !== liveDefault));
208
+ const keptList = kept.map((sp) => importedName(sp) === sp.local.name ? sp.local.name : `${JSON.stringify(importedName(sp))} as ${sp.local.name}`);
209
+ let out = `import ${local}${keptList.length ? `, { ${keptList.join(", ")} }` : ""} from ${JSON.stringify(stmt.source.value)};`;
210
+ if (target.esModule) for (const sp of defaults) out += ` const ${sp.local.name} = ${local}.default;`;
211
+ if (namespace) out += ` const ${namespace.local.name} = __goatly_cjs_ns(${local});`;
212
+ if (dynamic.length) {
213
+ const fields = dynamic.map((sp) => `${JSON.stringify(importedName(sp))}: ${sp.local.name}`);
214
+ out += ` const { ${fields.join(", ")} } = ${local};`;
215
+ }
216
+ s.overwrite(stmt.start, stmt.end, out);
217
+ changed = true;
218
+ }
219
+ if (!changed) return null;
220
+ s.append(`\n${CJS_NAMESPACE}\n`);
221
+ return {
222
+ code: s.toString(),
223
+ map: s.generateMap({
224
+ hires: "boundary",
225
+ source: file
226
+ })
227
+ };
228
+ }
229
+ const isRequireId = (n) => n?.type === "Identifier" && n.name === "require";
230
+ /**
231
+ * The `require("x")` calls with a static string (or a template literal without expressions) that
232
+ * refer to the global `require`, not to one a surrounding scope binds (a parameter, or a declaration
233
+ * in the function or file outside nested functions; block scoping is not distinguished). `null` if
234
+ * the code does not parse, or (for `"module"`) has no import/export statements.
235
+ */
236
+ function findStaticRequires(code, file, sourceType) {
237
+ let parsed;
238
+ try {
239
+ parsed = parseSync(file, code, {
240
+ lang: langFor(file),
241
+ sourceType
242
+ });
243
+ } catch {
244
+ return null;
245
+ }
246
+ if (parsed.errors?.length) return null;
247
+ if (sourceType === "module" && !parsed.module?.hasModuleSyntax) return null;
248
+ const program = parsed.program;
249
+ const binding = /* @__PURE__ */ new Set();
250
+ const scopes = [program];
251
+ const bind = (n) => isRequireId(n) && binding.add(scopes[scopes.length - 1]);
252
+ const enterFn = (fn) => {
253
+ scopes.push(fn);
254
+ if (fn.params.some(isRequireId)) binding.add(fn);
255
+ };
256
+ const exitFn = () => scopes.pop();
257
+ walk(program, {
258
+ FunctionDeclaration(fn) {
259
+ bind(fn.id);
260
+ enterFn(fn);
261
+ },
262
+ "FunctionDeclaration:exit": exitFn,
263
+ FunctionExpression: enterFn,
264
+ "FunctionExpression:exit": exitFn,
265
+ ArrowFunctionExpression: enterFn,
266
+ "ArrowFunctionExpression:exit": exitFn,
267
+ VariableDeclarator: (n) => bind(n.id),
268
+ ClassDeclaration: (n) => bind(n.id),
269
+ CatchClause: (n) => bind(n.param),
270
+ ImportSpecifier: (n) => bind(n.local),
271
+ ImportDefaultSpecifier: (n) => bind(n.local),
272
+ ImportNamespaceSpecifier: (n) => bind(n.local)
273
+ });
274
+ if (binding.has(program)) return [];
275
+ const calls = [];
276
+ let shadowed = 0;
277
+ const enter = (fn) => binding.has(fn) && shadowed++;
278
+ const exit = (fn) => binding.has(fn) && shadowed--;
279
+ walk(program, {
280
+ FunctionDeclaration: enter,
281
+ "FunctionDeclaration:exit": exit,
282
+ FunctionExpression: enter,
283
+ "FunctionExpression:exit": exit,
284
+ ArrowFunctionExpression: enter,
285
+ "ArrowFunctionExpression:exit": exit,
286
+ CallExpression(node) {
287
+ if (shadowed || !isRequireId(node.callee) || node.arguments.length !== 1) return;
288
+ const arg = node.arguments[0];
289
+ const spec = arg.type === "Literal" && typeof arg.value === "string" ? arg.value : arg.type === "TemplateLiteral" && arg.expressions.length === 0 ? arg.quasis[0].value.cooked : null;
290
+ if (spec != null) calls.push({
291
+ start: node.start,
292
+ end: node.end,
293
+ spec
294
+ });
295
+ }
296
+ });
297
+ return calls;
298
+ }
299
+ export { transformCjsImportsInEsm, transformCommonJsApiFile, transformGraphQLTags, transformHtmlBodyJsx, transformRequireInEsm };