@opsydyn/astro-foldkit 0.12.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.13.1](https://github.com/opsydyn/fold-kit-experiments/compare/astro-foldkit-v0.13.0...astro-foldkit-v0.13.1) (2026-11-23)
4
+
5
+ ### Bug Fixes
6
+
7
+ - ship the widened FoldKit 0.171 peer ranges, and record the upgrade ([#189](https://github.com/opsydyn/fold-kit-experiments/issues/189)) ([44a06de](https://github.com/opsydyn/fold-kit-experiments/commit/44a06dea64fcaa1ead7c87460f352ab75fc1aa86))
8
+
9
+ ## [0.13.0](https://github.com/opsydyn/fold-kit-experiments/compare/astro-foldkit-v0.12.0...astro-foldkit-v0.13.0) (2026-11-13)
10
+
11
+ ### Features
12
+
13
+ - **astro-foldkit:** preload the chunk chain of islands that boot at load ([6d7eaef](https://github.com/opsydyn/fold-kit-experiments/commit/6d7eaefadfac9c05347184ee954d4cacdb3ea04c))
14
+
3
15
  ## [0.12.0](https://github.com/opsydyn/fold-kit-experiments/compare/astro-foldkit-v0.11.0...astro-foldkit-v0.12.0) (2026-11-12)
4
16
 
5
17
  ### Features
package/README.md CHANGED
@@ -1,13 +1,13 @@
1
1
  # @opsydyn/astro-foldkit
2
2
 
3
3
  Astro integration and renderer for [FoldKit](https://foldkit.dev), with
4
- client-only islands and an opt-in server-rendered page path.
4
+ islands that can pre-render, and an opt-in server-rendered page path.
5
5
 
6
- FoldKit is an Elm Architecture runtime built on [Effect](https://effect.website). This package registers FoldKit as an Astro renderer so you can drop any FoldKit app into a `.astro` page as a component and hydrate it with `client:load`.
6
+ FoldKit is an Elm Architecture runtime built on [Effect](https://effect.website). This package registers FoldKit as an Astro renderer so you can drop any FoldKit app into a `.astro` page as a component, and choose per island whether and when it ships JavaScript.
7
7
 
8
8
  There are two deliberately separate entry paths:
9
9
 
10
- - `lazyApp` / `defineApp` keeps the existing client-only island contract. Astro receives a deterministic mount shell and FoldKit starts in the browser.
10
+ - `lazyApp` / `defineApp` registers an island. By default Astro receives a deterministic empty mount shell and FoldKit starts in the browser. With `{ prerender: true }` the island's first render is in the HTML, so it can ship with no directive and no JavaScript, or hydrate later with `client:visible` or this package's `client:interaction`. See [Choosing when JavaScript runs](#choosing-when-javascript-runs).
11
11
  - `definePage` opts one FoldKit application into SSG or request SSR. The server emits FoldKit HTML and public Flags, and `client:load` hydrates that exact DOM.
12
12
 
13
13
  ## Installation
@@ -26,8 +26,9 @@ npm install astro foldkit
26
26
 
27
27
  ## FoldKit compatibility
28
28
 
29
- `@opsydyn/astro-foldkit` targets FoldKit `0.167.x` to `0.169.x`, stable Effect
30
- `4.0.0`, and the matching `@foldkit/vite-plugin` `0.28.x` line.
29
+ `@opsydyn/astro-foldkit` targets FoldKit `0.171.x`, Effect `4.1.x`, and the
30
+ matching `@foldkit/vite-plugin` `0.29.x` line. An application on an older FoldKit
31
+ needs an older release of this integration.
31
32
  Applications can define interruptible work with
32
33
  `Command.define(name, { interrupt: true, ... })` inside their own update loop;
33
34
  this integration continues to own Astro rendering, hydration, and lifecycle
@@ -59,8 +60,9 @@ in public HTML, so it must not contain secrets. Do not reuse it across deploymen
59
60
  with different rendering inputs. Blank `server.buildId` options are rejected, and FoldKit
60
61
  fails closed when neither a compiled identity nor an explicit override is available.
61
62
 
62
- See the [0.167 migration guide](../../docs/migrations/foldkit-0.167.md) for the
63
- subscription API changes and package compatibility checks.
63
+ See the [FoldKit 0.170 release notes](../../docs/releases/foldkit-0.170.md) for
64
+ the move to Effect 4.1, and the [0.167 migration guide](../../docs/migrations/foldkit-0.167.md)
65
+ for the earlier subscription API changes.
64
66
 
65
67
  ## Defining an app
66
68
 
@@ -115,10 +117,16 @@ particular on any page carrying more than one island. Drop it only when this
115
117
  island is meant to own the page title. See [`noMeta`](#nometa).
116
118
 
117
119
  For `lazyApp` / `defineApp`, the server renderer emits a deterministic
118
- `<div data-foldkit-island="true"></div>` mount shell. It does not load or
119
- execute the FoldKit application during SSR; the application is loaded and
120
- embedded only by the client renderer. Astro still owns the outer island
121
- serialisation and client directive behavior.
120
+ `<div data-foldkit-island="true"></div>` mount shell. Unless the island opts
121
+ into [pre-rendering](#pre-rendered-islands-opt-in), it does not load or execute
122
+ the FoldKit application during SSR; the application is loaded and embedded only
123
+ by the client renderer. Astro still owns the outer island serialisation and
124
+ client directive behavior.
125
+
126
+ In development the integration also adds every module that imports
127
+ `define-app` or `define-page` to Vite's dependency scan, so an island's
128
+ dependencies are bundled when the dev server starts rather than on the first
129
+ request that loads it.
122
130
 
123
131
  ### Pre-rendered islands (opt-in)
124
132
 
@@ -191,6 +199,29 @@ renders before any JavaScript runs. A chart that loses its hover readout by
191
199
  going static can keep the information as a native SVG `<title>` on each mark,
192
200
  which the browser shows as a tooltip and which costs no runtime.
193
201
 
202
+ #### Module preloads for islands that boot at load
203
+
204
+ An island's JavaScript arrives as a chain: Astro's bootstrap fetches the
205
+ renderer and the component module, the component's `load` imports the
206
+ application, and each chunk reveals its own imports only once it arrives.
207
+ Astro emits no preload hints for island chunks, so every link costs a round
208
+ trip.
209
+
210
+ For each pre-rendered page, the build adds a `<link rel="modulepreload">` at
211
+ the end of `<head>` for every chunk a `client:load` or `client:only` FoldKit
212
+ island needs to boot, so the browser fetches the chain in parallel. The links
213
+ follow the stylesheets, so they do not compete with render-blocking CSS. What
214
+ the application imports lazily stays lazy, and islands that defer their
215
+ download (`client:visible`, `client:idle`, `client:interaction`,
216
+ `client:media`) are left alone, as are other renderers' islands. Nothing needs
217
+ configuring.
218
+
219
+ On a server-rendered report page whose owner hydrates with `client:load`, at
220
+ 150 ms per request, this cut the time to hydration from 1,140 ms to 510 ms, five
221
+ sequential round trips down to two, with first paint unchanged.
222
+
223
+ Pages rendered on request are not on disk at build time and keep the chain.
224
+
194
225
  #### `client:interaction`
195
226
 
196
227
  The integration adds a `client:interaction` directive. It hydrates a
@@ -543,7 +574,9 @@ Schema/value. `defineApp` keeps the existing props-based `init` contract.
543
574
  | `@opsydyn/astro-foldkit/define-page` | `definePage`, `PageConfig`, and page Flags context types |
544
575
  | `@opsydyn/astro-foldkit/server` | Server-only `resolvePageDocument` metadata resolver |
545
576
 
546
- The root entry point also exports the `NavigationConfig`, `NavigationEvent`, and `NavigationPhase` types.
577
+ The root entry point also exports the `InteractionOptions`, `NavigationConfig`,
578
+ `NavigationEvent`, and `NavigationPhase` types, and declares the
579
+ `client:interaction` directive on Astro's `AstroClientDirectives`.
547
580
 
548
581
  ## Embedding
549
582
 
@@ -680,7 +713,8 @@ element.addEventListener(
680
713
  | Package | Version |
681
714
  | :-------- | :-------------------- |
682
715
  | `astro` | `≥ 5.0` |
683
- | `foldkit` | `≥ 0.167.0 < 0.170.0` |
716
+ | `effect` | `~4.1.0` |
717
+ | `foldkit` | `≥ 0.170.0 < 0.172.0` |
684
718
 
685
719
  ## Stateflow Observatory example
686
720
 
package/dist/index.mjs CHANGED
@@ -2,6 +2,7 @@ import { fileURLToPath } from "node:url";
2
2
  import { foldkit as foldkit$1 } from "@foldkit/vite-plugin";
3
3
  import { existsSync, readFileSync, readdirSync } from "node:fs";
4
4
  import { join, relative, sep } from "node:path";
5
+ import { readFile, readdir, writeFile } from "node:fs/promises";
5
6
  //#region src/island-scan.ts
6
7
  const scannable = /\.[cm]?[jt]s$/;
7
8
  const declaration = /\.d\.[cm]?ts$/;
@@ -24,24 +25,165 @@ const islandScanPlugin = (root, srcDir) => ({
24
25
  }
25
26
  });
26
27
  //#endregion
28
+ //#region src/preload.ts
29
+ /**
30
+ * Module preloads for FoldKit islands that boot at load.
31
+ *
32
+ * An island's JavaScript arrives as a chain: Astro's bootstrap fetches the
33
+ * renderer and the component module, the component's `load` imports the
34
+ * application, and each of those reveals its own imports only once it has
35
+ * arrived. Astro emits no preload hints for island chunks, so every link of
36
+ * the chain costs a round trip. For an island that boots at load, the whole
37
+ * chain is known at build time; listing it in the head lets the browser fetch
38
+ * it in parallel.
39
+ *
40
+ * Islands that defer their download (`client:visible`, `client:idle`,
41
+ * `client:interaction`, `client:media`) are left alone: preloading them would
42
+ * spend the bandwidth they were chosen to save.
43
+ */
44
+ /** Directives that boot an island as soon as the page loads. */
45
+ const eagerDirectives = new Set(["load", "only"]);
46
+ /**
47
+ * The chunks an island needs to boot: the renderer, the component module, the
48
+ * application its `load` imports, and everything those import statically.
49
+ * What the application imports lazily stays lazy.
50
+ */
51
+ const islandPreloads = (graph, rendererFile, componentFile) => {
52
+ const files = /* @__PURE__ */ new Set();
53
+ const visit = (file) => {
54
+ if (files.has(file)) return;
55
+ const node = graph.get(file);
56
+ if (node === void 0) return;
57
+ files.add(file);
58
+ for (const imported of node.imports) visit(imported);
59
+ };
60
+ visit(rendererFile);
61
+ visit(componentFile);
62
+ for (const loaded of graph.get(componentFile)?.dynamicImports ?? []) visit(loaded);
63
+ return [...files];
64
+ };
65
+ const islandTag = /<astro-island\b[^>]*>/g;
66
+ const attribute = /\s([\w:-]+)="([^"]*)"/g;
67
+ const attributesOf = (tag) => new Map([...tag.matchAll(attribute)].map((match) => [match[1] ?? "", match[2] ?? ""]));
68
+ const splitQuery = (url) => {
69
+ const index = url.indexOf("?");
70
+ return index === -1 ? [url, ""] : [url.slice(0, index), url.slice(index)];
71
+ };
72
+ const rendererUrl = (url, graph) => {
73
+ const [path, query] = splitQuery(url);
74
+ for (const [file, node] of graph) if (node.foldkitRenderer && path.endsWith(`/${file}`)) return {
75
+ prefix: path.slice(0, -file.length),
76
+ file,
77
+ query
78
+ };
79
+ };
80
+ const componentFile = (url, renderer, graph) => {
81
+ const [path] = splitQuery(url);
82
+ if (!path.startsWith(renderer.prefix)) return void 0;
83
+ const file = path.slice(renderer.prefix.length);
84
+ return graph.has(file) ? file : void 0;
85
+ };
86
+ /**
87
+ * Adds `modulepreload` links for each FoldKit island on the page that boots at
88
+ * load, at the end of the head so they follow the stylesheets: placed before
89
+ * them, they compete with render-blocking CSS and delay first paint.
90
+ *
91
+ * Returns the page unchanged when it has no such island.
92
+ */
93
+ const addIslandPreloads = (html, graph) => {
94
+ const hrefs = /* @__PURE__ */ new Set();
95
+ for (const [tag] of html.matchAll(islandTag)) {
96
+ const attributes = attributesOf(tag);
97
+ if (!eagerDirectives.has(attributes.get("client") ?? "")) continue;
98
+ const renderer = rendererUrl(attributes.get("renderer-url") ?? "", graph);
99
+ if (renderer === void 0) continue;
100
+ const component = componentFile(attributes.get("component-url") ?? "", renderer, graph);
101
+ if (component === void 0) continue;
102
+ for (const file of islandPreloads(graph, renderer.file, component)) hrefs.add(`${renderer.prefix}${file}${renderer.query}`);
103
+ }
104
+ const links = [...hrefs].filter((href) => !html.includes(`rel="modulepreload" href="${href}"`)).map((href) => `<link rel="modulepreload" href="${href}">`).join("");
105
+ const head = html.indexOf("</head>");
106
+ return links === "" || head === -1 ? html : html.slice(0, head) + links + html.slice(head);
107
+ };
108
+ const normalizeId = (id) => id.replaceAll("\\", "/");
109
+ const chunkGraphOf = (bundle, rendererEntry) => {
110
+ const entry = normalizeId(rendererEntry);
111
+ const graph = /* @__PURE__ */ new Map();
112
+ for (const output of Object.values(bundle)) {
113
+ if (output.type !== "chunk") continue;
114
+ graph.set(output.fileName, {
115
+ imports: output.imports,
116
+ dynamicImports: output.dynamicImports,
117
+ foldkitRenderer: output.facadeModuleId !== null && normalizeId(output.facadeModuleId) === entry
118
+ });
119
+ }
120
+ return graph;
121
+ };
122
+ /** Records the client bundle's chunk graph for {@link writeIslandPreloads}. */
123
+ const preloadPlugin = (rendererEntry, record) => ({
124
+ name: "astro-foldkit:preload",
125
+ apply: "build",
126
+ generateBundle(_options, bundle) {
127
+ if (this.environment?.config.consumer !== "client") return;
128
+ record(chunkGraphOf(bundle, rendererEntry));
129
+ }
130
+ });
131
+ const htmlFiles = async (directory) => (await readdir(directory, {
132
+ recursive: true,
133
+ encoding: "utf8"
134
+ })).filter((path) => path.endsWith(".html")).map((path) => join(directory, path));
135
+ /**
136
+ * Rewrites the pre-rendered pages under `directory` that boot a FoldKit island
137
+ * at load. Pages rendered on request are not on disk and keep the chain.
138
+ *
139
+ * @returns the number of pages rewritten.
140
+ */
141
+ const writeIslandPreloads = async (directory, graph) => {
142
+ let rewritten = 0;
143
+ for (const file of await htmlFiles(directory)) {
144
+ const html = await readFile(file, "utf8");
145
+ if (!html.includes("<astro-island")) continue;
146
+ const updated = addIslandPreloads(html, graph);
147
+ if (updated === html) continue;
148
+ await writeFile(file, updated);
149
+ rewritten += 1;
150
+ }
151
+ return rewritten;
152
+ };
153
+ //#endregion
27
154
  //#region src/index.ts
28
155
  function foldkit(options = {}) {
29
156
  const configuredBuildId = options.server?.buildId;
30
157
  if (configuredBuildId !== void 0 && configuredBuildId.trim() === "") throw new Error("foldkit({ server: { buildId } }) requires a non-empty server.buildId.");
158
+ const rendererEntry = fileURLToPath(new URL("./client.mjs", import.meta.url));
159
+ let clientGraph;
31
160
  return {
32
161
  name: "astro-foldkit",
33
- hooks: { "astro:config:setup": ({ config, addClientDirective, addRenderer, updateConfig }) => {
34
- addRenderer({
35
- name: "astro-foldkit",
36
- clientEntrypoint: fileURLToPath(new URL("./client.mjs", import.meta.url)),
37
- serverEntrypoint: fileURLToPath(new URL("./server.mjs", import.meta.url))
38
- });
39
- addClientDirective({
40
- name: "interaction",
41
- entrypoint: fileURLToPath(new URL("./directive-interaction.mjs", import.meta.url))
42
- });
43
- updateConfig({ vite: { plugins: [foldkit$1(options.server), islandScanPlugin(fileURLToPath(config.root), fileURLToPath(config.srcDir))] } });
44
- } }
162
+ hooks: {
163
+ "astro:config:setup": ({ config, addClientDirective, addRenderer, updateConfig }) => {
164
+ addRenderer({
165
+ name: "astro-foldkit",
166
+ clientEntrypoint: rendererEntry,
167
+ serverEntrypoint: fileURLToPath(new URL("./server.mjs", import.meta.url))
168
+ });
169
+ addClientDirective({
170
+ name: "interaction",
171
+ entrypoint: fileURLToPath(new URL("./directive-interaction.mjs", import.meta.url))
172
+ });
173
+ updateConfig({ vite: { plugins: [
174
+ foldkit$1(options.server),
175
+ islandScanPlugin(fileURLToPath(config.root), fileURLToPath(config.srcDir)),
176
+ preloadPlugin(rendererEntry, (graph) => {
177
+ clientGraph = graph;
178
+ })
179
+ ] } });
180
+ },
181
+ "astro:build:done": async ({ dir, logger }) => {
182
+ if (clientGraph === void 0) return;
183
+ const rewritten = await writeIslandPreloads(fileURLToPath(dir), clientGraph);
184
+ if (rewritten > 0) logger.info(`Added module preloads for FoldKit islands to ${rewritten} page${rewritten === 1 ? "" : "s"}.`);
185
+ }
186
+ }
45
187
  };
46
188
  }
47
189
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opsydyn/astro-foldkit",
3
- "version": "0.12.0",
3
+ "version": "0.13.1",
4
4
  "description": "Astro integration and renderer for FoldKit.",
5
5
  "keywords": [
6
6
  "astro",
@@ -69,7 +69,10 @@
69
69
  "test:unit": "bun test test/unit",
70
70
  "test:integration": "bun test test/integration",
71
71
  "check": "NODE_OPTIONS=\"--experimental-strip-types\" oxlint . && oxfmt --check .",
72
- "check:fix": "oxfmt . && NODE_OPTIONS=\"--experimental-strip-types\" oxlint --fix ."
72
+ "check:fix": "oxfmt . && NODE_OPTIONS=\"--experimental-strip-types\" oxlint --fix .",
73
+ "api:report": "bun ../../tools/api-surface.ts",
74
+ "api:check": "bun ../../tools/api-surface.ts --check",
75
+ "compat:astro": "bun ../../tools/astro-compat.ts"
73
76
  },
74
77
  "dependencies": {
75
78
  "@foldkit/vite-plugin": "^0.29.0"
@@ -80,14 +83,14 @@
80
83
  "bun-types": "^1.3.14",
81
84
  "effect": "4.1.0",
82
85
  "fast-check": "^4.8.0",
83
- "foldkit": "0.170.0",
86
+ "foldkit": "0.171.0",
84
87
  "tsdown": "^0.21.8",
85
88
  "typescript": "^6.0.3"
86
89
  },
87
90
  "peerDependencies": {
88
91
  "astro": ">=5.0.0",
89
92
  "effect": "~4.1.0",
90
- "foldkit": ">=0.170.0 <0.171.0"
93
+ "foldkit": ">=0.170.0 <0.172.0"
91
94
  },
92
95
  "engines": {
93
96
  "node": ">=22.0.0"