@void/solid 0.0.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.
@@ -0,0 +1,708 @@
1
+ import solid from "vite-plugin-solid";
2
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
3
+ import { normalizePath } from "vite";
4
+ import { generateComponentManifest, resolveEffectiveLayoutChain, resolveStaticPageDataBuildOptions, scanPages } from "void/pages";
5
+ import { ISLANDS_CLIENT_ENTRY_ID, ISLANDS_RENDERER_ID, computePagesNeedingClientJS, configureIslandCssServer, extractCssImports, fileHasCssImports, needsIslandClientBundle, rebuildIslandCssMap, resolveSpecifier, rewriteCssImportForVirtualModule, watchPagesForRescan } from "void/pages-islands-plugin";
6
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
7
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
8
+ function normalizeWindowsPath(input = "") {
9
+ if (!input) return input;
10
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
11
+ }
12
+ const _UNC_REGEX = /^[/\\]{2}/;
13
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
14
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
15
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
16
+ const normalize = function(path) {
17
+ if (path.length === 0) return ".";
18
+ path = normalizeWindowsPath(path);
19
+ const isUNCPath = path.match(_UNC_REGEX);
20
+ const isPathAbsolute = isAbsolute(path);
21
+ const trailingSeparator = path[path.length - 1] === "/";
22
+ path = normalizeString(path, !isPathAbsolute);
23
+ if (path.length === 0) {
24
+ if (isPathAbsolute) return "/";
25
+ return trailingSeparator ? "./" : ".";
26
+ }
27
+ if (trailingSeparator) path += "/";
28
+ if (_DRIVE_LETTER_RE.test(path)) path += "/";
29
+ if (isUNCPath) {
30
+ if (!isPathAbsolute) return `//./${path}`;
31
+ return `//${path}`;
32
+ }
33
+ return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
34
+ };
35
+ const join = function(...segments) {
36
+ let path = "";
37
+ for (const seg of segments) {
38
+ if (!seg) continue;
39
+ if (path.length > 0) {
40
+ const pathTrailing = path[path.length - 1] === "/";
41
+ const segLeading = seg[0] === "/";
42
+ if (pathTrailing && segLeading) path += seg.slice(1);
43
+ else path += pathTrailing || segLeading ? seg : `/${seg}`;
44
+ } else path += seg;
45
+ }
46
+ return normalize(path);
47
+ };
48
+ function cwd() {
49
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
50
+ return "/";
51
+ }
52
+ const resolve = function(...arguments_) {
53
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
54
+ let resolvedPath = "";
55
+ let resolvedAbsolute = false;
56
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
57
+ const path = index >= 0 ? arguments_[index] : cwd();
58
+ if (!path || path.length === 0) continue;
59
+ resolvedPath = `${path}/${resolvedPath}`;
60
+ resolvedAbsolute = isAbsolute(path);
61
+ }
62
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
63
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
64
+ return resolvedPath.length > 0 ? resolvedPath : ".";
65
+ };
66
+ function normalizeString(path, allowAboveRoot) {
67
+ let res = "";
68
+ let lastSegmentLength = 0;
69
+ let lastSlash = -1;
70
+ let dots = 0;
71
+ let char = null;
72
+ for (let index = 0; index <= path.length; ++index) {
73
+ if (index < path.length) char = path[index];
74
+ else if (char === "/") break;
75
+ else char = "/";
76
+ if (char === "/") {
77
+ if (lastSlash === index - 1 || dots === 1);
78
+ else if (dots === 2) {
79
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
80
+ if (res.length > 2) {
81
+ const lastSlashIndex = res.lastIndexOf("/");
82
+ if (lastSlashIndex === -1) {
83
+ res = "";
84
+ lastSegmentLength = 0;
85
+ } else {
86
+ res = res.slice(0, lastSlashIndex);
87
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
88
+ }
89
+ lastSlash = index;
90
+ dots = 0;
91
+ continue;
92
+ } else if (res.length > 0) {
93
+ res = "";
94
+ lastSegmentLength = 0;
95
+ lastSlash = index;
96
+ dots = 0;
97
+ continue;
98
+ }
99
+ }
100
+ if (allowAboveRoot) {
101
+ res += res.length > 0 ? "/.." : "..";
102
+ lastSegmentLength = 2;
103
+ }
104
+ } else {
105
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
106
+ else res = path.slice(lastSlash + 1, index);
107
+ lastSegmentLength = index - lastSlash - 1;
108
+ }
109
+ lastSlash = index;
110
+ dots = 0;
111
+ } else if (char === "." && dots !== -1) ++dots;
112
+ else dots = -1;
113
+ }
114
+ return res;
115
+ }
116
+ const isAbsolute = function(p) {
117
+ return _IS_ABSOLUTE_RE.test(p);
118
+ };
119
+ const relative = function(from, to) {
120
+ const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
121
+ const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
122
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
123
+ const _fromCopy = [..._from];
124
+ for (const segment of _fromCopy) {
125
+ if (_to[0] !== segment) break;
126
+ _from.shift();
127
+ _to.shift();
128
+ }
129
+ return [..._from.map(() => ".."), ..._to].join("/");
130
+ };
131
+ const dirname = function(p) {
132
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
133
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
134
+ return segments.join("/") || (isAbsolute(p) ? "/" : ".");
135
+ };
136
+ //#endregion
137
+ //#region src/plugin-islands.ts
138
+ const COMPONENT_EXTENSIONS = [
139
+ ".tsx",
140
+ ".jsx",
141
+ ".ts",
142
+ ".js"
143
+ ];
144
+ /**
145
+ * Prefix for virtual island wrapper modules. Must NOT use the `\0` prefix
146
+ * because `vite-plugin-solid` skips `\0`-prefixed modules in its transform
147
+ * filter. Uses a clean `.tsx` extension (no query params) so rolldown can
148
+ * detect the language.
149
+ */
150
+ const WRAPPER_PREFIX = "/@void-island-wrap/";
151
+ function islandsPlugin(pagesDir) {
152
+ let pageScan = null;
153
+ let isDev = false;
154
+ const root = dirname(pagesDir);
155
+ const islandManifest = /* @__PURE__ */ new Map();
156
+ const islandCssFiles = /* @__PURE__ */ new Set();
157
+ const wrapperMeta = /* @__PURE__ */ new Map();
158
+ let wrapperId = 0;
159
+ let viteRoot = "";
160
+ const islandCssMap = /* @__PURE__ */ new Map();
161
+ let resolvedConfig = null;
162
+ /** Rebuild islandCssMap from current file contents (re-runs fileHasCssImports). */
163
+ function rebuildIslandCssMap$1() {
164
+ if (!pageScan) return;
165
+ rebuildIslandCssMap(pageScan, pagesDir, islandCssMap, fileHasCssImports);
166
+ }
167
+ function computePagesNeedingClientJS$1() {
168
+ if (!pageScan) return /* @__PURE__ */ new Set();
169
+ return computePagesNeedingClientJS(pageScan, pagesDir, resolvedConfig);
170
+ }
171
+ return [{
172
+ name: "void-solid:islands",
173
+ enforce: "pre",
174
+ configResolved(config) {
175
+ resolvedConfig = config;
176
+ viteRoot = config.root;
177
+ isDev = config.command === "serve";
178
+ },
179
+ configureServer(server) {
180
+ configureIslandCssServer(server, islandCssFiles, viteRoot, rebuildIslandCssMap$1);
181
+ watchPagesForRescan(server, pagesDir, root, (scan) => {
182
+ pageScan = scan;
183
+ rebuildIslandCssMap$1();
184
+ });
185
+ },
186
+ async buildStart() {
187
+ if (existsSync(pagesDir)) {
188
+ pageScan = await scanPages(root);
189
+ const importAttrRe = /import\s+\w+\s+from\s+("[^"]+"|'[^']+')\s+with\s*\{\s*island\s*:\s*("[^"]+"|'[^']+')\s*\}/g;
190
+ const filesToScan = [
191
+ ...pageScan.pages.map((p) => ({
192
+ filePath: p.componentPath,
193
+ island: p.island
194
+ })),
195
+ ...pageScan.layouts.map((l) => ({
196
+ filePath: l.filePath,
197
+ island: l.island
198
+ })),
199
+ ...pageScan.namedLayouts.map((nl) => ({
200
+ filePath: nl.filePath,
201
+ island: nl.island
202
+ }))
203
+ ];
204
+ for (const entry of filesToScan) {
205
+ if (!entry.island) continue;
206
+ const filePath = resolve(pagesDir, entry.filePath);
207
+ const code = readFileSync(filePath, "utf-8");
208
+ const importerDir = dirname(filePath);
209
+ importAttrRe.lastIndex = 0;
210
+ let m;
211
+ while ((m = importAttrRe.exec(code)) !== null) {
212
+ const spec = m[1].slice(1, -1);
213
+ const strategy = m[2].slice(1, -1);
214
+ const absPath = resolveSpecifier(spec, importerDir, COMPONENT_EXTENSIONS);
215
+ if (absPath) {
216
+ const islandId = normalizePath(relative(root, absPath)).replace(/\.[^.]+$/, "");
217
+ islandManifest.set(islandId, {
218
+ componentPath: absPath,
219
+ islandId,
220
+ hydrate: strategy
221
+ });
222
+ }
223
+ }
224
+ }
225
+ for (const page of pageScan.pages) {
226
+ if (!page.island) continue;
227
+ if (/\.(tsx|jsx)$/.test(page.componentPath)) islandCssFiles.add(normalizePath(resolve(pagesDir, page.componentPath)));
228
+ const layoutChain = resolveEffectiveLayoutChain(page, pageScan.layouts, pageScan.namedLayouts);
229
+ for (const layout of layoutChain) islandCssFiles.add(normalizePath(resolve(pagesDir, layout.filePath)));
230
+ }
231
+ rebuildIslandCssMap$1();
232
+ }
233
+ },
234
+ resolveId: {
235
+ filter: { id: /^(virtual:void-islands-(renderer|client)|\/@void-island-wrap\/)|\.(tsx|jsx)\.css$/ },
236
+ handler(source) {
237
+ if (source === ISLANDS_RENDERER_ID || source === ISLANDS_CLIENT_ENTRY_ID) return "\0" + source;
238
+ if (source.startsWith(WRAPPER_PREFIX)) return source;
239
+ if (source.endsWith(".css")) {
240
+ const srcPath = normalizePath(source.slice(0, -4));
241
+ if (islandCssFiles.has(srcPath)) return srcPath + ".css";
242
+ if (srcPath.startsWith("/")) {
243
+ const absPath = normalizePath(resolve(viteRoot, srcPath.slice(1)));
244
+ if (islandCssFiles.has(absPath)) return absPath + ".css";
245
+ }
246
+ }
247
+ }
248
+ },
249
+ load: {
250
+ filter: { id: /^(\0virtual:void-islands-(renderer|client)|\/@void-island-wrap\/)|\.(tsx|jsx)\.css$/ },
251
+ handler(id) {
252
+ if (id === "\0" + ISLANDS_RENDERER_ID) {
253
+ if (!pageScan) return "export function renderIslandPage() { throw new Error('No pages found'); }";
254
+ const mdPlugin = resolvedConfig?.plugins?.find((p) => p.name === "void-md");
255
+ const mdScriptIds = new Set(mdPlugin?.api?.getClientScripts?.()?.keys() ?? []);
256
+ const needsJS = computePagesNeedingClientJS$1();
257
+ return generateIslandRenderer(pageScan, pagesDir, isDev, islandCssMap, viteRoot, mdScriptIds, needsJS);
258
+ }
259
+ if (id === "\0" + ISLANDS_CLIENT_ENTRY_ID) {
260
+ if (!pageScan) return "";
261
+ return generateIslandClientEntry(islandManifest, islandCssFiles, isDev);
262
+ }
263
+ if (id.startsWith(WRAPPER_PREFIX)) {
264
+ const meta = wrapperMeta.get(id);
265
+ if (meta) return generateWrapperComponent(meta);
266
+ }
267
+ if (id.endsWith(".css") && !id.startsWith("\0")) {
268
+ const srcPath = id.slice(0, -4);
269
+ if (islandCssFiles.has(srcPath)) return extractCssImports(srcPath);
270
+ }
271
+ }
272
+ },
273
+ transform: {
274
+ filter: { id: /\.island\.(tsx|jsx)$/ },
275
+ handler(code, id) {
276
+ if (/import\s+\{[^}]*\buseForm\b/.test(code)) this.warn(`islands: useForm cannot be imported in island page '${id}'. Use useIslandForm instead.`);
277
+ const importAttrRe = /import\s+(\w+)\s+from\s+("[^"]+"|'[^']+')\s+with\s*\{\s*island\s*:\s*("[^"]+"|'[^']+')\s*\}/g;
278
+ const importerDir = dirname(id);
279
+ let transformed = code;
280
+ let match;
281
+ while ((match = importAttrRe.exec(code)) !== null) {
282
+ const name = match[1];
283
+ const specRaw = match[2];
284
+ const strategyRaw = match[3];
285
+ const spec = specRaw.slice(1, -1);
286
+ const strategy = strategyRaw.slice(1, -1);
287
+ const absPath = resolveSpecifier(spec, importerDir, COMPONENT_EXTENSIONS);
288
+ if (absPath) {
289
+ const islandId = normalizePath(relative(root, absPath)).replace(/\.[^.]+$/, "");
290
+ islandManifest.set(islandId, {
291
+ componentPath: absPath,
292
+ islandId,
293
+ hydrate: strategy
294
+ });
295
+ }
296
+ const islandId = absPath ? normalizePath(relative(root, absPath)).replace(/\.[^.]+$/, "") : spec;
297
+ const wrapperUrl = WRAPPER_PREFIX + "island_" + wrapperId++ + ".tsx";
298
+ wrapperMeta.set(wrapperUrl, {
299
+ src: absPath || spec,
300
+ islandId,
301
+ hydrate: strategy
302
+ });
303
+ const replacement = `import ${name} from ${JSON.stringify(wrapperUrl)}`;
304
+ transformed = transformed.replace(match[0], replacement);
305
+ }
306
+ if (transformed !== code) return {
307
+ code: transformed,
308
+ map: null
309
+ };
310
+ }
311
+ },
312
+ config(_, env) {
313
+ if (!existsSync(pagesDir)) return;
314
+ if (env.command !== "serve" && needsIslandClientBundle(pagesDir, /\.island\.(tsx|jsx)$/, false)) return { build: {
315
+ manifest: true,
316
+ rollupOptions: { input: { "islands-client": ISLANDS_CLIENT_ENTRY_ID } }
317
+ } };
318
+ }
319
+ }];
320
+ }
321
+ /**
322
+ * Generate a virtual TSX wrapper component.
323
+ * vite-plugin-solid compiles the JSX for both SSR and client.
324
+ */
325
+ function generateWrapperComponent(meta) {
326
+ return `import _Cmp from ${JSON.stringify(meta.src)};
327
+ export default function _IslandWrap(props) {
328
+ return <div data-island="${meta.islandId}" data-props={JSON.stringify(props)} data-hydrate="${meta.hydrate}"><_Cmp {...props} /></div>;
329
+ }
330
+ `;
331
+ }
332
+ function generateIslandRenderer(scan, pagesDir, isDev, islandCssMap, viteRoot, mdScriptIds, pagesNeedingClientJS) {
333
+ let cssMapCode = "";
334
+ if (isDev && islandCssMap.size > 0) {
335
+ const cssMapObj = {};
336
+ for (const [compId, paths] of islandCssMap) cssMapObj[compId] = paths.map((p) => "/" + normalizePath(relative(viteRoot, p)) + ".css");
337
+ cssMapCode = `const __cssPaths = ${JSON.stringify(cssMapObj)};`;
338
+ }
339
+ const mdScriptIdsCode = `const __mdClientScriptIds = new Set(${JSON.stringify([...mdScriptIds])});`;
340
+ const needsJSCode = `const __pagesNeedingClientJS = new Set(${JSON.stringify([...pagesNeedingClientJS])});`;
341
+ return `
342
+ import { renderToStringAsync, generateHydrationScript } from "solid-js/web";
343
+ import { createComponent } from "solid-js";
344
+ import { SharedContext, ErrorsContext } from "@void/solid";
345
+ import { renderHeadToString, renderHtmlAttrs, renderBodyAttrs } from "void/pages-head";
346
+
347
+ ${generateComponentManifest(scan, pagesDir)}
348
+ ${cssMapCode}
349
+ ${mdScriptIdsCode}
350
+ ${needsJSCode}
351
+
352
+ function escapeAttr(s) {
353
+ return String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
354
+ }
355
+
356
+ export async function renderIslandPage(pageObj, assetTags) {
357
+ const PageComponent = (await components[pageObj.component]()).default;
358
+ const layoutIds = layoutTree[pageObj.component] || [];
359
+ const layoutComponents = await Promise.all(
360
+ layoutIds.map(async (id) => (await components[id]()).default)
361
+ );
362
+
363
+ function ServerApp() {
364
+ return createComponent(SharedContext.Provider, {
365
+ value: pageObj.shared || {},
366
+ get children() {
367
+ return createComponent(ErrorsContext.Provider, {
368
+ value: pageObj.errors || {},
369
+ get children() {
370
+ // Build layout chain inside providers so contexts are available.
371
+ // No RouterContext — islands have no Void Router.
372
+ let element = createComponent(PageComponent, pageObj.props);
373
+ for (let i = layoutComponents.length - 1; i >= 0; i--) {
374
+ const Layout = layoutComponents[i];
375
+ const child = element;
376
+ element = createComponent(Layout, { get children() { return child; } });
377
+ }
378
+ return element;
379
+ }
380
+ });
381
+ }
382
+ });
383
+ }
384
+
385
+ const html = await renderToStringAsync(() => createComponent(ServerApp, {}));
386
+
387
+ const __mdScriptAttr = __mdClientScriptIds.has(pageObj.component) ? \` data-md-script="\${escapeAttr(pageObj.component)}"\` : "";
388
+ const headHtml = pageObj.head ? renderHeadToString(pageObj.head) : "";
389
+ const htmlAttrs = pageObj.head ? renderHtmlAttrs(pageObj.head) : "";
390
+ const bodyAttrs = pageObj.head ? renderBodyAttrs(pageObj.head) : "";
391
+
392
+ return \`<!doctype html>
393
+ <html\${htmlAttrs}>
394
+ <head>\${headHtml}\${typeof __cssPaths !== "undefined" ? (__cssPaths[pageObj.component] || []).map(url => '<link rel="stylesheet" href="' + url + '">').join("\\n") : ""}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}\${__pagesNeedingClientJS.has(pageObj.component) ? generateHydrationScript() : ""}</head>
395
+ <body\${bodyAttrs}>
396
+ <div id="app"\${__mdScriptAttr}>\${html}</div>
397
+ \${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""}
398
+ </body>
399
+ </html>\`;
400
+ }
401
+ `;
402
+ }
403
+ function generateIslandClientEntry(manifest, cssFiles, isDev) {
404
+ const entries = [...manifest.values()];
405
+ const uniqueIslands = /* @__PURE__ */ new Map();
406
+ for (const entry of entries) uniqueIslands.set(entry.islandId, entry.componentPath);
407
+ const lines = [];
408
+ lines.push("import { initIslands } from \"void/pages-client\";");
409
+ if (!isDev) {
410
+ const cssImportRe = /^\s*import\b[^"']*["']([^"']+\.(?:css|scss|sass|less|styl|stylus|pcss|postcss))["']/gm;
411
+ for (const file of cssFiles) {
412
+ const content = readFileSync(file, "utf-8");
413
+ cssImportRe.lastIndex = 0;
414
+ let match;
415
+ while ((match = cssImportRe.exec(content)) !== null) lines.push(rewriteCssImportForVirtualModule(match[0], match[1], file));
416
+ }
417
+ }
418
+ lines.push("const islands = {");
419
+ for (const [id, path] of uniqueIslands) lines.push(` ${JSON.stringify(id)}: () => import(${JSON.stringify(path)}),`);
420
+ lines.push("};");
421
+ lines.push(`
422
+ async function mountIsland(el, mod, props) {
423
+ const { render } = await import("solid-js/web");
424
+ const { createComponent } = await import("solid-js");
425
+ const Component = mod.default || mod;
426
+ el.textContent = "";
427
+ render(() => createComponent(Component, props), el);
428
+ el.setAttribute("data-hydrated", "true");
429
+ }
430
+
431
+ initIslands(islands, mountIsland);
432
+ `);
433
+ return lines.join("\n");
434
+ }
435
+ //#endregion
436
+ //#region src/plugin-pages.ts
437
+ const RENDERER_ID = "virtual:void-pages-renderer";
438
+ const CLIENT_ENTRY_ID = "virtual:void-pages-client";
439
+ /** Check if the pages directory has any non-island page files (.tsx/.jsx without .island.). */
440
+ function hasNonIslandPages(dir) {
441
+ try {
442
+ for (const entry of readdirSync(dir, {
443
+ withFileTypes: true,
444
+ recursive: true
445
+ })) {
446
+ if (!entry.isFile()) continue;
447
+ const name = entry.name;
448
+ if (name.startsWith("_") || name.startsWith("layout.")) continue;
449
+ if (/\.(tsx|jsx)$/.test(name) && !name.includes(".island.")) return true;
450
+ }
451
+ } catch {}
452
+ return false;
453
+ }
454
+ function pagesPlugin(pagesDir, options) {
455
+ let pageScan = null;
456
+ let viteConfig;
457
+ const root = dirname(pagesDir);
458
+ return {
459
+ name: "void-solid:pages",
460
+ async buildStart() {
461
+ if (existsSync(pagesDir)) pageScan = await scanPages(root);
462
+ },
463
+ resolveId: {
464
+ filter: { id: /^virtual:void-pages-(renderer|client)$/ },
465
+ handler(id) {
466
+ return "\0" + id;
467
+ }
468
+ },
469
+ load: {
470
+ filter: { id: /^\0virtual:void-pages-(renderer|client)$/ },
471
+ handler(id) {
472
+ if (id === "\0" + RENDERER_ID) {
473
+ if (!pageScan) return "export function renderPage() { throw new Error('No pages found'); }";
474
+ return generateRendererModule(pageScan, pagesDir);
475
+ }
476
+ if (id === "\0" + CLIENT_ENTRY_ID) {
477
+ if (!pageScan) return "";
478
+ return generateClientEntry(pageScan, pagesDir, options?.viewTransitions, options?.prefetch, resolveStaticPageDataBuildOptions(root, { publicDir: viteConfig?.publicDir }));
479
+ }
480
+ }
481
+ },
482
+ configResolved(config) {
483
+ viteConfig = config;
484
+ },
485
+ config(_, env) {
486
+ if (!existsSync(pagesDir)) return;
487
+ if (env.command === "serve") return { optimizeDeps: {
488
+ exclude: ["@void/solid"],
489
+ include: [
490
+ "solid-js",
491
+ "solid-js/web",
492
+ "solid-js/store"
493
+ ]
494
+ } };
495
+ if (!hasNonIslandPages(pagesDir)) return;
496
+ return { build: {
497
+ manifest: true,
498
+ rollupOptions: { input: { "pages-client": CLIENT_ENTRY_ID } }
499
+ } };
500
+ }
501
+ };
502
+ }
503
+ function generateRendererModule(scan, pagesDir) {
504
+ return `
505
+ import { renderToStringAsync, generateHydrationScript } from "solid-js/web";
506
+ import { createComponent } from "solid-js";
507
+ import { SharedContext, ErrorsContext, RouterContext, NavigationContext } from "@void/solid";
508
+ import { createSsrRouter, idleNavigationState } from "void/pages-client";
509
+ import { renderHeadToString, renderHtmlAttrs, renderBodyAttrs } from "void/pages-head";
510
+ import { serializePageData } from "void/pages-server";
511
+
512
+ ${generateComponentManifest(scan, pagesDir)}
513
+
514
+ export async function renderPage(pageObj, assetTags) {
515
+ const PageComponent = (await components[pageObj.component]()).default;
516
+ const layoutIds = layoutTree[pageObj.component] || [];
517
+ const layoutComponents = await Promise.all(
518
+ layoutIds.map(async (id) => (await components[id]()).default)
519
+ );
520
+
521
+ function ServerApp() {
522
+ return createComponent(SharedContext.Provider, {
523
+ value: pageObj.shared || {},
524
+ get children() {
525
+ return createComponent(ErrorsContext.Provider, {
526
+ value: pageObj.errors || {},
527
+ get children() {
528
+ return createComponent(RouterContext.Provider, {
529
+ value: createSsrRouter(pageObj.url || "/"),
530
+ get children() {
531
+ return createComponent(NavigationContext.Provider, {
532
+ value: () => idleNavigationState(),
533
+ get children() {
534
+ // Build layout chain inside providers so contexts are available
535
+ let element = createComponent(PageComponent, pageObj.props);
536
+ for (let i = layoutComponents.length - 1; i >= 0; i--) {
537
+ const Layout = layoutComponents[i];
538
+ const child = element;
539
+ element = createComponent(Layout, { get children() { return child; } });
540
+ }
541
+ return element;
542
+ }
543
+ });
544
+ }
545
+ });
546
+ }
547
+ });
548
+ }
549
+ });
550
+ }
551
+
552
+ // Use createComponent to match the client's hydration tree structure
553
+ const html = await renderToStringAsync(() => createComponent(ServerApp, {}));
554
+
555
+ const pageData = serializePageData(pageObj);
556
+ const headHtml = pageObj.head ? renderHeadToString(pageObj.head) : "";
557
+ const htmlAttrs = pageObj.head ? renderHtmlAttrs(pageObj.head) : "";
558
+ const bodyAttrs = pageObj.head ? renderBodyAttrs(pageObj.head) : "";
559
+
560
+ return \`<!doctype html>
561
+ <html\${htmlAttrs}>
562
+ <head>\${headHtml}\${assetTags.css}\${assetTags.preloads}\${generateHydrationScript()}</head>
563
+ <body\${bodyAttrs}>
564
+ <script id="__VOID_PAGE_DATA__" type="application/json">\${pageData}<\/script>
565
+ <div id="app">\${html}</div>
566
+ \${assetTags.body}
567
+ </body>
568
+ </html>\`;
569
+ }
570
+ `;
571
+ }
572
+ function generateClientEntry(scan, pagesDir, viewTransitions, prefetch, staticPageData) {
573
+ return `
574
+ import { createSignal, createComponent, batch } from "solid-js";
575
+ import { hydrate } from "solid-js/web";
576
+ import { SharedContext, ErrorsContext, RouterContext, NavigationContext, setActionRouter } from "@void/solid";
577
+ import { createRouterFacade, createVoidRouter, idleNavigationState } from "void/pages-client";
578
+ import { parseCacheFor } from "void/pages-prefetch";
579
+
580
+ ${generateComponentManifest(scan, pagesDir)}
581
+
582
+ const [component, setComponent] = createSignal(null);
583
+ const [pageProps, setPageProps] = createSignal({});
584
+ const [layouts, setLayouts] = createSignal([]);
585
+ const [shared, setShared] = createSignal({});
586
+ const [errors, setErrors] = createSignal({});
587
+ const [routeUrl, setRouteUrl] = createSignal(window.location.pathname + window.location.search + window.location.hash);
588
+ const [navigation, setNavigation] = createSignal(idleNavigationState());
589
+
590
+ const { router, initialPageData, initialComponent, initialLayouts, start } =
591
+ await createVoidRouter({
592
+ adapter: {
593
+ createDeferred: () => ({ value: null, loading: true, error: null }),
594
+ resolveDeferred(ref, value) { return { value, loading: false, error: null }; },
595
+ rejectDeferred(ref, error) { return { value: null, loading: false, error: new Error(error) }; },
596
+ isLoading: (ref) => ref.loading,
597
+ applyUpdate(pageData, comp, layoutComps) {
598
+ batch(() => {
599
+ setPageProps(pageData.props);
600
+ setComponent(() => comp);
601
+ setLayouts(layoutComps);
602
+ setShared((prev) => ({ ...prev, ...(pageData.shared || {}) }));
603
+ setErrors(pageData.errors || {});
604
+ });
605
+ },
606
+ onDeferredUpdate(props) {
607
+ batch(() => { setPageProps({ ...props }); });
608
+ },
609
+ },
610
+ components, layoutTree, routeMeta, matchRoute,
611
+ staticPageData: ${!!staticPageData?.enabled},
612
+ staticPageDataFastPath: ${!!staticPageData?.fastPath},
613
+ viewTransitions: ${!!viewTransitions},
614
+ prefetchHoverDelay: ${prefetch?.hoverDelay ?? 75},
615
+ prefetchDefaultCacheFor: parseCacheFor(${JSON.stringify(prefetch?.cacheFor ?? "30s")}),
616
+ onRouteChange(url) {
617
+ setRouteUrl(url);
618
+ },
619
+ onNavigationChange(next) {
620
+ setNavigation(next);
621
+ },
622
+ });
623
+
624
+ const reactiveRouter = createRouterFacade(router, () => routeUrl());
625
+
626
+ setActionRouter(reactiveRouter);
627
+
628
+ batch(() => {
629
+ setComponent(() => initialComponent);
630
+ setPageProps(initialPageData.props);
631
+ setLayouts(initialLayouts);
632
+ setShared(initialPageData.shared || {});
633
+ setErrors(initialPageData.errors || {});
634
+ });
635
+
636
+ function App() {
637
+ return createComponent(SharedContext.Provider, {
638
+ get value() { return shared(); },
639
+ get children() {
640
+ return createComponent(ErrorsContext.Provider, {
641
+ value: errors,
642
+ get children() {
643
+ return createComponent(RouterContext.Provider, {
644
+ value: reactiveRouter,
645
+ get children() {
646
+ return createComponent(NavigationContext.Provider, {
647
+ value: navigation,
648
+ get children() {
649
+ const Comp = component();
650
+ if (!Comp) return null;
651
+ let element = createComponent(Comp, pageProps());
652
+ const layoutList = layouts();
653
+ for (let i = layoutList.length - 1; i >= 0; i--) {
654
+ const Layout = layoutList[i];
655
+ const child = element;
656
+ element = createComponent(Layout, { get children() { return child; } });
657
+ }
658
+ return element;
659
+ }
660
+ });
661
+ }
662
+ });
663
+ }
664
+ });
665
+ }
666
+ });
667
+ }
668
+
669
+ const appEl = document.getElementById("app");
670
+ hydrate(() => createComponent(App, {}), appEl);
671
+ appEl.setAttribute("data-hydrated", "true");
672
+ export { reactiveRouter as router };
673
+ start();
674
+ `;
675
+ }
676
+ //#endregion
677
+ //#region src/plugin.ts
678
+ function configPlugin() {
679
+ return {
680
+ name: "void:solid:config",
681
+ config() {
682
+ return {
683
+ optimizeDeps: { exclude: ["@void/solid"] },
684
+ ssr: {
685
+ noExternal: ["@void/solid"],
686
+ optimizeDeps: { exclude: ["@void/solid"] }
687
+ }
688
+ };
689
+ }
690
+ };
691
+ }
692
+ function voidSolid(options) {
693
+ const pagesDir = join(process.cwd(), "pages");
694
+ return [
695
+ configPlugin(),
696
+ solid({
697
+ ssr: true,
698
+ ...options?.solid
699
+ }),
700
+ pagesPlugin(pagesDir, {
701
+ viewTransitions: options?.viewTransitions,
702
+ prefetch: options?.prefetch
703
+ }),
704
+ ...islandsPlugin(pagesDir)
705
+ ];
706
+ }
707
+ //#endregion
708
+ export { voidSolid };