@ilha/void 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugin.js ADDED
@@ -0,0 +1,393 @@
1
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { generateComponentManifest, resolveEffectiveLayoutChain, resolvePagesDir, resolveStaticPageDataBuildOptions, scanPages } from "void/pages";
4
+ import { normalizePath } from "vite";
5
+ import { ISLANDS_CLIENT_ENTRY_ID, ISLANDS_RENDERER_ID, computePagesNeedingClientJS, editIslandSource, findIslandImports, findStaticCssImports, needsIslandClientBundle, resolveSpecifier, rewriteCssImportForVirtualModule, watchPagesForRescan } from "void/pages-islands-plugin";
6
+
7
+ //#region src/plugin-islands.ts
8
+ const COMPONENT_EXTENSIONS = [
9
+ ".tsx",
10
+ ".jsx",
11
+ ".ts",
12
+ ".js"
13
+ ];
14
+ /** Island wrapper modules. Plain JS: wrappers call `createIsland`, no JSX. */
15
+ const WRAPPER_PREFIX = "/@ilha-void-island/";
16
+ const ISLAND_PAGE_RE = /\.island\.(?:tsx|jsx)$/u;
17
+ const PAGE_COMPONENT_RE$1 = /\.(?:tsx|jsx)$/u;
18
+ const EXTENSION_RE = /\.[^.]+$/u;
19
+ const VIRTUAL_ID_RE$1 = /^(?:virtual:void-islands-(?:renderer|client)$|\/@ilha-void-island\/)/u;
20
+ const RESOLVED_ID_RE$1 = /^(?:\0virtual:void-islands-(?:renderer|client)$|\/@ilha-void-island\/)/u;
21
+ const USE_FORM_IMPORT_RE = /import\s+\{[^}]*\buseForm\b/u;
22
+ const generateWrapperModule = ({ hydrate, islandId, src }) => `import Component from ${JSON.stringify(src)};
23
+ import { createIsland } from "@ilha/void/server";
24
+
25
+ export default createIsland(Component, { hydrate: ${JSON.stringify(hydrate)}, id: ${JSON.stringify(islandId)} });
26
+ `;
27
+ const generateIslandRendererModule = (scan, pagesDir, { markdownScriptIds, pagesNeedingClientJS }) => `import { createIslandPageRenderer } from "@ilha/void/server";
28
+
29
+ ${generateComponentManifest(scan, pagesDir)}
30
+
31
+ export const renderIslandPage = createIslandPageRenderer({
32
+ components,
33
+ layoutTree,
34
+ markdownScriptIds: new Set(${JSON.stringify([...markdownScriptIds])}),
35
+ pagesNeedingClientJS: new Set(${JSON.stringify([...pagesNeedingClientJS])}),
36
+ });
37
+ `;
38
+ const generateIslandClientEntry = (manifest, { cssImports }) => {
39
+ const islands = /* @__PURE__ */ new Map();
40
+ for (const entry of manifest.values()) islands.set(entry.islandId, entry.componentPath);
41
+ const loaders = [...islands].map(([id, file]) => ` ${JSON.stringify(id)}: () => import(${JSON.stringify(file)}),`).join("\n");
42
+ return `import { mountIsland } from "@ilha/void/islands";
43
+ import { initIslands } from "void/pages-client";
44
+ ${cssImports.join("\n")}
45
+
46
+ const islands = {
47
+ ${loaders}
48
+ };
49
+
50
+ initIslands(islands, mountIsland);
51
+ `;
52
+ };
53
+ /**
54
+ * Turn `with { island }` imports in `.island` pages into SSR wrappers and
55
+ * serve Void's island renderer and client entry.
56
+ */
57
+ const islandsPlugin = (pagesDir, { root }) => {
58
+ let scan = null;
59
+ let isDev = false;
60
+ let resolvedConfig = null;
61
+ const islandManifest = /* @__PURE__ */ new Map();
62
+ const cssSourceFiles = /* @__PURE__ */ new Set();
63
+ const wrappers = /* @__PURE__ */ new Map();
64
+ let wrapperCount = 0;
65
+ const registerIsland = (specifier, importerDir, hydrate) => {
66
+ const absPath = resolveSpecifier(specifier, importerDir, COMPONENT_EXTENSIONS);
67
+ if (!absPath) return {
68
+ absPath,
69
+ islandId: specifier
70
+ };
71
+ const islandId = normalizePath(path.relative(root, absPath)).replace(EXTENSION_RE, "");
72
+ islandManifest.set(islandId, {
73
+ componentPath: absPath,
74
+ hydrate,
75
+ islandId
76
+ });
77
+ return {
78
+ absPath,
79
+ islandId
80
+ };
81
+ };
82
+ /** Read island imports and CSS sources ahead of time for the client build. */
83
+ const prescan = (pages) => {
84
+ const files = [...pages.pages.map((page) => ({
85
+ file: page.componentPath,
86
+ island: page.island
87
+ })), ...[...pages.layouts, ...pages.namedLayouts].map((layout) => ({
88
+ file: layout.filePath,
89
+ island: layout.island
90
+ }))];
91
+ for (const { file, island } of files) {
92
+ if (!island) continue;
93
+ const filePath = path.resolve(pagesDir, file);
94
+ const code = readFileSync(filePath, "utf-8");
95
+ for (const found of findIslandImports(code, filePath)) registerIsland(found.specifier, path.dirname(filePath), found.hydrate);
96
+ }
97
+ for (const page of pages.pages) {
98
+ if (!page.island) continue;
99
+ if (PAGE_COMPONENT_RE$1.test(page.componentPath)) cssSourceFiles.add(normalizePath(path.resolve(pagesDir, page.componentPath)));
100
+ for (const layout of resolveEffectiveLayoutChain(page, pages.layouts, pages.namedLayouts)) cssSourceFiles.add(normalizePath(path.resolve(pagesDir, layout.filePath)));
101
+ }
102
+ };
103
+ const cssImports = () => {
104
+ if (isDev) return [];
105
+ const lines = [];
106
+ for (const file of cssSourceFiles) {
107
+ const code = readFileSync(file, "utf-8");
108
+ for (const item of findStaticCssImports(code, file)) lines.push(rewriteCssImportForVirtualModule(item.statement, item.specifier, file));
109
+ }
110
+ return lines;
111
+ };
112
+ return {
113
+ async buildStart() {
114
+ if (!existsSync(pagesDir)) return;
115
+ scan = await scanPages(root, { pagesDir });
116
+ prescan(scan);
117
+ },
118
+ config(_, env) {
119
+ if (env.command === "serve" || !existsSync(pagesDir) || !needsIslandClientBundle(pagesDir, ISLAND_PAGE_RE, false)) return;
120
+ return { build: {
121
+ manifest: true,
122
+ rollupOptions: { input: { "islands-client": ISLANDS_CLIENT_ENTRY_ID } }
123
+ } };
124
+ },
125
+ configResolved(config) {
126
+ resolvedConfig = config;
127
+ isDev = config.command === "serve";
128
+ },
129
+ configureServer(server) {
130
+ watchPagesForRescan(server, pagesDir, root, (next) => {
131
+ scan = next;
132
+ });
133
+ },
134
+ enforce: "pre",
135
+ load: {
136
+ filter: { id: RESOLVED_ID_RE$1 },
137
+ handler(id) {
138
+ if (id === `\0${ISLANDS_RENDERER_ID}`) {
139
+ if (!scan) return "export function renderIslandPage() { throw new Error('@ilha/void: no pages found.'); }";
140
+ const markdown = resolvedConfig?.plugins.find((plugin) => plugin.name === "void-md");
141
+ return generateIslandRendererModule(scan, pagesDir, {
142
+ markdownScriptIds: new Set(markdown?.api?.getClientScripts?.().keys()),
143
+ pagesNeedingClientJS: computePagesNeedingClientJS(scan, pagesDir, resolvedConfig)
144
+ });
145
+ }
146
+ if (id === `\0${ISLANDS_CLIENT_ENTRY_ID}`) return scan ? generateIslandClientEntry(islandManifest, { cssImports: cssImports() }) : "";
147
+ const wrapper = wrappers.get(id);
148
+ return wrapper ? generateWrapperModule(wrapper) : void 0;
149
+ }
150
+ },
151
+ name: "@ilha/void:islands",
152
+ resolveId: {
153
+ filter: { id: VIRTUAL_ID_RE$1 },
154
+ handler(source) {
155
+ if (source.startsWith(WRAPPER_PREFIX)) return source;
156
+ return `\0${source}`;
157
+ }
158
+ },
159
+ transform: {
160
+ filter: { id: ISLAND_PAGE_RE },
161
+ handler(code, id) {
162
+ if (USE_FORM_IMPORT_RE.test(code)) this.warn(`@ilha/void: useForm cannot be used in island page '${id}'. Use useIslandForm instead.`);
163
+ const edits = [];
164
+ for (const found of findIslandImports(code, id)) {
165
+ const { absPath, islandId } = registerIsland(found.specifier, path.dirname(id), found.hydrate);
166
+ const wrapperId = `${WRAPPER_PREFIX}island_${String(wrapperCount)}.js`;
167
+ wrapperCount += 1;
168
+ wrappers.set(wrapperId, {
169
+ hydrate: found.hydrate,
170
+ islandId,
171
+ src: absPath ?? found.specifier
172
+ });
173
+ edits.push({
174
+ end: found.end,
175
+ start: found.start,
176
+ text: `import ${found.importName} from ${JSON.stringify(wrapperId)}`
177
+ });
178
+ }
179
+ return edits.length > 0 ? editIslandSource(code, edits) : void 0;
180
+ }
181
+ }
182
+ };
183
+ };
184
+
185
+ //#endregion
186
+ //#region src/plugin-pages.ts
187
+ const RENDERER_ID = "virtual:void-pages-renderer";
188
+ const CLIENT_ENTRY_ID = "virtual:void-pages-client";
189
+ const VIRTUAL_ID_RE = /^virtual:void-pages-(?:renderer|client)$/u;
190
+ const RESOLVED_ID_RE = /^\0virtual:void-pages-(?:renderer|client)$/u;
191
+ const PAGE_COMPONENT_RE = /\.(?:tsx|jsx)$/u;
192
+ const DEFAULT_HOVER_DELAY = 75;
193
+ const DEFAULT_CACHE_FOR = "30s";
194
+ /** True when `dir` holds a regular page, so the pages client must be built. */
195
+ const hasRegularPages = (dir) => {
196
+ try {
197
+ for (const entry of readdirSync(dir, {
198
+ recursive: true,
199
+ withFileTypes: true
200
+ })) {
201
+ const { name } = entry;
202
+ if (entry.isFile() && !name.startsWith("_") && !name.startsWith("layout.") && PAGE_COMPONENT_RE.test(name) && !name.includes(".island.")) return true;
203
+ }
204
+ } catch {}
205
+ return false;
206
+ };
207
+ const generateRendererModule = (scan, pagesDir) => `import { createPageRenderer } from "@ilha/void/server";
208
+
209
+ ${generateComponentManifest(scan, pagesDir)}
210
+
211
+ export const renderPage = createPageRenderer({ components, layoutTree });
212
+ `;
213
+ const generateClientEntry = (scan, pagesDir, { prefetch, staticPageData, viewTransitions }) => `import { startPages } from "@ilha/void/client";
214
+ import { parseCacheFor } from "void/pages-prefetch";
215
+
216
+ ${generateComponentManifest(scan, pagesDir)}
217
+
218
+ export const router = await startPages({
219
+ components,
220
+ layoutTree,
221
+ matchRoute,
222
+ prefetchDefaultCacheFor: parseCacheFor(${JSON.stringify(prefetch?.cacheFor ?? DEFAULT_CACHE_FOR)}),
223
+ prefetchHoverDelay: ${String(prefetch?.hoverDelay ?? DEFAULT_HOVER_DELAY)},
224
+ routeMeta,
225
+ staticPageData: ${String(staticPageData?.enabled === true)},
226
+ staticPageDataFastPath: ${String(staticPageData?.fastPath === true)},
227
+ viewTransitions: ${String(viewTransitions === true)},
228
+ });
229
+ `;
230
+ const invalidatePageModules = (server) => {
231
+ for (const environment of Object.values(server.environments)) for (const id of [`\0${RENDERER_ID}`, `\0${CLIENT_ENTRY_ID}`]) {
232
+ const mod = environment.moduleGraph.getModuleById(id);
233
+ if (mod) environment.moduleGraph.invalidateModule(mod);
234
+ }
235
+ };
236
+ /** Serve Void's pages renderer and client entry for Ilha components. */
237
+ const pagesPlugin = (pagesDir, options) => {
238
+ let scan = null;
239
+ let pendingScan = null;
240
+ let isDev = false;
241
+ let viteConfig;
242
+ const normalizedPagesDir = normalizePath(pagesDir);
243
+ const scanNow = async () => {
244
+ try {
245
+ scan = existsSync(pagesDir) ? await scanPages(options.root, { pagesDir }) : null;
246
+ } finally {
247
+ pendingScan = null;
248
+ }
249
+ };
250
+ /** Rescan the pages dir, sharing one scan between concurrent callers. */
251
+ const rescan = () => {
252
+ pendingScan ??= scanNow();
253
+ return pendingScan;
254
+ };
255
+ return {
256
+ async buildStart() {
257
+ await rescan();
258
+ },
259
+ config(_, env) {
260
+ if (!existsSync(pagesDir)) return;
261
+ if (env.command === "serve") {
262
+ isDev = true;
263
+ return;
264
+ }
265
+ if (!hasRegularPages(pagesDir)) return;
266
+ return { build: {
267
+ manifest: true,
268
+ rollupOptions: { input: { "pages-client": CLIENT_ENTRY_ID } }
269
+ } };
270
+ },
271
+ configResolved(config) {
272
+ viteConfig = config;
273
+ },
274
+ configureServer(server) {
275
+ const onChange = async (file, event) => {
276
+ const normalized = normalizePath(file);
277
+ if (normalized !== normalizedPagesDir && !normalized.startsWith(`${normalizedPagesDir}/`)) return;
278
+ if (event === "change" && !normalized.endsWith(".md")) return;
279
+ await rescan();
280
+ invalidatePageModules(server);
281
+ };
282
+ server.watcher.on("add", (file) => onChange(file, "add"));
283
+ server.watcher.on("change", (file) => onChange(file, "change"));
284
+ server.watcher.on("unlink", (file) => onChange(file, "unlink"));
285
+ },
286
+ load: {
287
+ filter: { id: RESOLVED_ID_RE },
288
+ async handler(id) {
289
+ if (isDev && pendingScan) await pendingScan;
290
+ if (!scan && existsSync(pagesDir)) await rescan();
291
+ if (id === `\0${RENDERER_ID}`) return scan ? generateRendererModule(scan, pagesDir) : "export function renderPage() { throw new Error('@ilha/void: no pages found.'); }";
292
+ if (!scan) return "";
293
+ return generateClientEntry(scan, pagesDir, {
294
+ prefetch: options.prefetch,
295
+ staticPageData: resolveStaticPageDataBuildOptions(options.root, { publicDir: viteConfig?.publicDir }),
296
+ viewTransitions: options.viewTransitions
297
+ });
298
+ }
299
+ },
300
+ name: "@ilha/void:pages",
301
+ resolveId: {
302
+ filter: { id: VIRTUAL_ID_RE },
303
+ handler: (id) => `\0${id}`
304
+ }
305
+ };
306
+ };
307
+
308
+ //#endregion
309
+ //#region src/plugin.ts
310
+ const readJson = (file) => {
311
+ try {
312
+ return JSON.parse(readFileSync(file, "utf-8"));
313
+ } catch {
314
+ return null;
315
+ }
316
+ };
317
+ const readDependencyPackageJson = (root, name) => {
318
+ let dir = root;
319
+ for (;;) {
320
+ const candidate = path.join(dir, "node_modules", name, "package.json");
321
+ if (existsSync(candidate)) return readJson(candidate);
322
+ const parent = path.dirname(dir);
323
+ if (parent === dir) return null;
324
+ dir = parent;
325
+ }
326
+ };
327
+ /**
328
+ * App dependencies built on ilha (a UI library, for example). They must share
329
+ * the app's ilha instance: a second copy breaks context lookup and hydration.
330
+ */
331
+ const detectIlhaConsumers = (root) => {
332
+ const app = readJson(path.join(root, "package.json"));
333
+ if (!app) return [];
334
+ return Object.keys({
335
+ ...app.dependencies,
336
+ ...app.devDependencies
337
+ }).filter((name) => {
338
+ if (name === "ilha" || name === "@ilha/void") return false;
339
+ const pkg = readDependencyPackageJson(root, name);
340
+ return pkg !== null && ("ilha" in (pkg.peerDependencies ?? {}) || "ilha" in (pkg.dependencies ?? {}));
341
+ });
342
+ };
343
+ const withNoExternal = (existing, names) => {
344
+ if (existing === true) return true;
345
+ let list = [];
346
+ if (Array.isArray(existing)) list = existing;
347
+ else if (existing !== void 0) list = [existing];
348
+ return [.../* @__PURE__ */ new Set([...list, ...names])];
349
+ };
350
+ const configPlugin = () => ({
351
+ config(userConfig) {
352
+ const root = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
353
+ const singletons = [
354
+ "ilha",
355
+ "@ilha/void",
356
+ ...detectIlhaConsumers(root)
357
+ ];
358
+ return {
359
+ ...userConfig.oxc === false || userConfig.oxc?.jsx !== void 0 ? {} : { oxc: { jsx: {
360
+ importSource: "ilha",
361
+ runtime: "automatic"
362
+ } } },
363
+ optimizeDeps: { include: [
364
+ "ilha",
365
+ "ilha/jsx-runtime",
366
+ "ilha/jsx-dev-runtime"
367
+ ] },
368
+ resolve: { dedupe: singletons },
369
+ ssr: { noExternal: withNoExternal(userConfig.ssr?.noExternal, singletons) }
370
+ };
371
+ },
372
+ name: "@ilha/void:config"
373
+ });
374
+ /**
375
+ * Render Void pages, layouts, and islands with ilha. Add it after
376
+ * `voidPlugin()` in your Vite config.
377
+ */
378
+ const voidIlha = (options = {}) => {
379
+ const root = process.cwd();
380
+ const pagesDir = resolvePagesDir(root);
381
+ return [
382
+ configPlugin(),
383
+ pagesPlugin(pagesDir, {
384
+ prefetch: options.prefetch,
385
+ root,
386
+ viewTransitions: options.viewTransitions
387
+ }),
388
+ islandsPlugin(pagesDir, { root })
389
+ ];
390
+ };
391
+
392
+ //#endregion
393
+ export { voidIlha };
@@ -0,0 +1,38 @@
1
+ import type { View } from "ilha";
2
+ import type { PageObject } from "void/pages-protocol";
3
+ import type { ComponentManifest, LayoutTree, PageComponent } from "./app";
4
+ import type { JsonRecord } from "./types";
5
+ /** Asset markup Void hands to a page renderer. */
6
+ export interface AssetTags {
7
+ readonly css: string;
8
+ readonly preloads: string;
9
+ readonly body: string;
10
+ }
11
+ export interface PageRendererOptions {
12
+ components: ComponentManifest;
13
+ layoutTree: LayoutTree;
14
+ }
15
+ export interface IslandPageRendererOptions extends PageRendererOptions {
16
+ /** Component IDs whose island page ships client JavaScript. */
17
+ pagesNeedingClientJS: ReadonlySet<string>;
18
+ /** Markdown component IDs with a client script for `void-md`. */
19
+ markdownScriptIds: ReadonlySet<string>;
20
+ }
21
+ /** Build `renderPage` for regular pages: full SSR, hydrated by the Void Router. */
22
+ export declare const createPageRenderer: (options: PageRendererOptions) => (pageObj: PageObject, assetTags: AssetTags) => Promise<string>;
23
+ /** Build `renderIslandPage` for `.island` pages: static HTML plus islands. */
24
+ export declare const createIslandPageRenderer: (options: IslandPageRendererOptions) => (pageObj: PageObject, assetTags: AssetTags) => Promise<string>;
25
+ export interface IslandOptions {
26
+ /** Island ID in the client island manifest. */
27
+ id: string;
28
+ /** Void hydration strategy: `load`, `visible`, `idle`, or `media:(query)`. */
29
+ hydrate: string;
30
+ }
31
+ /**
32
+ * Wrap a component imported `with { island }`. The server renders it as its
33
+ * own root so its hydration snapshot travels with it; the islands client
34
+ * mounts it from the `data-island` marker.
35
+ */
36
+ export declare const createIsland: (Component: PageComponent, { hydrate, id }: IslandOptions) => ({ children: _children, ...props }: JsonRecord & {
37
+ children?: View;
38
+ }) => Promise<View>;
package/dist/server.js ADDED
@@ -0,0 +1,95 @@
1
+ import { n as createPageState } from "./context-fQy_XW7o.js";
2
+ import { n as loadPageComponents, r as routeData, t as createPageRoot } from "./app-C92pEfKv.js";
3
+ import { createSsrRouter, idleNavigationState } from "void/pages-client";
4
+ import { h, renderToString, unsafe } from "ilha";
5
+ import { renderBodyAttrs, renderHeadToString, renderHtmlAttrs } from "void/pages-head";
6
+ import { serializePageData } from "void/pages-server";
7
+
8
+ //#region src/server.ts
9
+ const escapeAttr = (value) => value.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;");
10
+ const renderDocument = ({ app, body, head, pageObj }) => {
11
+ const pageHead = pageObj.head ? renderHeadToString(pageObj.head) : "";
12
+ return `<!doctype html>
13
+ <html${pageObj.head ? renderHtmlAttrs(pageObj.head) : ""}>
14
+ <head>${pageHead}${head}</head>
15
+ <body${pageObj.head ? renderBodyAttrs(pageObj.head) : ""}>
16
+ ${app}
17
+ ${body}
18
+ </body>
19
+ </html>`;
20
+ };
21
+ const renderTree = async ({ components, hydratable, layoutTree, pageObj, router }) => {
22
+ const { errors, pageId, params, props, shared } = routeData(pageObj);
23
+ const { layouts, page } = await loadPageComponents({
24
+ componentId: pageId,
25
+ components,
26
+ layoutTree
27
+ });
28
+ const tree = {
29
+ layouts,
30
+ page,
31
+ pageKey: pageId,
32
+ props,
33
+ state: createPageState({
34
+ errors,
35
+ navigation: idleNavigationState(),
36
+ params,
37
+ router,
38
+ shared
39
+ })
40
+ };
41
+ return await renderToString(createPageRoot({ read: () => tree }), {
42
+ markers: hydratable,
43
+ snapshot: hydratable
44
+ });
45
+ };
46
+ /** Build `renderPage` for regular pages: full SSR, hydrated by the Void Router. */
47
+ const createPageRenderer = (options) => async (pageObj, assetTags) => {
48
+ const html = await renderTree({
49
+ ...options,
50
+ hydratable: true,
51
+ pageObj,
52
+ router: createSsrRouter(pageObj.url || "/", pageObj.params ?? {})
53
+ });
54
+ return renderDocument({
55
+ app: `<script id="__VOID_PAGE_DATA__" type="application/json">${serializePageData(pageObj)}<\/script>
56
+ <div id="app">${html}</div>`,
57
+ body: assetTags.body,
58
+ head: `${assetTags.css}${assetTags.preloads}`,
59
+ pageObj
60
+ });
61
+ };
62
+ /** Build `renderIslandPage` for `.island` pages: static HTML plus islands. */
63
+ const createIslandPageRenderer = (options) => async (pageObj, assetTags) => {
64
+ const html = await renderTree({
65
+ ...options,
66
+ hydratable: false,
67
+ pageObj,
68
+ router: null
69
+ });
70
+ const needsJS = options.pagesNeedingClientJS.has(pageObj.component);
71
+ const mdScript = options.markdownScriptIds.has(pageObj.component) ? ` data-md-script="${escapeAttr(pageObj.component)}"` : "";
72
+ return renderDocument({
73
+ app: `<div id="app"${mdScript}>${html}</div>`,
74
+ body: needsJS ? assetTags.body : "",
75
+ head: `${assetTags.css}${needsJS ? assetTags.preloads : ""}`,
76
+ pageObj
77
+ });
78
+ };
79
+ /**
80
+ * Wrap a component imported `with { island }`. The server renders it as its
81
+ * own root so its hydration snapshot travels with it; the islands client
82
+ * mounts it from the `data-island` marker.
83
+ */
84
+ const createIsland = (Component, { hydrate, id }) => async ({ children: _children, ...props }) => {
85
+ const render = Component;
86
+ const html = await renderToString(() => render(props));
87
+ return h("div", {
88
+ "data-hydrate": hydrate,
89
+ "data-island": id,
90
+ "data-props": JSON.stringify(props)
91
+ }, unsafe(html));
92
+ };
93
+
94
+ //#endregion
95
+ export { createIsland, createIslandPageRenderer, createPageRenderer };
@@ -0,0 +1,22 @@
1
+ import type { DeferredState } from "void";
2
+ /** A JSON value: what Void serializes into page data and island props. */
3
+ export type JsonValue = string | number | boolean | null | readonly JsonValue[] | JsonRecord;
4
+ export interface JsonRecord {
5
+ readonly [key: string]: JsonValue | undefined;
6
+ }
7
+ /** A loader prop: JSON, or the state of a `defer()`red value. */
8
+ export type PageValue = JsonValue | DeferredState<JsonValue>;
9
+ /** Props Void passes to a page: its loader result. */
10
+ export type PageProps = Readonly<Record<string, PageValue | undefined>>;
11
+ /** Field validation messages, keyed by field name. */
12
+ export type FieldErrors = Readonly<Record<string, string>>;
13
+ /** A form field value. `Blob`s make Void submit the form as multipart. */
14
+ export type FormValue = JsonValue | Blob | readonly FormValue[] | {
15
+ readonly [key: string]: FormValue | undefined;
16
+ };
17
+ /** Form data: field name → value. */
18
+ export type FormValues = Readonly<Record<string, FormValue | undefined>>;
19
+ /** Widen literal field types from form defaults: `false` → `boolean`. */
20
+ export type WidenFields<T> = {
21
+ [K in keyof T]: T[K] extends string ? string : T[K] extends number ? number : T[K] extends boolean ? boolean : T[K];
22
+ };
@@ -0,0 +1,27 @@
1
+ import type { VisitOptions } from "void/pages-client";
2
+ import type { ActionFormOptions, ActionUrl, ResolveActionBody } from "void/routes";
3
+ import type { FormFields } from "./form-state";
4
+ import type { FormValues, WidenFields } from "./types";
5
+ export type FormSubmitOptions = Omit<VisitOptions, "method" | "data"> & {
6
+ data?: FormValues;
7
+ };
8
+ /** `useForm()` state plus submit helpers that go through the Void Router. */
9
+ export interface PageForm<T extends object> extends FormFields<T> {
10
+ post: (options?: FormSubmitOptions) => Promise<void>;
11
+ put: (options?: FormSubmitOptions) => Promise<void>;
12
+ patch: (options?: FormSubmitOptions) => Promise<void>;
13
+ delete: (options?: FormSubmitOptions) => Promise<void>;
14
+ }
15
+ export interface UseForm {
16
+ /** Typed from the page's action when Void's route types are generated. */
17
+ <U extends ActionUrl & string>(url: U, defaults: ResolveActionBody<U>, options?: ActionFormOptions<U>): PageForm<WidenFields<ResolveActionBody<U>>>;
18
+ <T extends FormValues>(url: string, defaults: T, options?: {
19
+ params?: Record<string, string>;
20
+ }): PageForm<WidenFields<T>>;
21
+ }
22
+ /**
23
+ * Bind form state to a page action. Submits through the Void Router, so a
24
+ * success refreshes page props without a full reload. Island pages use
25
+ * `useIslandForm()` instead.
26
+ */
27
+ export declare const useForm: UseForm;
@@ -0,0 +1,14 @@
1
+ import type { FormFields } from "./form-state";
2
+ import type { FormValues, WidenFields } from "./types";
3
+ /** `useIslandForm()` state plus submit helpers that take the action URL. */
4
+ export interface IslandForm<T extends object> extends FormFields<T> {
5
+ post: (url: string) => Promise<void>;
6
+ put: (url: string) => Promise<void>;
7
+ patch: (url: string) => Promise<void>;
8
+ delete: (url: string) => Promise<void>;
9
+ }
10
+ /**
11
+ * Form state for island pages, which have no Void Router. Submits with
12
+ * `fetch()`, then reloads the page or follows the redirect.
13
+ */
14
+ export declare const useIslandForm: <T extends FormValues>(defaults: T) => IslandForm<WidenFields<T>>;
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "@ilha/void",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Ilha pages, server rendering, islands, forms, and navigation for Void",
5
+ "keywords": [
6
+ "frontend",
7
+ "ilha",
8
+ "island-architecture",
9
+ "islands",
10
+ "ssr",
11
+ "vite",
12
+ "void"
13
+ ],
14
+ "homepage": "https://github.com/ilhajs/ilha/tree/main/packages/void#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/ilhajs/ilha/issues"
17
+ },
18
+ "license": "MIT",
19
+ "author": "Ryuz <ryuzer@proton.me>",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/ilhajs/ilha.git"
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "main": "./dist/index.js",
30
+ "module": "./dist/index.js",
31
+ "types": "./dist/index.d.ts",
32
+ "exports": {
33
+ ".": {
34
+ "types": "./dist/index.d.ts",
35
+ "import": "./dist/index.js"
36
+ },
37
+ "./client": {
38
+ "types": "./dist/client.d.ts",
39
+ "import": "./dist/client.js"
40
+ },
41
+ "./islands": {
42
+ "types": "./dist/islands.d.ts",
43
+ "import": "./dist/islands.js"
44
+ },
45
+ "./plugin": {
46
+ "types": "./dist/plugin.d.ts",
47
+ "import": "./dist/plugin.js"
48
+ },
49
+ "./server": {
50
+ "types": "./dist/server.d.ts",
51
+ "import": "./dist/server.js"
52
+ }
53
+ },
54
+ "publishConfig": {
55
+ "access": "public"
56
+ },
57
+ "scripts": {
58
+ "build": "tsdown && tsc -p tsconfig.build.json",
59
+ "cleanup": "rimraf dist node_modules",
60
+ "test": "bun test"
61
+ },
62
+ "devDependencies": {
63
+ "ilha": "^0.16.0",
64
+ "vite": "^8.3.1",
65
+ "void": "^1.1.11"
66
+ },
67
+ "peerDependencies": {
68
+ "ilha": ">=0.16.0",
69
+ "vite": "^8.0.0",
70
+ "void": "^1.1.0"
71
+ }
72
+ }