@opsydyn/astro-foldkit 0.5.0 → 0.6.0

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,11 +1,30 @@
1
1
  # Changelog
2
2
 
3
- ## [0.5.0](https://github.com/opsydyn/fold-kit-experiments/compare/astro-foldkit-v0.4.0...astro-foldkit-v0.5.0) (2026-07-18)
3
+ ## [0.6.0](https://github.com/opsydyn/fold-kit-experiments/compare/astro-foldkit-v0.5.0...astro-foldkit-v0.6.0) (2026-08-20)
4
+
5
+
6
+ ### Features
7
+
8
+ * **astro-foldkit:** add server render handoff ([9773a4d](https://github.com/opsydyn/fold-kit-experiments/commit/9773a4d1883c53fa60957368a0125d3b57b7cd24))
9
+ * **astro-foldkit:** document opt-in server rendering ([53e9d00](https://github.com/opsydyn/fold-kit-experiments/commit/53e9d004c75c10245d0aa88fc4c412b96c7f2f4c))
10
+ * **astro-foldkit:** expose server document resolver ([969dc2f](https://github.com/opsydyn/fold-kit-experiments/commit/969dc2f7e4a679df8b04d60c57783d6b8fb84bd1))
11
+ * **astro-foldkit:** formalize define-page contract ([62863c5](https://github.com/opsydyn/fold-kit-experiments/commit/62863c58fa1462d2ecb04bd52cf3d5e0bb444601))
12
+ * **astro-foldkit:** hydrate page owners on client ([9f8f76b](https://github.com/opsydyn/fold-kit-experiments/commit/9f8f76bef77ea734006c1faa90defdfdd115d09d))
13
+ * support FoldKit 0.136 ([50f4134](https://github.com/opsydyn/fold-kit-experiments/commit/50f4134d7596926fed373408642816736907934f))
4
14
 
5
15
 
16
+ ### Bug Fixes
17
+
18
+ * **astro-foldkit:** align server document tests ([f71c2c2](https://github.com/opsydyn/fold-kit-experiments/commit/f71c2c2ccea94f148e81126b00174375566fa5bb))
19
+ * **astro-foldkit:** keep define-page markers inert ([0fb4e54](https://github.com/opsydyn/fold-kit-experiments/commit/0fb4e54dbd3a0b53f21de57f27f3948e13fcf80b))
20
+ * **astro-foldkit:** pass stamped root to page hydration ([b3b3ba6](https://github.com/opsydyn/fold-kit-experiments/commit/b3b3ba65c4bb25bb9c2738f82d1148e5e6407679))
21
+ * **astro-foldkit:** reject empty server build id ([320bc39](https://github.com/opsydyn/fold-kit-experiments/commit/320bc39a9ca8d610fe60480c0c399a71fc029b51))
22
+
23
+ ## [0.5.0](https://github.com/opsydyn/fold-kit-experiments/compare/astro-foldkit-v0.4.0...astro-foldkit-v0.5.0) (2026-07-18)
24
+
6
25
  ### Features
7
26
 
8
- * **astro-foldkit:** add lazy app entry API ([9786bdd](https://github.com/opsydyn/fold-kit-experiments/commit/9786bdd226cfd2200b6e64d5b198a53a7aad6d13))
27
+ - **astro-foldkit:** add lazy app entry API ([9786bdd](https://github.com/opsydyn/fold-kit-experiments/commit/9786bdd226cfd2200b6e64d5b198a53a7aad6d13))
9
28
 
10
29
  ## [0.4.0](https://github.com/opsydyn/fold-kit-experiments/compare/astro-foldkit-v0.3.0...astro-foldkit-v0.4.0) (2026-07-18)
11
30
 
package/README.md CHANGED
@@ -1,9 +1,15 @@
1
1
  # @opsydyn/astro-foldkit
2
2
 
3
- Astro integration and renderer for [FoldKit](https://foldkit.dev).
3
+ Astro integration and renderer for [FoldKit](https://foldkit.dev), with
4
+ client-only islands and an opt-in server-rendered page path.
4
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
7
 
8
+ There are two deliberately separate entry paths:
9
+
10
+ - `lazyApp` / `defineApp` keeps the existing client-only island contract. Astro receives a deterministic mount shell and FoldKit starts in the browser.
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
+
7
13
  ## Installation
8
14
 
9
15
  ```sh
@@ -14,10 +20,11 @@ npm install astro foldkit
14
20
 
15
21
  ## FoldKit compatibility
16
22
 
17
- `@opsydyn/astro-foldkit` requires FoldKit `0.129.0` or later. Applications can
18
- use `Command.Interruptible` for request cancellation inside their own update
19
- loop; this integration continues to own only Astro hydration and lifecycle
20
- event delivery.
23
+ `@opsydyn/astro-foldkit` is tested with FoldKit `0.148.x` and the matching
24
+ `@foldkit/vite-plugin` `0.16.x` line. Applications can define interruptible
25
+ work with `Command.define(name, { interrupt: true, ... })` inside their own
26
+ update loop; this integration continues to own Astro rendering, hydration,
27
+ and lifecycle event delivery.
21
28
 
22
29
  ## Setup
23
30
 
@@ -28,10 +35,22 @@ import { defineConfig } from 'astro/config';
28
35
  import foldkit from '@opsydyn/astro-foldkit';
29
36
 
30
37
  export default defineConfig({
31
- integrations: [foldkit()],
38
+ integrations: [
39
+ foldkit({
40
+ server: {
41
+ buildId: process.env.FOLDKIT_BUILD_ID ?? 'development',
42
+ },
43
+ }),
44
+ ],
32
45
  });
33
46
  ```
34
47
 
48
+ The build ID is an explicit server/client handoff identity. Use a stable
49
+ deployment-specific value in production and the same value in every process
50
+ that serves the build. The integration defaults to `development` for local
51
+ use, rejects a blank value, and fails a `definePage` render closed rather than
52
+ hydrating a mismatched document when no usable identity is available.
53
+
35
54
  ## Defining an app
36
55
 
37
56
  Use `lazyApp` to register a FoldKit app for lazy loading. The literal loader keeps each Astro island as an explicit code-splitting boundary; it returns your `main.ts` module, which must export a value that satisfies `AppConfig`. `defineApp` remains available as a backwards-compatible alias.
@@ -45,12 +64,17 @@ export default lazyApp(() => import('./main'));
45
64
 
46
65
  ```ts
47
66
  // src/apps/counter/main.ts
67
+ import type { Document, HtmlBuilder } from 'foldkit/html';
68
+
69
+ type Message = 'Inc' | 'Dec';
70
+
48
71
  export const Model = null;
49
72
  export const init = () => [0, []] as const;
50
- export const update = (model: number, message: 'Inc' | 'Dec') =>
73
+ export const update = (model: number, message: Message) =>
51
74
  [message === 'Inc' ? model + 1 : model - 1, []] as const;
52
- export const view = (model: number) => ({
53
- /* foldkit view tree */
75
+ export const view = (model: number, h: HtmlBuilder<Message>): Document => ({
76
+ title: `Counter: ${model}`,
77
+ body: h.button([h.OnClick('Inc')], [String(model)]),
54
78
  });
55
79
  ```
56
80
 
@@ -63,10 +87,153 @@ import Counter from '../apps/counter/app'
63
87
  <Counter client:load />
64
88
  ```
65
89
 
66
- The server renderer emits a deterministic `<div data-foldkit-island="true">` mount shell. It does not load or execute the FoldKit application during SSR; the application is loaded and embedded only by the client renderer. Astro still owns the outer island serialisation and client directive behavior.
90
+ For `lazyApp` / `defineApp`, the server renderer emits a deterministic
91
+ `<div data-foldkit-island="true"></div>` mount shell. It does not load or
92
+ execute the FoldKit application during SSR; the application is loaded and
93
+ embedded only by the client renderer. Astro still owns the outer island
94
+ serialisation and client directive behavior.
67
95
 
68
96
  The demo app's [`/request-diagnostics`](../../apps/web/src/pages/request-diagnostics.astro) page shows the integration boundary with a practical machine-driven chart workflow. The page uses `@opsydyn/astro-foldkit` for hydration, `@opsydyn/foldkit-viz` for chart primitives, and `foldkit/experimental/machine` in the application update layer.
69
97
 
98
+ ## Server-rendered pages (opt-in)
99
+
100
+ Use `definePage` when one FoldKit application owns the document content for an
101
+ Astro route. It is intentionally separate from `lazyApp`: existing apps and
102
+ charts remain client-only islands unless they are explicitly migrated.
103
+
104
+ The page loader has the same literal lazy-module shape as `lazyApp`, but its
105
+ Flags factory is synchronous and receives request facts from Astro:
106
+
107
+ ```ts
108
+ // src/apps/greeting/page.ts
109
+ import { definePage } from '@opsydyn/astro-foldkit/define-page';
110
+ import { Match, Schema } from 'effect';
111
+
112
+ import { Flags, type Locale, type Name } from './model';
113
+
114
+ type Props = { readonly name: Name };
115
+
116
+ const localeFromUrl = (url: URL): Locale =>
117
+ Match.value(url.searchParams.get('locale')).pipe(
118
+ Match.when('ar', () => 'ar' as const),
119
+ Match.when('en', () => 'en' as const),
120
+ Match.orElse(() => 'en' as const),
121
+ );
122
+
123
+ export default definePage<Props, Flags>(() => import('./main'), {
124
+ flags: ({ props, url }) =>
125
+ Schema.decodeSync(Flags)({
126
+ name: props.name,
127
+ locale: localeFromUrl(url),
128
+ }),
129
+ });
130
+ ```
131
+
132
+ The loaded `main` module exports the page configuration, including the runtime
133
+ `Flags` Schema/value used by FoldKit to validate the serialized handoff:
134
+
135
+ ```ts
136
+ // src/apps/greeting/main.ts
137
+ import { Message } from './message';
138
+ import { Flags, init, Model } from './model';
139
+ import { update } from './update';
140
+ import { view } from './view';
141
+
142
+ export { Flags, init, Message, Model, update, view };
143
+ ```
144
+
145
+ `Flags` must be public JSON-serializable data required to create the first
146
+ Model. The factory may derive it from `request`, `url`, `params`, and validated
147
+ component `props`, but it must not return secrets, credentials, request bodies,
148
+ or runtime objects. It must not run Commands, Subscriptions, remote loads, or
149
+ browser-only resources. Server rendering is a deterministic render handoff,
150
+ not a server data-loading abstraction.
151
+
152
+ ### Request SSR
153
+
154
+ Resolve the same page document in the Astro frontmatter so its FoldKit metadata
155
+ can reach the outer layout. Keep the resolver import server-only:
156
+
157
+ ```astro
158
+ ---
159
+ export const prerender = false;
160
+
161
+ import { Schema } from 'effect';
162
+ import { resolvePageDocument } from '@opsydyn/astro-foldkit/server';
163
+
164
+ import GreetingPage from '../apps/greeting/page';
165
+ import { Name } from '../apps/greeting/model';
166
+ import Layout from '../layouts/Layout.astro';
167
+
168
+ const name = Schema.decodeSync(Name)(Astro.url.searchParams.get('name') ?? 'astronaut');
169
+ const document = await resolvePageDocument(GreetingPage, {
170
+ request: Astro.request,
171
+ url: Astro.url,
172
+ params: Astro.params,
173
+ props: { name },
174
+ });
175
+ ---
176
+
177
+ <Layout
178
+ title={document.title}
179
+ lang={document.lang}
180
+ dir={document.dir}
181
+ canonical={document.canonical}
182
+ ogUrl={document.ogUrl}
183
+ >
184
+ <GreetingPage client:load name={name} />
185
+ </Layout>
186
+ ```
187
+
188
+ The layout owns the outer `<html>` structure and applies `title`, `lang`,
189
+ `dir`, `canonical`, and `ogUrl` from the resolved FoldKit `Document`. The
190
+ `client:load` directive is still required for an interactive page: the server
191
+ HTML contains one stamped FoldKit root and the browser hydrates that exact root
192
+ with the serialized Flags payload.
193
+
194
+ ### SSG
195
+
196
+ The same page owner can be prerendered when its props and Flags are universal:
197
+
198
+ ```astro
199
+ ---
200
+ export const prerender = true;
201
+
202
+ import { Schema } from 'effect';
203
+ import { resolvePageDocument } from '@opsydyn/astro-foldkit/server';
204
+
205
+ import GreetingPage from '../apps/greeting/page';
206
+ import { Name } from '../apps/greeting/model';
207
+ import Layout from '../layouts/Layout.astro';
208
+
209
+ const name = Schema.decodeSync(Name)('static astronaut');
210
+ const document = await resolvePageDocument(GreetingPage, {
211
+ request: Astro.request,
212
+ url: Astro.url,
213
+ params: Astro.params,
214
+ props: { name },
215
+ });
216
+ ---
217
+
218
+ <Layout
219
+ title={document.title}
220
+ lang={document.lang}
221
+ dir={document.dir}
222
+ canonical={document.canonical}
223
+ ogUrl={document.ogUrl}
224
+ >
225
+ <GreetingPage client:load name={name} />
226
+ </Layout>
227
+ ```
228
+
229
+ An SSG error fails the build. A request-SSR error reaches Astro's error
230
+ response. The integration does not replace failed page rendering with the
231
+ client-only shell. A document may have only one `definePage` owner; use
232
+ `lazyApp` / `defineApp` for additional charts or embedded applications.
233
+
234
+ `noMeta` remains an island-only option for `defineApp`. It does not change the
235
+ page-owner metadata contract.
236
+
70
237
  ## Passing props
71
238
 
72
239
  `lazyApp` accepts a type parameter for the props your FoldKit app expects. This makes the component callable with typed attributes in `.astro` files.
@@ -123,10 +290,17 @@ Prevents the FoldKit program from overwriting `document.title`. Use this wheneve
123
290
  <DashboardChart client:load noMeta data={chartData} />
124
291
  ```
125
292
 
126
- Both `noMeta` and `noMeta={true}` are accepted. The prop is stripped before `init` receives the rest of your props.
293
+ Both `noMeta` and `noMeta={true}` are accepted. The wrapper pins only the
294
+ Document `title`; FoldKit still applies `lang` and `dir` from the app's current
295
+ Document.
127
296
 
128
297
  ## Architecture
129
298
 
299
+ `definePage` owns one server-rendered FoldKit application for a document;
300
+ `lazyApp` / `defineApp` owns an independent client island. The integration does
301
+ not infer page ownership from ordinary app markers, and adding `definePage`
302
+ does not migrate existing chart routes.
303
+
130
304
  ### Imperative shell, functional core
131
305
 
132
306
  The Astro page is the **imperative shell**: it performs side effects (HTTP fetches, query-param reads, URL parsing) and validates raw values into branded types via `Schema.decodeSync`. The shell hands only clean, typed values into the component.
@@ -166,19 +340,25 @@ The double-decode is intentional: `Schema.decodeSync` at the Astro boundary ensu
166
340
 
167
341
  The module returned by your loader must export:
168
342
 
169
- | Export | Type | Description |
170
- | :------- | :------------------------------------------------------------- | :---------------------------------------------- |
171
- | `Model` | `unknown` | Initial model type marker |
172
- | `init` | `(props: unknown) => readonly [Model, ReadonlyArray<Command>]` | Initial state from props and startup commands |
173
- | `update` | `(model, message) => readonly [Model, ReadonlyArray<Command>]` | Pure state transition |
174
- | `view` | `(model) => Document` | Render the current model to a FoldKit view tree |
343
+ | Export | Type | Description |
344
+ | :------- | :------------------------------------------------------------- | :-------------------------------------------- |
345
+ | `Model` | `unknown` | Initial model type marker |
346
+ | `init` | `(props: unknown) => readonly [Model, ReadonlyArray<Command>]` | Initial state from props and startup commands |
347
+ | `update` | `(model, message) => readonly [Model, ReadonlyArray<Command>]` | Pure state transition |
348
+ | `view` | `(model, h: HtmlBuilder<Message>) => Document` | Render with the current render-frame builder |
349
+
350
+ For `definePage`, `init` receives the validated `Flags` value rather than raw
351
+ Astro props, and the module must additionally export the runtime `Flags`
352
+ Schema/value. `defineApp` keeps the existing props-based `init` contract.
175
353
 
176
354
  ## Exports
177
355
 
178
- | Entry point | Description |
179
- | :---------------------------------- | :-------------------------------------------------------- |
180
- | `@opsydyn/astro-foldkit` | Default Astro integration (`foldkit()`) |
181
- | `@opsydyn/astro-foldkit/define-app` | `lazyApp` helper (`defineApp` alias) and `AppConfig` type |
356
+ | Entry point | Description |
357
+ | :----------------------------------- | :-------------------------------------------------------- |
358
+ | `@opsydyn/astro-foldkit` | Default Astro integration (`foldkit()`) |
359
+ | `@opsydyn/astro-foldkit/define-app` | `lazyApp` helper (`defineApp` alias) and `AppConfig` type |
360
+ | `@opsydyn/astro-foldkit/define-page` | `definePage`, `PageConfig`, and page Flags context types |
361
+ | `@opsydyn/astro-foldkit/server` | Server-only `resolvePageDocument` metadata resolver |
182
362
 
183
363
  The root entry point also exports the `NavigationConfig`, `NavigationEvent`, and `NavigationPhase` types.
184
364
 
@@ -242,7 +422,7 @@ type NavigationEvent = {
242
422
 
243
423
  The bridge sends `coldLoad` immediately for the first mount of an island identity. A retained island receives `stayed` on `astro:before-swap` when its matching `uid` exists in the incoming document, but does not receive `entered` from the following global `astro:page-load`. A same-identity remount emits `entered` on mount; an active island can also emit `entered` for a later page load when it was not retained. Every mounted island emits `exited` once on `astro:unmount`. Events contain normalized pathnames; route parsing and route-specific message decisions belong in the app mapper. If the configured inbound port is missing, the integration warns once and leaves the FoldKit runtime mounted without forwarding events.
244
424
 
245
- The integration owns only lifecycle observation and port delivery. The app owns parsing `path` into its route type, mapping the event into a past-tense Message, and deciding whether an `entered` event should run a load or revalidation command. Keep that policy in `update` or a FoldKit `Transition`, so SSR props, navigation facts, and side effects remain separate.
425
+ The integration owns only lifecycle observation and port delivery. The app owns parsing `path` into its route type, mapping the event into a past-tense Message, and deciding whether an `entered` event should run a load or revalidation command. Keep that policy in `update` or a FoldKit `Transition`, so SSR props, navigation facts, and side effects remain separate. When an app uses exited to interrupt work, the interrupt key, state, and outcome policy stay in its update loop; the integration does not cancel or replace commands.
246
426
 
247
427
  Pass the ports map to `makeApplication` alongside your `init`, `update`, and `view`:
248
428
 
@@ -293,10 +473,10 @@ element.addEventListener(
293
473
 
294
474
  ## Peer dependencies
295
475
 
296
- | Package | Version |
297
- | :-------- | :-------- |
298
- | `astro` | `≥ 5.0` |
299
- | `foldkit` | `≥ 0.126` |
476
+ | Package | Version |
477
+ | :-------- | :-------------------- |
478
+ | `astro` | `≥ 5.0` |
479
+ | `foldkit` | `≥ 0.148.0 < 0.149.0` |
300
480
 
301
481
  ## License
302
482
 
@@ -0,0 +1,7 @@
1
+ //#region src/build-id.d.ts
2
+ type FoldkitEnv = Readonly<{
3
+ FOLDKIT_BUILD_ID?: string;
4
+ }>;
5
+ declare function readFoldkitBuildId(env?: FoldkitEnv | undefined): string;
6
+ //#endregion
7
+ export { readFoldkitBuildId };
@@ -0,0 +1,8 @@
1
+ //#region src/build-id.ts
2
+ function readFoldkitBuildId(env = import.meta.env) {
3
+ const buildId = env?.FOLDKIT_BUILD_ID;
4
+ if (buildId === void 0 || buildId === "") throw new Error("FoldKit server rendering requires import.meta.env.FOLDKIT_BUILD_ID. Configure foldkit({ server: { buildId } }).");
5
+ return buildId;
6
+ }
7
+ //#endregion
8
+ export { readFoldkitBuildId };
package/dist/client.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as AppConfigShape, r as FoldkitApp } from "./types-BOU7iNnu.mjs";
1
+ import { a as FoldkitPage, i as FoldkitApp, n as AppConfigShape, s as PageConfigShape } from "./types-4PDoP5Mh.mjs";
2
2
 
3
3
  //#region src/client.d.ts
4
4
  type EventTargetLike = {
@@ -26,11 +26,16 @@ type ClientEnvironment = {
26
26
  type ClientRuntime = {
27
27
  readonly makeApplication: (config: unknown) => unknown;
28
28
  readonly embed: (program: unknown) => EmbedHandle;
29
+ readonly hydrate?: (program: unknown, options: {
30
+ readonly buildId: string;
31
+ }) => unknown;
29
32
  };
30
- declare function createClientRenderer(runtime?: ClientRuntime, environment?: Partial<ClientEnvironment>): (element: HTMLElement) => <Props extends Record<string, unknown>, Config extends AppConfigShape<Props>>(component: FoldkitApp<Props, Config>, props: Props, _slots: Record<string, unknown>, _meta: {
33
+ type ClientPage = FoldkitPage<Record<string, unknown>, Record<string, unknown>, PageConfigShape<Record<string, unknown>>>;
34
+ type ClientComponent<Props extends Record<string, unknown>, Config extends AppConfigShape<Props>> = FoldkitApp<Props, Config> | ClientPage;
35
+ declare function createClientRenderer(runtime?: ClientRuntime, environment?: Partial<ClientEnvironment>): (element: HTMLElement) => <Props extends Record<string, unknown>, Config extends AppConfigShape<Props>>(component: ClientComponent<Props, Config>, props: Props, _slots: Record<string, unknown>, _meta: {
31
36
  client: string;
32
37
  }) => Promise<void>;
33
- declare const _default: (element: HTMLElement) => <Props extends Record<string, unknown>, Config extends AppConfigShape<Props>>(component: FoldkitApp<Props, Config>, props: Props, _slots: Record<string, unknown>, _meta: {
38
+ declare const _default: (element: HTMLElement) => <Props extends Record<string, unknown>, Config extends AppConfigShape<Props>>(component: ClientComponent<Props, Config>, props: Props, _slots: Record<string, unknown>, _meta: {
34
39
  client: string;
35
40
  }) => Promise<void>;
36
41
  //#endregion
package/dist/client.mjs CHANGED
@@ -1,5 +1,12 @@
1
+ import { readFoldkitBuildId } from "./build-id.mjs";
1
2
  import { Runtime } from "foldkit";
2
3
  //#region src/client-helpers.ts
4
+ const FOLDKIT_ROOT_SELECTOR = "[data-foldkit-app]";
5
+ const findSingleFoldkitRoot = (container) => {
6
+ const roots = Array.from(container.querySelectorAll(FOLDKIT_ROOT_SELECTOR));
7
+ if (roots.length !== 1) throw new Error(`Expected exactly one stamped FoldKit root inside the Astro island, found ${roots.length}.`);
8
+ return roots[0];
9
+ };
3
10
  /** Returns true when the `noMeta` prop should suppress document metadata writes. */
4
11
  const shouldSkipMetadata = (props) => props.noMeta === true || props.noMeta === "";
5
12
  /**
@@ -8,8 +15,8 @@ const shouldSkipMetadata = (props) => props.noMeta === true || props.noMeta ===
8
15
  * `document.title` when the app is embedded as an island on a page that
9
16
  * owns its own title.
10
17
  */
11
- const makeNoMetaView = (view, initialTitle) => (model) => ({
12
- ...view(model),
18
+ const makeNoMetaView = (view, initialTitle) => (model, h) => ({
19
+ ...view(model, h),
13
20
  title: initialTitle
14
21
  });
15
22
  //#endregion
@@ -99,20 +106,33 @@ const attachNavigationBridge = (element, navigation, send, environment) => {
99
106
  };
100
107
  const defaultRuntime = {
101
108
  makeApplication: (config) => Runtime.makeApplication(config),
102
- embed: (program) => Runtime.embed(program)
109
+ embed: (program) => Runtime.embed(program),
110
+ hydrate: (program, options) => Runtime.hydrate(program, options)
103
111
  };
112
+ const isPageOwner = (component) => typeof component === "function" && "__foldkitPage" in component && component.__foldkitPage === true;
104
113
  function createClientRenderer(runtime = defaultRuntime, environment = {}) {
105
114
  return (element) => async (component, props, _slots, _meta) => {
106
115
  const config = await component.load();
116
+ const runtimeConfig = config;
107
117
  const clientEnvironment = {
108
118
  document: environment.document ?? globalThis.document,
109
119
  window: environment.window ?? globalThis.window
110
120
  };
111
121
  element.id ||= element.getAttribute("uid") ?? crypto.randomUUID();
112
- const baseView = config.view;
122
+ if (isPageOwner(component)) {
123
+ const root = findSingleFoldkitRoot(element);
124
+ const application = runtime.makeApplication({
125
+ ...config,
126
+ container: root
127
+ });
128
+ if (runtime.hydrate === void 0) throw new Error("FoldKit Runtime.hydrate is not available for page hydration.");
129
+ runtime.hydrate(application, { buildId: readFoldkitBuildId() });
130
+ return;
131
+ }
132
+ const baseView = runtimeConfig.view;
113
133
  const view = shouldSkipMetadata(props) ? makeNoMetaView(baseView, clientEnvironment.document.title) : baseView;
114
134
  const program = runtime.makeApplication({
115
- ...config,
135
+ ...runtimeConfig,
116
136
  init: () => config.init(props),
117
137
  view,
118
138
  container: element,
@@ -1,4 +1,4 @@
1
- import { n as AppConfigShape, r as FoldkitApp, t as AppConfig } from "./types-BOU7iNnu.mjs";
1
+ import { i as FoldkitApp, n as AppConfigShape, t as AppConfig } from "./types-4PDoP5Mh.mjs";
2
2
 
3
3
  //#region src/define-app.d.ts
4
4
  declare function defineApp<Props extends Record<string, unknown> = Record<string, unknown>, Config extends AppConfigShape<Props> = AppConfigShape<Props>>(load: () => Promise<Config>): FoldkitApp<Props, Config>;
@@ -0,0 +1,6 @@
1
+ import { a as FoldkitPage, c as PageContext, d as PageParams, l as PageFlagsContext, o as PageConfig, r as DefinePageOptions, s as PageConfigShape, u as PageFlagsSchema } from "./types-4PDoP5Mh.mjs";
2
+
3
+ //#region src/define-page.d.ts
4
+ declare function definePage<Props extends Record<string, unknown> = Record<string, unknown>, Flags extends Record<string, unknown> = Record<string, unknown>, Config extends PageConfigShape<Flags> = PageConfigShape<Flags>>(load: () => Promise<Config>, options: DefinePageOptions<Props, Flags>): FoldkitPage<Props, Flags, Config>;
5
+ //#endregion
6
+ export { type DefinePageOptions, type FoldkitPage, type PageConfig, type PageConfigShape, type PageContext, type PageFlagsContext, type PageFlagsSchema, type PageParams, definePage };
@@ -0,0 +1,10 @@
1
+ //#region src/define-page.ts
2
+ function definePage(load, options) {
3
+ return Object.assign((_props) => {}, {
4
+ __foldkitPage: true,
5
+ load,
6
+ flags: options.flags
7
+ });
8
+ }
9
+ //#endregion
10
+ export { definePage };
package/dist/index.d.mts CHANGED
@@ -2,6 +2,11 @@ import { n as NavigationEvent, r as NavigationPhase, t as NavigationConfig } fro
2
2
  import { AstroIntegration } from "astro";
3
3
 
4
4
  //#region src/index.d.ts
5
- declare function foldkit(): AstroIntegration;
5
+ type FoldkitIntegrationOptions = Readonly<{
6
+ server?: Readonly<{
7
+ buildId: string;
8
+ }>;
9
+ }>;
10
+ declare function foldkit(options?: FoldkitIntegrationOptions): AstroIntegration;
6
11
  //#endregion
7
- export { type NavigationConfig, type NavigationEvent, type NavigationPhase, foldkit as default };
12
+ export { FoldkitIntegrationOptions, type NavigationConfig, type NavigationEvent, type NavigationPhase, foldkit as default };
package/dist/index.mjs CHANGED
@@ -1,7 +1,10 @@
1
1
  import { fileURLToPath } from "node:url";
2
2
  import { foldkit as foldkit$1 } from "@foldkit/vite-plugin";
3
3
  //#region src/index.ts
4
- function foldkit() {
4
+ function foldkit(options = {}) {
5
+ const configuredBuildId = options.server?.buildId;
6
+ if (configuredBuildId !== void 0 && configuredBuildId.trim() === "") throw new Error("foldkit({ server: { buildId } }) requires a non-empty server.buildId.");
7
+ const buildId = configuredBuildId ?? "development";
5
8
  return {
6
9
  name: "astro-foldkit",
7
10
  hooks: { "astro:config:setup": ({ addRenderer, updateConfig }) => {
@@ -10,7 +13,7 @@ function foldkit() {
10
13
  clientEntrypoint: fileURLToPath(new URL("./client.mjs", import.meta.url)),
11
14
  serverEntrypoint: fileURLToPath(new URL("./server.mjs", import.meta.url))
12
15
  });
13
- updateConfig({ vite: { plugins: [foldkit$1()] } });
16
+ updateConfig({ vite: { plugins: [foldkit$1({ buildId })] } });
14
17
  } }
15
18
  };
16
19
  }
@@ -0,0 +1,14 @@
1
+ import { a as FoldkitPage, c as PageContext } from "./types-4PDoP5Mh.mjs";
2
+ import { RenderedApplication } from "foldkit/experimental/server";
3
+
4
+ //#region src/server-document.d.ts
5
+ type ResolvedPageDocument = {
6
+ readonly title: string;
7
+ readonly lang?: string;
8
+ readonly dir?: 'ltr' | 'rtl' | 'auto';
9
+ readonly canonical?: string;
10
+ readonly ogUrl?: string;
11
+ };
12
+ declare function resolvePageDocument<Props extends Record<string, unknown> = Record<string, unknown>, Flags extends Record<string, unknown> = Record<string, unknown>>(page: FoldkitPage<Props, Flags>, context: PageContext<Props>): Promise<ResolvedPageDocument>;
13
+ //#endregion
14
+ export { type ResolvedPageDocument, resolvePageDocument };
@@ -0,0 +1,16 @@
1
+ import { readFoldkitBuildId } from "./build-id.mjs";
2
+ import { renderFoldkitServerApplication } from "./server-render.mjs";
3
+ //#region src/server-document.ts
4
+ const setOptional = (document, key, value) => value === void 0 ? document : {
5
+ ...document,
6
+ [key]: value
7
+ };
8
+ const mapRenderedApplicationDocument = (rendered) => {
9
+ return setOptional(setOptional(setOptional(setOptional({ title: rendered.title }, "lang", rendered.lang), "dir", rendered.dir), "canonical", rendered.canonical), "ogUrl", rendered.ogUrl);
10
+ };
11
+ async function resolvePageDocument(page, context) {
12
+ const flags = page.flags(context);
13
+ return mapRenderedApplicationDocument(await renderFoldkitServerApplication(await page.load(), flags, readFoldkitBuildId()));
14
+ }
15
+ //#endregion
16
+ export { resolvePageDocument };
@@ -0,0 +1,8 @@
1
+ import { s as PageConfigShape } from "./types-4PDoP5Mh.mjs";
2
+ import { RenderedApplication } from "foldkit/experimental/server";
3
+
4
+ //#region src/server-render.d.ts
5
+ type ServerConfig<Flags extends Record<string, unknown>> = Pick<PageConfigShape<Flags>, 'Flags' | 'init' | 'view'>;
6
+ declare function renderFoldkitServerApplication<Flags extends Record<string, unknown>>(config: ServerConfig<Flags>, flags: Flags, buildId: string): Promise<RenderedApplication>;
7
+ //#endregion
8
+ export { renderFoldkitServerApplication };
@@ -0,0 +1,15 @@
1
+ import { Effect } from "effect";
2
+ import { renderToString } from "foldkit/experimental/server";
3
+ //#region src/server-render.ts
4
+ async function renderFoldkitServerApplication(config, flags, buildId) {
5
+ return await Effect.runPromise(renderToString({
6
+ Flags: config.Flags,
7
+ init: config.init,
8
+ view: config.view
9
+ }, {
10
+ flags,
11
+ buildId
12
+ }));
13
+ }
14
+ //#endregion
15
+ export { renderFoldkitServerApplication };
package/dist/server.d.mts CHANGED
@@ -1,8 +1,17 @@
1
+ import { d as PageParams } from "./types-4PDoP5Mh.mjs";
1
2
  import { NamedSSRLoadedRendererValue } from "astro";
2
3
 
3
4
  //#region src/server.d.ts
5
+ type AstroRendererResult = Readonly<{
6
+ createAstro: (props: Record<string, unknown>, slots: Record<string, string>) => unknown;
7
+ params: PageParams;
8
+ request: Request;
9
+ }>;
10
+ type RendererThis = Readonly<{
11
+ result?: AstroRendererResult;
12
+ }>;
4
13
  declare function check(Component: unknown): Promise<boolean>;
5
- declare function renderToStaticMarkup(_component: unknown, _props: Record<string, unknown>, _slots: Record<string, string>): Promise<{
14
+ declare function renderToStaticMarkup(this: RendererThis | void, component: unknown, props: Record<string, unknown>, slots: Record<string, string>): Promise<{
6
15
  html: string;
7
16
  }>;
8
17
  declare const renderer: NamedSSRLoadedRendererValue;
package/dist/server.mjs CHANGED
@@ -1,8 +1,40 @@
1
+ import { readFoldkitBuildId } from "./build-id.mjs";
2
+ import { renderFoldkitServerApplication } from "./server-render.mjs";
1
3
  //#region src/server.ts
4
+ const claimedPageResults = /* @__PURE__ */ new WeakSet();
5
+ const isObjectOrFunction = (value) => value != null && (typeof value === "object" || typeof value === "function");
6
+ const isFoldkitApp = (value) => isObjectOrFunction(value) && "__foldkit" in value && value.__foldkit === true;
7
+ const isFoldkitPage = (value) => isObjectOrFunction(value) && "__foldkitPage" in value && value.__foldkitPage === true;
8
+ const claimPageResult = (result) => {
9
+ if (claimedPageResults.has(result)) throw new Error("Astro FoldKit server rendering supports exactly one FoldKit page owner per result.");
10
+ claimedPageResults.add(result);
11
+ };
12
+ const requireResult = (result) => {
13
+ if (result === void 0) throw new Error("Astro FoldKit server rendering requires the Astro renderer result.");
14
+ return result;
15
+ };
16
+ const pageContext = (result, props, slots) => {
17
+ const astro = result.createAstro(props, slots);
18
+ const request = astro.request ?? result.request;
19
+ return {
20
+ request,
21
+ url: astro.url ?? new URL(request.url),
22
+ params: astro.params ?? result.params,
23
+ props: astro.props ?? props
24
+ };
25
+ };
26
+ const renderPage = async (result, component, props, slots) => {
27
+ const currentResult = requireResult(result);
28
+ claimPageResult(currentResult);
29
+ const context = pageContext(currentResult, props, slots);
30
+ const flags = component.flags(context);
31
+ return { html: (await renderFoldkitServerApplication(await component.load(), flags, readFoldkitBuildId())).html };
32
+ };
2
33
  async function check(Component) {
3
- return Component != null && (typeof Component === "object" || typeof Component === "function") && "__foldkit" in Component && Component.__foldkit === true;
34
+ return isFoldkitApp(Component) || isFoldkitPage(Component);
4
35
  }
5
- async function renderToStaticMarkup(_component, _props, _slots) {
36
+ async function renderToStaticMarkup(component, props, slots) {
37
+ if (isFoldkitPage(component)) return renderPage(this?.result, component, props, slots);
6
38
  return { html: "<div data-foldkit-island=\"true\"></div>" };
7
39
  }
8
40
  const renderer = {
@@ -0,0 +1,55 @@
1
+ import { t as NavigationConfig } from "./navigation-Cy2lnE4G.mjs";
2
+ import { Runtime } from "foldkit";
3
+ import { Schema } from "effect";
4
+ import { Document } from "foldkit/html";
5
+
6
+ //#region src/types.d.ts
7
+ type TaggedMessage = {
8
+ readonly _tag: string;
9
+ };
10
+ type CommandBatch = ReadonlyArray<unknown>;
11
+ type AppConfigShape<Props extends Record<string, unknown>> = {
12
+ readonly Model: unknown;
13
+ readonly init: (props: Props) => readonly [unknown, CommandBatch];
14
+ readonly update: (model: never, message: never) => readonly [unknown, CommandBatch];
15
+ readonly view: (model: never, h: never) => Document;
16
+ readonly navigation?: NavigationConfig<unknown>;
17
+ readonly ports?: Record<string, unknown>;
18
+ };
19
+ type AppConfig<Props extends Record<string, unknown> = Record<string, unknown>, Model = unknown, Message extends TaggedMessage = TaggedMessage> = {
20
+ readonly Model: unknown;
21
+ readonly init: (props: Props) => readonly [Model, CommandBatch];
22
+ readonly update: Runtime.ApplicationConfig<Model, Message>['update'];
23
+ readonly view: Runtime.ApplicationConfig<Model, Message>['view'];
24
+ };
25
+ type FoldkitApp<Props extends Record<string, unknown> = Record<string, unknown>, Config extends AppConfigShape<Props> = AppConfigShape<Props>> = {
26
+ (props?: Props): void;
27
+ readonly __foldkit: true;
28
+ readonly load: () => Promise<Config>;
29
+ };
30
+ type PageParams = Readonly<Record<string, string | undefined>>;
31
+ type PageFlagsContext<Props extends Record<string, unknown> = Record<string, unknown>> = {
32
+ readonly request: Request;
33
+ readonly url: URL;
34
+ readonly params: PageParams;
35
+ readonly props: Props;
36
+ };
37
+ type PageContext<Props extends Record<string, unknown> = Record<string, unknown>> = PageFlagsContext<Props>;
38
+ type PageFlagsSchema<Flags extends Record<string, unknown>> = Schema.Codec<Flags, any, never, never>;
39
+ type PageConfig<Flags extends Record<string, unknown> = Record<string, unknown>, Model = unknown, Message extends TaggedMessage = TaggedMessage> = AppConfig<Flags, Model, Message> & {
40
+ readonly Flags: PageFlagsSchema<Flags>;
41
+ };
42
+ type PageConfigShape<Flags extends Record<string, unknown>> = AppConfigShape<Flags> & {
43
+ readonly Flags: PageFlagsSchema<Flags>;
44
+ };
45
+ type DefinePageOptions<Props extends Record<string, unknown> = Record<string, unknown>, Flags extends Record<string, unknown> = Record<string, unknown>> = {
46
+ readonly flags: (context: PageFlagsContext<Props>) => Flags;
47
+ };
48
+ type FoldkitPage<Props extends Record<string, unknown> = Record<string, unknown>, Flags extends Record<string, unknown> = Record<string, unknown>, Config extends PageConfigShape<Flags> = PageConfigShape<Flags>> = {
49
+ (props?: Props): void;
50
+ readonly __foldkitPage: true;
51
+ readonly load: () => Promise<Config>;
52
+ readonly flags: (context: PageFlagsContext<Props>) => Flags;
53
+ };
54
+ //#endregion
55
+ export { FoldkitPage as a, PageContext as c, PageParams as d, FoldkitApp as i, PageFlagsContext as l, AppConfigShape as n, PageConfig as o, DefinePageOptions as r, PageConfigShape as s, AppConfig as t, PageFlagsSchema as u };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opsydyn/astro-foldkit",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Astro integration and renderer for FoldKit.",
5
5
  "keywords": [
6
6
  "astro",
@@ -32,6 +32,12 @@
32
32
  "*": {
33
33
  "define-app": [
34
34
  "./dist/define-app.d.mts"
35
+ ],
36
+ "define-page": [
37
+ "./dist/define-page.d.mts"
38
+ ],
39
+ "server": [
40
+ "./dist/server-public.d.mts"
35
41
  ]
36
42
  }
37
43
  },
@@ -43,6 +49,14 @@
43
49
  "./define-app": {
44
50
  "types": "./dist/define-app.d.mts",
45
51
  "import": "./dist/define-app.mjs"
52
+ },
53
+ "./define-page": {
54
+ "types": "./dist/define-page.d.mts",
55
+ "import": "./dist/define-page.mjs"
56
+ },
57
+ "./server": {
58
+ "types": "./dist/server-public.d.mts",
59
+ "import": "./dist/server-public.mjs"
46
60
  }
47
61
  },
48
62
  "publishConfig": {
@@ -58,20 +72,21 @@
58
72
  "check:fix": "oxfmt . && NODE_OPTIONS=\"--experimental-strip-types\" oxlint --fix ."
59
73
  },
60
74
  "dependencies": {
61
- "@foldkit/vite-plugin": "^0.10.1"
75
+ "@foldkit/vite-plugin": "^0.16.0",
76
+ "effect": "4.0.0-rc.109"
62
77
  },
63
78
  "devDependencies": {
64
79
  "@types/node": "^22.0.0",
65
80
  "astro": "7.1.1",
66
81
  "bun-types": "^1.3.14",
67
82
  "fast-check": "^4.8.0",
68
- "foldkit": "^0.129.0",
83
+ "foldkit": "^0.148.0",
69
84
  "tsdown": "^0.21.8",
70
85
  "typescript": "^6.0.3"
71
86
  },
72
87
  "peerDependencies": {
73
88
  "astro": ">=5.0.0",
74
- "foldkit": ">=0.129.0"
89
+ "foldkit": ">=0.148.0 <0.149.0"
75
90
  },
76
91
  "engines": {
77
92
  "node": ">=22.0.0"
@@ -1,30 +0,0 @@
1
- import { t as NavigationConfig } from "./navigation-Cy2lnE4G.mjs";
2
- import { Runtime } from "foldkit";
3
- import { Document } from "foldkit/html";
4
-
5
- //#region src/types.d.ts
6
- type TaggedMessage = {
7
- readonly _tag: string;
8
- };
9
- type CommandBatch = ReadonlyArray<unknown>;
10
- type AppConfigShape<Props extends Record<string, unknown>> = {
11
- readonly Model: unknown;
12
- readonly init: (props: Props) => readonly [unknown, CommandBatch];
13
- readonly update: (model: never, message: never) => readonly [unknown, CommandBatch];
14
- readonly view: (model: never) => Document;
15
- readonly navigation?: NavigationConfig<unknown>;
16
- readonly ports?: Record<string, unknown>;
17
- };
18
- type AppConfig<Props extends Record<string, unknown> = Record<string, unknown>, Model = unknown, Message extends TaggedMessage = TaggedMessage> = {
19
- readonly Model: unknown;
20
- readonly init: (props: Props) => readonly [Model, CommandBatch];
21
- readonly update: Runtime.ApplicationConfig<Model, Message>['update'];
22
- readonly view: (model: Model) => Document;
23
- };
24
- type FoldkitApp<Props extends Record<string, unknown> = Record<string, unknown>, Config extends AppConfigShape<Props> = AppConfigShape<Props>> = {
25
- (props?: Props): void;
26
- readonly __foldkit: true;
27
- readonly load: () => Promise<Config>;
28
- };
29
- //#endregion
30
- export { AppConfigShape as n, FoldkitApp as r, AppConfig as t };