goatly 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +874 -1
  2. package/bin/goatly.js +99 -0
  3. package/dist/cli/index.js +234 -0
  4. package/dist/compat/gatsby-node-entry.js +16 -0
  5. package/dist/compat/gatsby-package.json +6 -0
  6. package/dist/compat/md5-file.js +47 -0
  7. package/dist/compat-apis.json +72 -0
  8. package/dist/compat-apis.json.js +62 -0
  9. package/dist/graphql.js +3 -0
  10. package/dist/node/actions/index.js +619 -0
  11. package/dist/node/actions/job-store.js +180 -0
  12. package/dist/node/actions/jobs.js +174 -0
  13. package/dist/node/api-runner.js +258 -0
  14. package/dist/node/bootstrap.js +569 -0
  15. package/dist/node/build/assets.js +110 -0
  16. package/dist/node/build/incremental.js +208 -0
  17. package/dist/node/build/index.js +763 -0
  18. package/dist/node/build/memory-governor.js +450 -0
  19. package/dist/node/build/output-dirs.js +70 -0
  20. package/dist/node/build/page-data.js +40 -0
  21. package/dist/node/build/page-files.js +186 -0
  22. package/dist/node/build/partitioned-state.js +258 -0
  23. package/dist/node/build/query-worker.js +626 -0
  24. package/dist/node/build/query-workers.js +863 -0
  25. package/dist/node/build/render-thread.js +103 -0
  26. package/dist/node/build/render-worker.js +162 -0
  27. package/dist/node/build/state.js +24 -0
  28. package/dist/node/build/timing-breakdown.js +216 -0
  29. package/dist/node/build/work-clock.js +75 -0
  30. package/dist/node/build/worker-pool.js +242 -0
  31. package/dist/node/cache-layout.js +99 -0
  32. package/dist/node/cache.js +1430 -0
  33. package/dist/node/compat/chokidar-shim.js +148 -0
  34. package/dist/node/compat/core-utils-lmdb.js +145 -0
  35. package/dist/node/compat/create-node-id-shim.js +1 -0
  36. package/dist/node/compat/module-hooks.js +245 -0
  37. package/dist/node/compat/redux-shim.js +1 -0
  38. package/dist/node/config/index.js +162 -0
  39. package/dist/node/config/not-found-pages.js +95 -0
  40. package/dist/node/datastore/codec.js +144 -0
  41. package/dist/node/datastore/index.js +127 -0
  42. package/dist/node/datastore/logfile/cache.js +89 -0
  43. package/dist/node/datastore/logfile/index.js +1329 -0
  44. package/dist/node/datastore/logfile/record.js +71 -0
  45. package/dist/node/datastore/types.js +1 -0
  46. package/dist/node/develop/express-compat.js +207 -0
  47. package/dist/node/develop/graphiql.js +22 -0
  48. package/dist/node/develop/hydration-report.js +41 -0
  49. package/dist/node/develop/index.js +618 -0
  50. package/dist/node/develop/local-url.js +10 -0
  51. package/dist/node/develop/ssr-runner.js +66 -0
  52. package/dist/node/gql.js +5 -0
  53. package/dist/node/index.js +15 -0
  54. package/dist/node/info.js +270 -0
  55. package/dist/node/internal-plugins/data-bridge.js +196 -0
  56. package/dist/node/internal-plugins/page-creator.js +318 -0
  57. package/dist/node/loader/import-module.js +160 -0
  58. package/dist/node/node-helpers.js +66 -0
  59. package/dist/node/not-found-pages.js +220 -0
  60. package/dist/node/plugins/api-list.js +12 -0
  61. package/dist/node/plugins/load-plugins.js +427 -0
  62. package/dist/node/plugins/resolve-plugin.js +79 -0
  63. package/dist/node/plugins/static-exports.js +64 -0
  64. package/dist/node/query/compile.js +326 -0
  65. package/dist/node/query/dependencies.js +45 -0
  66. package/dist/node/query/execute.js +417 -0
  67. package/dist/node/query/extract.js +372 -0
  68. package/dist/node/query/gql-tada-introspection.js +124 -0
  69. package/dist/node/query/graphql-env.js +231 -0
  70. package/dist/node/query/graphql-runner.js +79 -0
  71. package/dist/node/redux/actions.js +1 -0
  72. package/dist/node/redux/index.js +133 -0
  73. package/dist/node/redux/node-changes.js +128 -0
  74. package/dist/node/redux/reducers.js +193 -0
  75. package/dist/node/redux/state.js +71 -0
  76. package/dist/node/renderer.js +124 -0
  77. package/dist/node/reporter-transports.js +259 -0
  78. package/dist/node/reporter.js +497 -0
  79. package/dist/node/schema/date.js +539 -0
  80. package/dist/node/schema/extensions.js +315 -0
  81. package/dist/node/schema/index.js +542 -0
  82. package/dist/node/schema/infer.js +388 -0
  83. package/dist/node/schema/inline-objects.js +128 -0
  84. package/dist/node/schema/naming.js +20 -0
  85. package/dist/node/schema/node-model.js +207 -0
  86. package/dist/node/schema/query-engine.js +1808 -0
  87. package/dist/node/schema/resolver-kinds.js +7 -0
  88. package/dist/node/schema/resolvers.js +273 -0
  89. package/dist/node/schema/type-builders.js +45 -0
  90. package/dist/node/schema/types.js +241 -0
  91. package/dist/node/serve.js +90 -0
  92. package/dist/node/site-page-nodes.js +277 -0
  93. package/dist/node/types.js +1 -0
  94. package/dist/node/utils/content-digest.js +107 -0
  95. package/dist/node/utils/cpus.js +104 -0
  96. package/dist/node/utils/create-node-id.js +51 -0
  97. package/dist/node/utils/env.js +25 -0
  98. package/dist/node/utils/fs-retry.js +74 -0
  99. package/dist/node/utils/memory-signals.js +441 -0
  100. package/dist/node/utils/memory.js +657 -0
  101. package/dist/node/utils/murmurhash.js +32 -0
  102. package/dist/node/utils/parser.js +33 -0
  103. package/dist/node/utils/partition-hash.js +19 -0
  104. package/dist/node/utils/paths.js +122 -0
  105. package/dist/node/utils/resolver.js +48 -0
  106. package/dist/node/utils/runtime.js +5 -0
  107. package/dist/node/utils/serializable.js +41 -0
  108. package/dist/node/utils/strings.js +41 -0
  109. package/dist/node/vite/config.js +289 -0
  110. package/dist/node/vite/paths.js +12 -0
  111. package/dist/node/vite/plugin-deps.js +232 -0
  112. package/dist/node/vite/plugin.js +283 -0
  113. package/dist/node/vite/react-compiler.js +362 -0
  114. package/dist/node/vite/source-files.js +83 -0
  115. package/dist/node/vite/static-image.js +136 -0
  116. package/dist/node/vite/styled-components.js +73 -0
  117. package/dist/node/vite/transforms.js +330 -0
  118. package/dist/node/wasm-data/host.js +406 -0
  119. package/dist/node/wasm-data/lower.js +406 -0
  120. package/dist/node/wasm-data/runner.js +79 -0
  121. package/dist/node/wasm-data/worker.js +95 -0
  122. package/dist/reporter.js +5 -0
  123. package/dist/runtime/api-runner.js +81 -0
  124. package/dist/runtime/app.js +256 -0
  125. package/dist/runtime/client-entry.js +4 -0
  126. package/dist/runtime/client.js +383 -0
  127. package/dist/runtime/default-html.js +31 -0
  128. package/dist/runtime/head-markup.js +100 -0
  129. package/dist/runtime/head-sync.js +101 -0
  130. package/dist/runtime/head-tags.js +45 -0
  131. package/dist/runtime/hydration-report.js +111 -0
  132. package/dist/runtime/index.js +12 -0
  133. package/dist/runtime/link.js +293 -0
  134. package/dist/runtime/loader.js +449 -0
  135. package/dist/runtime/not-found.js +61 -0
  136. package/dist/runtime/page-renderer.js +35 -0
  137. package/dist/runtime/preamble.js +47 -0
  138. package/dist/runtime/react-compat.js +14 -0
  139. package/dist/runtime/renderer-shared.js +10 -0
  140. package/dist/runtime/renderers/react-client.js +14 -0
  141. package/dist/runtime/renderers/react-server.js +99 -0
  142. package/dist/runtime/renderers/react.js +17 -0
  143. package/dist/runtime/renderers/types.js +1 -0
  144. package/dist/runtime/root-error-handlers.js +29 -0
  145. package/dist/runtime/router/history.js +132 -0
  146. package/dist/runtime/router/index.js +240 -0
  147. package/dist/runtime/router/utils.js +118 -0
  148. package/dist/runtime/script.js +110 -0
  149. package/dist/runtime/scroll.js +40 -0
  150. package/dist/runtime/slice.js +11 -0
  151. package/dist/runtime/ssr.js +240 -0
  152. package/dist/runtime/static-query.js +47 -0
  153. package/dist/utils.js +4 -0
  154. package/package.json +105 -3
  155. package/types/graphql-tada.d.ts +223 -0
  156. package/types/graphql.d.ts +2 -0
  157. package/types/index.d.ts +2287 -0
  158. package/types/node.d.ts +389 -0
  159. package/types/reporter.d.ts +187 -0
  160. package/types/router.d.ts +102 -0
  161. package/types/vendor/gql-tada.d.ts +2529 -0
@@ -0,0 +1,256 @@
1
+ import { BaseContext, LocationContext, navigate } from "./router/index.js";
2
+ import { StaticQueryUsageContext } from "./static-query.js";
3
+ import { HtmlAttributeCollectorContext } from "./head-tags.js";
4
+ import { grabMatchParams, isNotFoundPagePath, stripPrefix } from "./loader.js";
5
+ import { ApiRunnerContext, wrapElement } from "./api-runner.js";
6
+ import { headMode } from "./renderer-shared.js";
7
+ import { HeadPortal } from "./head-sync.js";
8
+ import { createContext, createElement, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
9
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
10
+ // src/runtime/app.tsx
11
+ const RouteAnnouncerProps = {
12
+ id: "gatsby-announcer",
13
+ style: {
14
+ position: "absolute",
15
+ top: 0,
16
+ width: 1,
17
+ height: 1,
18
+ padding: 0,
19
+ overflow: "hidden",
20
+ clip: "rect(0, 0, 0, 0)",
21
+ whiteSpace: "nowrap",
22
+ border: 0
23
+ },
24
+ "aria-live": "assertive",
25
+ "aria-atomic": "true"
26
+ };
27
+ const useIsoLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
28
+ function RouteAnnouncer({ location }) {
29
+ const [announcement, setAnnouncement] = useState("");
30
+ const first = useRef(true);
31
+ useEffect(() => {
32
+ if (first.current) {
33
+ first.current = false;
34
+ return;
35
+ }
36
+ requestAnimationFrame(() => {
37
+ let pageName = `new page at ${location.pathname}`;
38
+ if (document.title) pageName = document.title;
39
+ const h1 = document.querySelector("#gatsby-focus-wrapper h1");
40
+ if (h1) pageName = h1.textContent ?? pageName;
41
+ setAnnouncement(`Navigated to ${pageName}`);
42
+ });
43
+ }, [location.key, location.pathname]);
44
+ return createElement("div", RouteAnnouncerProps, announcement);
45
+ }
46
+ /**
47
+ * The page's `path` prop – also its key, like Gatsby's: pages that share a component (a template, a
48
+ * collection route) mount it anew instead of keeping the previous page's state. (Not a client-only
49
+ * route's URLs: they share the page's matchPath.)
50
+ */
51
+ function pagePath(location, pageResources) {
52
+ const { page } = pageResources;
53
+ const isErrorPage = !!pageResources.notFound || isNotFoundPagePath(page.path) || page.path === "/500.html";
54
+ return encodeURI(isErrorPage ? stripPrefix(location.pathname, __BASE_PATH__) : page.matchPath || page.path);
55
+ }
56
+ function pageProps(location, pageResources, nav) {
57
+ const { page, json } = pageResources;
58
+ const params = {
59
+ ...grabMatchParams(location.pathname, page.matchPath),
60
+ ...json?.pageContext?.__params
61
+ };
62
+ return {
63
+ path: pagePath(location, pageResources),
64
+ uri: location.pathname,
65
+ location,
66
+ navigate: nav,
67
+ pageResources,
68
+ ...json,
69
+ data: json?.data,
70
+ pageContext: json?.pageContext ?? {},
71
+ params,
72
+ serverData: void 0,
73
+ children: void 0
74
+ };
75
+ }
76
+ function PageRenderer({ location, pageResources, pageKey, runner, nav }) {
77
+ const props = pageProps(location, pageResources, nav);
78
+ const key = pageKey ?? props.path;
79
+ const element = createElement(pageResources.component, {
80
+ ...props,
81
+ key
82
+ });
83
+ return wrapElement(runner, "wrapPageElement", element, { props });
84
+ }
85
+ /**
86
+ * Renders the page's `Head` export, by the renderer's head mode:
87
+ * - "hoist" (react-dom 19): inside the app tree. The renderer hoists `<title>`, `<meta>` and
88
+ * `<link>` into `<head>` itself (SSR: the hoisted preamble is moved into the document head;
89
+ * hydration adopts it).
90
+ * - "portal" (react-dom 18): inside the app tree too, but through `HeadPortal` (a detached element
91
+ * synced into `document.head`) on the client, and separately through `HeadRoot` + `headMarkup` on
92
+ * the server.
93
+ */
94
+ function HeadRenderer({ location, pageResources }) {
95
+ const Head = pageResources.head;
96
+ if (typeof Head !== "function") return null;
97
+ const { json, page } = pageResources;
98
+ const params = {
99
+ ...grabMatchParams(location.pathname, page.matchPath),
100
+ ...json?.pageContext?.__params
101
+ };
102
+ return createElement(Head, {
103
+ location: { pathname: location.pathname },
104
+ params,
105
+ data: json?.data ?? {},
106
+ pageContext: json?.pageContext ?? {},
107
+ serverData: void 0
108
+ });
109
+ }
110
+ /** The current `RouteState`, read below `wrapRootElement` (see `useAppContexts`). */
111
+ const RouteStateContext = createContext(null);
112
+ const basePath = typeof __BASE_PATH__ !== "undefined" && __BASE_PATH__ || "/";
113
+ const ROOT_BASE = Object.freeze({
114
+ baseuri: basePath,
115
+ basepath: basePath
116
+ });
117
+ /**
118
+ * The element passed to `wrapRootElement`: the location contexts around the body. It reads the
119
+ * route state from context, so the element itself never changes and `wrapRootElement` runs once
120
+ * per root, like Gatsby – a store or client created in it survives navigations.
121
+ */
122
+ function LocationContexts({ body: Body }) {
123
+ const route = useContext(RouteStateContext);
124
+ const { location, navigate } = route;
125
+ const locationValue = useMemo(() => ({
126
+ location,
127
+ navigate
128
+ }), [location, navigate]);
129
+ return /* @__PURE__ */ jsx(LocationContext.Provider, {
130
+ value: locationValue,
131
+ children: /* @__PURE__ */ jsx(BaseContext.Provider, {
132
+ value: ROOT_BASE,
133
+ children: /* @__PURE__ */ jsx(Body, { ...route })
134
+ })
135
+ });
136
+ }
137
+ /**
138
+ * The SSR collectors' providers, always rendered (null values in the browser), so the server and
139
+ * hydration trees have the same shape. A new collector: a field in `SsrSinks` and a provider here.
140
+ */
141
+ function SsrSinksProvider({ sinks, children }) {
142
+ return /* @__PURE__ */ jsx(StaticQueryUsageContext.Provider, {
143
+ value: sinks?.staticQueryUsage ?? null,
144
+ children: /* @__PURE__ */ jsx(HtmlAttributeCollectorContext.Provider, {
145
+ value: sinks?.htmlAttributes ?? null,
146
+ children
147
+ })
148
+ });
149
+ }
150
+ /**
151
+ * Everything around the body: the runner and SSR collector contexts (constant per root), then
152
+ * wrapRootElement around the location contexts. Shared by `AppRoot` and `HeadRoot`, so the Head
153
+ * export gets the same contexts on the server (portal head mode: separate render) as in the
154
+ * browser.
155
+ *
156
+ * `wrapRootElement` is called once, on the first render (a hook: call it unconditionally); later
157
+ * renders (navigations) only update the route state context below it. Context values only change
158
+ * when what they carry does: memoized consumers inside wrapRootElement are not re-rendered by a
159
+ * navigation unless they read the location. (`StaticQueryContext` is not provided: its default
160
+ * is stable, and a user's provider – also one around the root – takes effect.)
161
+ */
162
+ function useAppContexts(props, body) {
163
+ const { location, pageResources, runner } = props;
164
+ const navigate$1 = props.navigate ?? navigate;
165
+ const [wrapped] = useState(() => wrapElement(runner, "wrapRootElement", createElement(LocationContexts, { body }), props.wrapRootPathname === null ? {} : { pathname: props.wrapRootPathname ?? location.pathname }));
166
+ const { pageKey } = props;
167
+ const route = useMemo(() => ({
168
+ location,
169
+ pageResources,
170
+ navigate: navigate$1,
171
+ pageKey
172
+ }), [
173
+ location,
174
+ pageResources,
175
+ navigate$1,
176
+ pageKey
177
+ ]);
178
+ return /* @__PURE__ */ jsx(ApiRunnerContext.Provider, {
179
+ value: runner,
180
+ children: /* @__PURE__ */ jsx(SsrSinksProvider, {
181
+ sinks: props.ssr,
182
+ children: /* @__PURE__ */ jsx(RouteStateContext.Provider, {
183
+ value: route,
184
+ children: wrapped
185
+ })
186
+ })
187
+ });
188
+ }
189
+ /** The page, route announcer and Head – rendered inside `wrapRootElement`. */
190
+ function PageBody({ location, pageResources, navigate, pageKey }) {
191
+ const runner = useContext(ApiRunnerContext);
192
+ const head = /* @__PURE__ */ jsx(HeadRenderer, {
193
+ location,
194
+ pageResources
195
+ });
196
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [
197
+ /* @__PURE__ */ jsx("div", {
198
+ style: { outline: "none" },
199
+ tabIndex: -1,
200
+ id: "gatsby-focus-wrapper",
201
+ children: /* @__PURE__ */ jsx(PageRenderer, {
202
+ location,
203
+ pageResources,
204
+ pageKey,
205
+ runner,
206
+ nav: navigate
207
+ })
208
+ }),
209
+ /* @__PURE__ */ jsx(RouteAnnouncer, { location }),
210
+ headMode === "portal" ? /* @__PURE__ */ jsx(HeadPortal, { children: head }) : head
211
+ ] });
212
+ }
213
+ function HeadBody({ location, pageResources }) {
214
+ return /* @__PURE__ */ jsx(HeadRenderer, {
215
+ location,
216
+ pageResources
217
+ });
218
+ }
219
+ /**
220
+ * The application tree. Used *identically* for SSR (build & develop) and for hydration,
221
+ * so `React.useId()` and any other tree-position based logic produce matching results.
222
+ */
223
+ function AppRoot(props) {
224
+ const { location, pageResources, onCommit, onBeforePaint } = props;
225
+ useIsoLayoutEffect(() => {
226
+ onBeforePaint?.(location);
227
+ }, [
228
+ location.key,
229
+ location.pathname,
230
+ pageResources
231
+ ]);
232
+ useEffect(() => {
233
+ onCommit?.(location, pageResources);
234
+ }, [
235
+ location.key,
236
+ location.pathname,
237
+ pageResources
238
+ ]);
239
+ return useAppContexts(props, PageBody);
240
+ }
241
+ /** Portal head mode SSR: the Head export alone, with the same contexts (incl. wrapRootElement) as in `AppRoot`. */
242
+ function HeadRoot(props) {
243
+ return useAppContexts(props, HeadBody);
244
+ }
245
+ /** Stateful root used on server and client (state only changes on the client). */
246
+ function Root({ initial, subscribe, ...rest }) {
247
+ const [state, setState] = useState(initial);
248
+ useEffect(() => subscribe?.(setState), []);
249
+ return /* @__PURE__ */ jsx(AppRoot, {
250
+ ...rest,
251
+ location: state.location,
252
+ pageResources: state.pageResources,
253
+ pageKey: state.pageKey
254
+ });
255
+ }
256
+ export { ApiRunnerContext, AppRoot, HeadRoot, Root, RouteAnnouncerProps, pagePath };
@@ -0,0 +1,4 @@
1
+ import { startClient } from "./client.js";
2
+ // src/runtime/client-entry.ts
3
+ startClient();
4
+ export {};
@@ -0,0 +1,383 @@
1
+ import { createApiRunner } from "./api-runner.js";
2
+ import { Root, pagePath } from "./app.js";
3
+ import { findPath, hasNotFoundSections, isNotFoundPageForUrl, isNotFoundPageOwnUrl, isNotFoundPagePath, loader, normalizePagePath, onNotFoundPagesChange } from "./loader.js";
4
+ import { globalHistory } from "./router/history.js";
5
+ import { notFoundLookupPath } from "./not-found.js";
6
+ import { setNavigateImplementation } from "./router/index.js";
7
+ import { parsePath } from "./link.js";
8
+ import { sessionStorageScroll } from "./scroll.js";
9
+ import { installHydrationReporter } from "./hydration-report.js";
10
+ import { rootErrorHandlers } from "./root-error-handlers.js";
11
+ import { createElement } from "react";
12
+ import { mount } from "virtual:goatly/renderer-client";
13
+ import browserPlugins from "virtual:goatly/browser-plugins";
14
+ import redirects from "virtual:goatly/redirects";
15
+ import runtimeConfig from "virtual:goatly/runtime-config";
16
+ // src/runtime/client.tsx
17
+ const runner = createApiRunner(browserPlugins, () => ({
18
+ getResourceURLsForPathname: (p) => loader.getResourceURLsForPathname(p),
19
+ loadPage: (p) => loader.loadPage(p),
20
+ loadPageSync: (p) => loader.loadPageSync(p)
21
+ }));
22
+ function createEmitter() {
23
+ const listeners = /* @__PURE__ */ new Map();
24
+ return {
25
+ on(e, cb) {
26
+ if (!listeners.has(e)) listeners.set(e, /* @__PURE__ */ new Set());
27
+ listeners.get(e).add(cb);
28
+ },
29
+ off(e, cb) {
30
+ listeners.get(e)?.delete(cb);
31
+ },
32
+ emit(e, d) {
33
+ listeners.get(e)?.forEach((cb) => cb(d));
34
+ }
35
+ };
36
+ }
37
+ const redirectMap = /* @__PURE__ */ new Map();
38
+ const redirectIgnoreCaseMap = /* @__PURE__ */ new Map();
39
+ for (const r of redirects) {
40
+ if (!r.redirectInBrowser) continue;
41
+ if (r.ignoreCase) redirectIgnoreCaseMap.set(r.fromPath.toLowerCase(), r);
42
+ else redirectMap.set(r.fromPath, r);
43
+ }
44
+ function findRedirect(pathname) {
45
+ const alt = pathname.endsWith("/") ? pathname.slice(0, -1) : `${pathname}/`;
46
+ return redirectMap.get(pathname) ?? redirectMap.get(alt) ?? redirectIgnoreCaseMap.get(pathname.toLowerCase()) ?? redirectIgnoreCaseMap.get(alt.toLowerCase());
47
+ }
48
+ let currentState;
49
+ let setRootState;
50
+ let prevLocation = null;
51
+ let pendingAction = "PUSH";
52
+ let initialRenderDone = false;
53
+ let lastCommittedLocation = "";
54
+ let lastScrolledLocation = "";
55
+ function saveScroll(location) {
56
+ if (location) sessionStorageScroll.save(location.pathname, location.key, [window.scrollX, window.scrollY]);
57
+ }
58
+ function findHashTarget(hash) {
59
+ if (!hash) return void 0;
60
+ let id = hash.slice(1);
61
+ try {
62
+ id = decodeURIComponent(id);
63
+ } catch {}
64
+ return document.getElementById(id) ?? document.getElementsByName(id)[0];
65
+ }
66
+ function scrollToHash(hash) {
67
+ const el = findHashTarget(hash);
68
+ el?.scrollIntoView();
69
+ return !!el;
70
+ }
71
+ /**
72
+ * Runs `shouldUpdateScroll` and applies a position or element id it returned. Returns whether the
73
+ * caller should go on with the default scroll behaviour (no plugin answered, or one returned `true`).
74
+ */
75
+ function askShouldUpdateScroll(location, prev) {
76
+ const results = runner.apiRunner("shouldUpdateScroll", {
77
+ prevRouterProps: prev ? { location: prev } : void 0,
78
+ routerProps: { location },
79
+ pathname: location.pathname,
80
+ getSavedScrollPosition: (loc, key) => sessionStorageScroll.read(loc.pathname, key ?? loc.key)
81
+ });
82
+ const decision = results.length ? results[results.length - 1] : true;
83
+ if (decision === false) return false;
84
+ if (Array.isArray(decision)) {
85
+ window.scrollTo(decision[0], decision[1]);
86
+ return false;
87
+ }
88
+ if (typeof decision === "string") {
89
+ document.getElementById(decision)?.scrollIntoView();
90
+ return false;
91
+ }
92
+ return true;
93
+ }
94
+ /**
95
+ * The first render (e.g. after a reload): scrolls to the hash target or restores the saved position,
96
+ * if `shouldUpdateScroll` agrees. Like Gatsby's ScrollHandler on mount, plugins are only asked when
97
+ * there is something to scroll to, without `prevRouterProps`.
98
+ */
99
+ function initialScroll(location) {
100
+ const target = findHashTarget(location.hash);
101
+ const saved = location.hash ? void 0 : sessionStorageScroll.read(location.pathname, location.key);
102
+ if (!target && !Array.isArray(saved)) return;
103
+ if (!askShouldUpdateScroll(location, null)) return;
104
+ if (target) target.scrollIntoView();
105
+ else if (Array.isArray(saved)) window.scrollTo(saved[0], saved[1]);
106
+ }
107
+ function updateScroll(location) {
108
+ if (!initialRenderDone) return;
109
+ const id = `${location.key}|${location.pathname}|${location.hash}`;
110
+ if (id === lastScrolledLocation) return;
111
+ lastScrolledLocation = id;
112
+ if (!askShouldUpdateScroll(location, prevLocation)) return;
113
+ if (pendingAction === "POP") {
114
+ const saved = sessionStorageScroll.read(location.pathname, location.key);
115
+ if (Array.isArray(saved)) {
116
+ window.scrollTo(saved[0], saved[1]);
117
+ return;
118
+ }
119
+ }
120
+ if (!scrollToHash(location.hash)) window.scrollTo(0, 0);
121
+ }
122
+ async function resolveResources(location) {
123
+ const path = location.pathname + location.search;
124
+ return loader.loadPageSync(path) ?? await loader.loadPage(path);
125
+ }
126
+ async function onLocationChange(location, action) {
127
+ pendingAction = action;
128
+ const resources = await resolveResources(location);
129
+ if (!resources) {
130
+ window.location.reload();
131
+ return;
132
+ }
133
+ prevLocation = currentState?.location ?? null;
134
+ currentState = {
135
+ location,
136
+ pageResources: resources
137
+ };
138
+ setRootState?.(currentState);
139
+ }
140
+ async function navigateImpl(to, options = {}) {
141
+ if (typeof to === "number") {
142
+ globalHistory.navigate(to);
143
+ return;
144
+ }
145
+ let { pathname, search, hash } = parsePath(to);
146
+ const redirect = findRedirect(pathname);
147
+ if (redirect) {
148
+ to = redirect.toPath;
149
+ ({pathname, search, hash} = parsePath(to));
150
+ if (/^[a-z]+:/i.test(to)) {
151
+ window.location.assign(to);
152
+ return;
153
+ }
154
+ }
155
+ if (window.___swUpdated) {
156
+ window.location.href = pathname + search + hash;
157
+ return;
158
+ }
159
+ const current = currentState?.location;
160
+ saveScroll(current);
161
+ if (current && current.pathname === pathname && current.search === search && hash && !options.replace) {
162
+ await globalHistory.navigate(to, options);
163
+ return;
164
+ }
165
+ const target = {
166
+ ...current ?? globalHistory.location,
167
+ pathname,
168
+ search,
169
+ hash
170
+ };
171
+ runner.apiRunner("onPreRouteUpdate", {
172
+ location: target,
173
+ prevLocation: current ?? null
174
+ });
175
+ const delayTimer = setTimeout(() => {
176
+ window.___emitter?.emit("onDelayedLoadPageResources", { pathname });
177
+ runner.apiRunner("onRouteUpdateDelayed", { location: target });
178
+ }, 1e3);
179
+ let resources = null;
180
+ try {
181
+ resources = await loader.loadPage(pathname + search);
182
+ } catch {
183
+ resources = null;
184
+ }
185
+ clearTimeout(delayTimer);
186
+ if (!resources) {
187
+ window.location.href = to;
188
+ return;
189
+ }
190
+ await globalHistory.navigate(to, options);
191
+ }
192
+ function registerServiceWorker() {
193
+ if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator)) return;
194
+ if (!runner.apiRunner("registerServiceWorker", {}).some(Boolean)) return;
195
+ if (window.location.protocol !== "https:" && window.location.hostname !== "localhost") return;
196
+ navigator.serviceWorker.register(`${__BASE_PATH__}/sw.js`).then((reg) => {
197
+ reg.addEventListener("updatefound", () => {
198
+ runner.apiRunner("onServiceWorkerUpdateFound", { serviceWorker: reg });
199
+ const installing = reg.installing;
200
+ installing?.addEventListener("statechange", () => {
201
+ switch (installing.state) {
202
+ case "installed":
203
+ if (navigator.serviceWorker.controller) {
204
+ window.___swUpdated = true;
205
+ runner.apiRunner("onServiceWorkerUpdateReady", { serviceWorker: reg });
206
+ } else runner.apiRunner("onServiceWorkerInstalled", { serviceWorker: reg });
207
+ break;
208
+ case "redundant":
209
+ runner.apiRunner("onServiceWorkerRedundant", { serviceWorker: reg });
210
+ break;
211
+ case "activated": runner.apiRunner("onServiceWorkerActive", { serviceWorker: reg });
212
+ }
213
+ });
214
+ });
215
+ });
216
+ }
217
+ /** develop: forwards hydration mismatches to the dev server's terminal (set before rendering) */
218
+ let reportRecoverableError;
219
+ function defaultRenderer(element, container) {
220
+ mount(element, container, {
221
+ onRecoverableError(error, info) {
222
+ if (process.env.NODE_ENV !== "production") {
223
+ console.error("[goatly] hydration error", error);
224
+ reportRecoverableError?.(error, info);
225
+ }
226
+ },
227
+ ...rootErrorHandlers(runner)
228
+ });
229
+ }
230
+ /** Starts the Gatsby compatible client runtime. */
231
+ async function startClient() {
232
+ globalThis.___goatlyBrowserApiRunner = runner;
233
+ window.___emitter = createEmitter();
234
+ window.___loader = loader;
235
+ window.___navigate = (to, options) => void navigateImpl(to, options);
236
+ window.___push = (to) => void navigateImpl(to, { replace: false });
237
+ window.___replace = (to) => void navigateImpl(to, { replace: true });
238
+ setNavigateImplementation((to, options) => navigateImpl(to, options));
239
+ loader.setBuildHash(window.___buildHash ?? runtimeConfig.buildHash);
240
+ if ("scrollRestoration" in window.history) window.history.scrollRestoration = "manual";
241
+ runner.apiRunner("onClientEntry");
242
+ const redirect = findRedirect(window.location.pathname);
243
+ if (redirect) {
244
+ window.location.replace(redirect.toPath);
245
+ return;
246
+ }
247
+ const browserLoc = globalHistory.location;
248
+ const here = browserLoc.pathname + browserLoc.search;
249
+ const pagePath$1 = window.pagePath;
250
+ const urlPage = normalizePagePath(findPath(browserLoc.pathname));
251
+ const urlPath = normalizePagePath(notFoundLookupPath(browserLoc.pathname, __BASE_PATH__));
252
+ const servedNotFound = isNotFoundPagePath(pagePath$1) && !isNotFoundPageOwnUrl(pagePath$1, urlPage);
253
+ const toRoute = servedNotFound && urlPage !== urlPath;
254
+ const toSection = servedNotFound && !toRoute && !isNotFoundPageForUrl(pagePath$1, here);
255
+ const loadServed = async () => {
256
+ const served = window.___pageData ? await loader.resourcesFromPageData(window.___pageData, servedNotFound) : pagePath$1 ? await loader.loadPage(pagePath$1) : null;
257
+ return served && servedNotFound && !served.notFound ? {
258
+ ...served,
259
+ notFound: true
260
+ } : served;
261
+ };
262
+ let served = null;
263
+ let resources;
264
+ if (toRoute || toSection) {
265
+ const [shown, resolved] = await Promise.all([hasNotFoundSections() ? loadServed().catch(() => null) : null, toRoute ? loader.loadPage(here) : loader.loadNotFoundPage(here)]);
266
+ served = shown;
267
+ resources = resolved ?? shown;
268
+ } else resources = await loadServed();
269
+ if (!resources) resources = await loader.loadPage(here);
270
+ if (!resources) {
271
+ console.error(`[goatly] page resources for ${browserLoc.pathname} not found`);
272
+ return;
273
+ }
274
+ const isSpecial = !!resources.page.matchPath || !!resources.notFound || isNotFoundPagePath(resources.page.path) || /^\/(404|500)(\/?|\.html)$/.test(resources.page.path);
275
+ if (pagePath$1 && !isSpecial && __BASE_PATH__ + pagePath$1 !== browserLoc.pathname) window.history.replaceState(window.history.state, "", __BASE_PATH__ + pagePath$1 + browserLoc.search + browserLoc.hash);
276
+ const location = globalHistory.location;
277
+ loader.setPageResources(location.pathname + location.search, resources);
278
+ currentState = {
279
+ location,
280
+ pageResources: resources
281
+ };
282
+ const renderedPath = window.___renderedPath;
283
+ const renderedElsewhere = !!renderedPath && renderedPath !== location.pathname;
284
+ const hydrateState = (renderedElsewhere || served) && document.getElementById("___gatsby")?.hasChildNodes() ? {
285
+ location: renderedElsewhere ? {
286
+ ...location,
287
+ pathname: renderedPath,
288
+ search: "",
289
+ hash: ""
290
+ } : location,
291
+ pageResources: served ?? resources,
292
+ pageKey: pagePath(currentState.location, currentState.pageResources)
293
+ } : currentState;
294
+ let hydratingWithRenderedPath = hydrateState !== currentState;
295
+ let pendingSwitch = false;
296
+ const trySwitch = () => {
297
+ if (pendingSwitch && setRootState) {
298
+ pendingSwitch = false;
299
+ setRootState(currentState);
300
+ }
301
+ };
302
+ globalHistory.listen(({ location: loc, action }) => {
303
+ onLocationChange(loc, action);
304
+ });
305
+ let scrollTicking = false;
306
+ window.addEventListener("scroll", () => {
307
+ if (scrollTicking) return;
308
+ scrollTicking = true;
309
+ requestAnimationFrame(() => {
310
+ scrollTicking = false;
311
+ saveScroll(currentState?.location);
312
+ });
313
+ }, { passive: true });
314
+ const element = createElement(Root, {
315
+ initial: hydrateState,
316
+ runner,
317
+ subscribe(set) {
318
+ setRootState = set;
319
+ trySwitch();
320
+ return () => {
321
+ setRootState = void 0;
322
+ };
323
+ },
324
+ onBeforePaint: (loc) => updateScroll(loc),
325
+ onCommit(loc) {
326
+ globalHistory._onTransitionComplete();
327
+ if (hydratingWithRenderedPath) {
328
+ hydratingWithRenderedPath = false;
329
+ pendingSwitch = true;
330
+ trySwitch();
331
+ return;
332
+ }
333
+ const id = `${loc.key}|${loc.pathname}|${loc.search}|${loc.hash}`;
334
+ if (id === lastCommittedLocation) return;
335
+ lastCommittedLocation = id;
336
+ if (!initialRenderDone) {
337
+ initialRenderDone = true;
338
+ lastScrolledLocation = `${loc.key}|${loc.pathname}|${loc.hash}`;
339
+ runner.apiRunner("onRouteUpdate", {
340
+ location: loc,
341
+ prevLocation: null
342
+ });
343
+ runner.apiRunner("onInitialClientRender");
344
+ initialScroll(loc);
345
+ return;
346
+ }
347
+ runner.apiRunner("onRouteUpdate", {
348
+ location: loc,
349
+ prevLocation
350
+ });
351
+ document.getElementById("gatsby-focus-wrapper")?.focus({ preventScroll: true });
352
+ }
353
+ });
354
+ const container = document.getElementById("___gatsby");
355
+ const hot = import.meta.hot;
356
+ if (hot && process.env.NODE_ENV !== "production" && container.hasChildNodes()) reportRecoverableError = installHydrationReporter(hot);
357
+ runner.apiRunner("onPreRouteUpdate", {
358
+ location: currentState.location,
359
+ prevLocation: null
360
+ });
361
+ (runner.apiRunner("replaceHydrateFunction", {}, void 0).find((r) => typeof r === "function") ?? defaultRenderer)(element, container);
362
+ registerServiceWorker();
363
+ if (hot) {
364
+ const refresh = async () => {
365
+ loader.invalidate();
366
+ const loc = currentState.location;
367
+ const fresh = await loader.loadPage(loc.pathname + loc.search);
368
+ if (fresh) {
369
+ currentState = {
370
+ location: loc,
371
+ pageResources: fresh
372
+ };
373
+ setRootState?.(currentState);
374
+ }
375
+ };
376
+ hot.on("goatly:data-update", refresh);
377
+ onNotFoundPagesChange(() => {
378
+ const shown = currentState?.pageResources;
379
+ if (shown && (shown.notFound || isNotFoundPagePath(shown.page.path))) refresh();
380
+ });
381
+ }
382
+ }
383
+ export { startClient };
@@ -0,0 +1,31 @@
1
+ import { jsx, jsxs } from "react/jsx-runtime";
2
+ // src/runtime/default-html.tsx
3
+ /** Same markup as Gatsby's default `html.js` */
4
+ function HTML(props) {
5
+ return /* @__PURE__ */ jsxs("html", {
6
+ ...props.htmlAttributes,
7
+ children: [/* @__PURE__ */ jsxs("head", { children: [
8
+ /* @__PURE__ */ jsx("meta", { charSet: "utf-8" }),
9
+ /* @__PURE__ */ jsx("meta", {
10
+ httpEquiv: "x-ua-compatible",
11
+ content: "ie=edge"
12
+ }),
13
+ /* @__PURE__ */ jsx("meta", {
14
+ name: "viewport",
15
+ content: "width=device-width, initial-scale=1, shrink-to-fit=no"
16
+ }),
17
+ props.headComponents
18
+ ] }), /* @__PURE__ */ jsxs("body", {
19
+ ...props.bodyAttributes,
20
+ children: [
21
+ props.preBodyComponents,
22
+ /* @__PURE__ */ jsx("div", {
23
+ id: "___gatsby",
24
+ dangerouslySetInnerHTML: { __html: props.body }
25
+ }, "body"),
26
+ props.postBodyComponents
27
+ ]
28
+ })]
29
+ });
30
+ }
31
+ export { HTML as default };