@fluixi/start 0.1.0-alpha.72 → 0.1.0-alpha.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/adapter.cjs +748 -0
  2. package/dist/adapter.mjs +717 -0
  3. package/dist/adapters/entry.cjs +122 -0
  4. package/dist/adapters/entry.mjs +95 -0
  5. package/dist/adapters/platforms.cjs +311 -0
  6. package/dist/adapters/platforms.mjs +284 -0
  7. package/dist/api-RH6E5UTH.mjs +114 -0
  8. package/dist/api.cjs +145 -0
  9. package/dist/api.mjs +116 -0
  10. package/dist/commands/api-23MJFSYL.mjs +17 -0
  11. package/dist/commands/api-4IYNQRKG.mjs +16 -0
  12. package/dist/commands/api-RH6E5UTH.mjs +114 -0
  13. package/dist/commands/build.cjs +870 -0
  14. package/dist/commands/build.mjs +710 -0
  15. package/dist/commands/chunk-NS5GR2GX.mjs +115 -0
  16. package/dist/commands/chunk-OCPCK4ZJ.mjs +117 -0
  17. package/dist/commands/dev.cjs +663 -0
  18. package/dist/commands/dev.mjs +505 -0
  19. package/dist/commands/index.cjs +1138 -0
  20. package/dist/commands/index.mjs +975 -0
  21. package/dist/commands/prerender.cjs +402 -0
  22. package/dist/commands/prerender.mjs +375 -0
  23. package/dist/commands/start.cjs +461 -0
  24. package/dist/commands/start.mjs +426 -0
  25. package/dist/config.cjs +144 -0
  26. package/dist/config.mjs +108 -0
  27. package/dist/di.cjs +200 -0
  28. package/dist/di.mjs +169 -0
  29. package/dist/document.cjs +115 -0
  30. package/dist/document.mjs +86 -0
  31. package/dist/generated-api.cjs +43 -0
  32. package/dist/generated-api.mjs +18 -0
  33. package/dist/generated-server-fns.cjs +43 -0
  34. package/dist/generated-server-fns.mjs +18 -0
  35. package/dist/handler-core.cjs +211 -0
  36. package/dist/handler-core.mjs +185 -0
  37. package/dist/handler.cjs +181 -0
  38. package/dist/handler.mjs +150 -0
  39. package/dist/head.cjs +25 -0
  40. package/dist/head.mjs +4 -0
  41. package/dist/image.cjs +146 -0
  42. package/dist/image.mjs +120 -0
  43. package/dist/index.cjs +1036 -0
  44. package/dist/index.mjs +968 -0
  45. package/dist/interceptors.cjs +71 -0
  46. package/dist/interceptors.mjs +42 -0
  47. package/dist/internal.cjs +388 -0
  48. package/dist/internal.d.ts.map +1 -1
  49. package/dist/internal.js +6 -2
  50. package/dist/internal.mjs +218 -0
  51. package/dist/middleware.cjs +58 -0
  52. package/dist/middleware.mjs +31 -0
  53. package/dist/preload.cjs +42 -0
  54. package/dist/preload.mjs +18 -0
  55. package/dist/router.cjs +25 -0
  56. package/dist/router.mjs +4 -0
  57. package/dist/server-fn-setup.cjs +46 -0
  58. package/dist/server-fn-setup.mjs +22 -0
  59. package/dist/server-fn.cjs +109 -0
  60. package/dist/server-fn.mjs +79 -0
  61. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  62. package/dist/ui.cjs +123 -0
  63. package/dist/ui.mjs +93 -0
  64. package/package.json +45 -25
@@ -0,0 +1,748 @@
1
+ /*! @fluixi/start v0.1.0-alpha.74 | (c) 2026 Ibrahima Touré and Fluixi contributors | MIT */
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/adapter.ts
22
+ var adapter_exports = {};
23
+ __export(adapter_exports, {
24
+ cloudflareAdapter: () => cloudflareAdapter,
25
+ createProdHandler: () => createProdHandler,
26
+ netlifyAdapter: () => netlifyAdapter,
27
+ nodeAdapter: () => nodeAdapter,
28
+ readTemplate: () => readTemplate,
29
+ ssrBuildOptions: () => ssrBuildOptions,
30
+ vercelAdapter: () => vercelAdapter,
31
+ webAdapter: () => webAdapter
32
+ });
33
+ module.exports = __toCommonJS(adapter_exports);
34
+ var import_promises3 = require("node:fs/promises");
35
+ var import_node_fs3 = require("node:fs");
36
+ var import_node_path4 = require("node:path");
37
+ var import_node_url = require("node:url");
38
+ var import_node_module = require("node:module");
39
+
40
+ // src/config.ts
41
+ var import_node_path = require("node:path");
42
+ function resolveConfig(config = {}) {
43
+ const root = (0, import_node_path.resolve)(config.root ?? process.cwd());
44
+ return {
45
+ root,
46
+ ssr: config.ssr ?? true,
47
+ port: config.port ?? 3e3,
48
+ serverEntry: config.serverEntry ?? "src/entry-server.ts",
49
+ clientEntry: config.clientEntry ?? "src/entry-client.ts",
50
+ template: config.template ?? "index.html",
51
+ mountId: config.mountId ?? "root",
52
+ routesDir: config.routesDir ?? "src/routes",
53
+ apiDir: config.apiDir ?? "src/api",
54
+ middleware: config.middleware ?? "src/middleware.ts",
55
+ ssrNoExternal: config.ssrNoExternal ?? [],
56
+ resolve: config.resolve ?? [],
57
+ adapter: config.adapter,
58
+ i18n: resolveI18n(config.i18n),
59
+ prerender: resolvePrerender(config.prerender)
60
+ };
61
+ }
62
+ function resolvePrerender(prerender) {
63
+ if (!prerender) return false;
64
+ const opts = typeof prerender === "object" ? prerender : {};
65
+ return {
66
+ routes: opts.routes?.length ? opts.routes : ["/"],
67
+ crawl: opts.crawl ?? true
68
+ };
69
+ }
70
+ function resolveI18n(i18n) {
71
+ if (i18n === false) return false;
72
+ const opts = typeof i18n === "object" ? i18n : {};
73
+ return {
74
+ dir: opts.dir ?? "src/i18n",
75
+ defaultLocale: opts.defaultLocale,
76
+ locales: opts.locales
77
+ };
78
+ }
79
+
80
+ // src/handler.ts
81
+ var import_node_http = require("node:http");
82
+ var import_promises = require("node:fs/promises");
83
+ var import_node_fs = require("node:fs");
84
+ var import_node_stream = require("node:stream");
85
+ var import_node_path2 = require("node:path");
86
+ function streamDocument(head, body, tail) {
87
+ const enc = new TextEncoder();
88
+ const stream = new ReadableStream({
89
+ async start(controller) {
90
+ try {
91
+ controller.enqueue(enc.encode(head));
92
+ const reader = body.getReader();
93
+ for (; ; ) {
94
+ const { done, value } = await reader.read();
95
+ if (done) break;
96
+ controller.enqueue(value);
97
+ }
98
+ controller.enqueue(enc.encode(tail));
99
+ controller.close();
100
+ } catch (err) {
101
+ controller.error(err);
102
+ }
103
+ }
104
+ });
105
+ return new Response(stream, {
106
+ status: 200,
107
+ headers: { "content-type": "text/html; charset=utf-8" }
108
+ });
109
+ }
110
+ function createRequestHandler(render) {
111
+ return async (request) => {
112
+ const url = new URL(request.url);
113
+ try {
114
+ const html = await render(url.pathname + url.search, request);
115
+ return new Response(html, {
116
+ status: 200,
117
+ headers: { "content-type": "text/html; charset=utf-8" }
118
+ });
119
+ } catch (e) {
120
+ return new Response(String(e?.stack || e), {
121
+ status: 500,
122
+ headers: { "content-type": "text/plain; charset=utf-8" }
123
+ });
124
+ }
125
+ };
126
+ }
127
+ function nodeToRequest(req) {
128
+ const host = req.headers.host ?? "localhost";
129
+ const url = `http://${host}${req.url ?? "/"}`;
130
+ const headers = new Headers();
131
+ for (const [k, v] of Object.entries(req.headers)) {
132
+ if (Array.isArray(v)) v.forEach((x) => headers.append(k, x));
133
+ else if (v != null) headers.set(k, v);
134
+ }
135
+ const method = req.method ?? "GET";
136
+ const init = { method, headers };
137
+ if (method !== "GET" && method !== "HEAD") {
138
+ init.body = req;
139
+ init.duplex = "half";
140
+ }
141
+ return new Request(url, init);
142
+ }
143
+ async function sendResponse(res, response) {
144
+ res.statusCode = response.status;
145
+ response.headers.forEach((value, key) => res.setHeader(key, value));
146
+ const body = response.body;
147
+ if (!body) {
148
+ res.end(await response.text().catch(() => ""));
149
+ return;
150
+ }
151
+ const reader = body.getReader();
152
+ try {
153
+ for (; ; ) {
154
+ const { done, value } = await reader.read();
155
+ if (done) break;
156
+ res.write(value);
157
+ }
158
+ } finally {
159
+ res.end();
160
+ }
161
+ }
162
+ function toNodeHandler(handler) {
163
+ return async (req, res) => {
164
+ const response = await handler(nodeToRequest(req));
165
+ await sendResponse(res, response);
166
+ };
167
+ }
168
+ function serveNode(handler, opts = {}) {
169
+ const port = opts.port ?? 3e3;
170
+ const node = toNodeHandler(handler);
171
+ const server = (0, import_node_http.createServer)((req, res) => {
172
+ node(req, res).catch((e) => {
173
+ res.statusCode = 500;
174
+ res.end(String(e?.stack || e));
175
+ });
176
+ });
177
+ server.listen(
178
+ port,
179
+ () => opts.onListen ? opts.onListen(port) : console.log(` fluixi → http://localhost:${port}`)
180
+ );
181
+ return server;
182
+ }
183
+ var MIME = {
184
+ ".js": "text/javascript",
185
+ ".mjs": "text/javascript",
186
+ ".css": "text/css",
187
+ ".html": "text/html",
188
+ ".json": "application/json",
189
+ ".svg": "image/svg+xml",
190
+ ".png": "image/png",
191
+ ".jpg": "image/jpeg",
192
+ ".jpeg": "image/jpeg",
193
+ ".webp": "image/webp",
194
+ ".ico": "image/x-icon",
195
+ ".woff": "font/woff",
196
+ ".woff2": "font/woff2",
197
+ ".map": "application/json"
198
+ };
199
+ function withStaticFiles(handler, dir) {
200
+ return async (request) => {
201
+ const { pathname } = new URL(request.url);
202
+ if (pathname !== "/" && (0, import_node_path2.extname)(pathname)) {
203
+ const file = (0, import_node_path2.join)(dir, decodeURIComponent(pathname));
204
+ try {
205
+ const s = await (0, import_promises.stat)(file);
206
+ if (s.isFile()) {
207
+ const body = import_node_stream.Readable.toWeb((0, import_node_fs.createReadStream)(file));
208
+ return new Response(body, {
209
+ headers: {
210
+ "content-type": MIME[(0, import_node_path2.extname)(file).toLowerCase()] ?? "application/octet-stream",
211
+ "content-length": String(s.size)
212
+ }
213
+ });
214
+ }
215
+ } catch {
216
+ }
217
+ }
218
+ return handler(request);
219
+ };
220
+ }
221
+
222
+ // src/document.ts
223
+ var import_head = require("@fluixi/head");
224
+ function injectApp(template, appHtml, mountId = "root") {
225
+ const mount = new RegExp(`<div id=["']${mountId}["']\\s*>\\s*</div>`);
226
+ if (mount.test(template)) {
227
+ return template.replace(mount, `<div id="${mountId}">${appHtml}</div>`);
228
+ }
229
+ if (template.includes("<!--ssr-outlet-->")) {
230
+ return template.replace("<!--ssr-outlet-->", appHtml);
231
+ }
232
+ return template.replace("</body>", `<div id="${mountId}">${appHtml}</div></body>`);
233
+ }
234
+ function splitTemplate(template, mountId = "root") {
235
+ const mount = new RegExp(`<div id=["']${mountId}["']\\s*>\\s*</div>`);
236
+ const m = template.match(mount);
237
+ if (m && m.index !== void 0) {
238
+ return {
239
+ head: template.slice(0, m.index) + `<div id="${mountId}">`,
240
+ tail: `</div>` + template.slice(m.index + m[0].length)
241
+ };
242
+ }
243
+ const outlet = template.indexOf("<!--ssr-outlet-->");
244
+ if (outlet !== -1) {
245
+ return {
246
+ head: template.slice(0, outlet),
247
+ tail: template.slice(outlet + "<!--ssr-outlet-->".length)
248
+ };
249
+ }
250
+ const body = template.indexOf("</body>");
251
+ if (body !== -1) {
252
+ return {
253
+ head: template.slice(0, body) + `<div id="${mountId}">`,
254
+ tail: `</div>` + template.slice(body)
255
+ };
256
+ }
257
+ return { head: template, tail: "" };
258
+ }
259
+ function injectPreload(template, files) {
260
+ const tags = files.filter((file) => !template.includes(file)).map(
261
+ (file) => file.endsWith(".css") ? `<link rel="stylesheet" href="${file}">` : (
262
+ // `modulepreload` also fetches the chunk's own static imports.
263
+ `<link rel="modulepreload" href="${file}">`
264
+ )
265
+ );
266
+ if (tags.length === 0) return template;
267
+ const head = template.indexOf("</head>");
268
+ if (head === -1) return template;
269
+ return template.slice(0, head) + tags.join("") + template.slice(head);
270
+ }
271
+ function setHtmlAttr(html, name, value) {
272
+ const existing = new RegExp(`(<html\\b[^>]*?)\\s${name}="[^"]*"`, "i");
273
+ if (existing.test(html)) return html.replace(existing, `$1 ${name}="${value}"`);
274
+ return html.replace(/<html\b/i, `<html ${name}="${value}"`);
275
+ }
276
+ function injectAppAndHead(template, rendered, mountId = "root") {
277
+ const { head, body } = (0, import_head.extractHeadMarker)(rendered);
278
+ let html = injectApp(template, body, mountId);
279
+ if (head) {
280
+ if (head.headHtml) {
281
+ if (/<title[\s>]/i.test(head.headHtml)) html = html.replace(/<title>[\s\S]*?<\/title>/i, "");
282
+ html = html.replace("</head>", `${head.headHtml}</head>`);
283
+ }
284
+ for (const [k, v] of Object.entries(head.htmlAttrs)) html = setHtmlAttr(html, k, v);
285
+ }
286
+ return html;
287
+ }
288
+ function guardHandler(handler, onError) {
289
+ return async (request) => {
290
+ try {
291
+ return await handler(request);
292
+ } catch (e) {
293
+ onError?.(e);
294
+ return new Response(String(e?.stack || e), {
295
+ status: 500,
296
+ headers: { "content-type": "text/plain; charset=utf-8" }
297
+ });
298
+ }
299
+ };
300
+ }
301
+
302
+ // src/middleware.ts
303
+ function normalizeMiddleware(mod) {
304
+ const def = mod?.default ?? mod;
305
+ if (def == null) return [];
306
+ if (Array.isArray(def)) return def.filter((m) => typeof m === "function");
307
+ return typeof def === "function" ? [def] : [];
308
+ }
309
+ function composeMiddleware(middlewares, core) {
310
+ if (middlewares.length === 0) return core;
311
+ return (request) => {
312
+ let lastCalled = -1;
313
+ const dispatch = (i) => {
314
+ if (i <= lastCalled) {
315
+ return Promise.reject(new Error("middleware called next() more than once"));
316
+ }
317
+ lastCalled = i;
318
+ const mw = middlewares[i];
319
+ if (!mw) return Promise.resolve(core(request));
320
+ return Promise.resolve(mw(request, () => dispatch(i + 1)));
321
+ };
322
+ return dispatch(0);
323
+ };
324
+ }
325
+
326
+ // src/handler-core.ts
327
+ function createHandlerFrom({ template, mod, cfg, middleware, preload }) {
328
+ const withPreload = (html, pathname) => preload ? injectPreload(html, preload(pathname)) : html;
329
+ let core;
330
+ if (!cfg.ssr) {
331
+ core = createRequestHandler(async (url) => withPreload(template, url.split("?")[0]));
332
+ } else if (typeof mod.renderStream === "function") {
333
+ core = async (request) => {
334
+ const url = new URL(request.url);
335
+ const { head, tail } = splitTemplate(withPreload(template, url.pathname), cfg.mountId);
336
+ const body = await mod.renderStream(url.pathname + url.search, request);
337
+ return streamDocument(head, body, tail);
338
+ };
339
+ } else {
340
+ const render = mod.render ?? mod.default;
341
+ core = createRequestHandler(
342
+ async (url, request) => (
343
+ // `url` here is `pathname + search`; matching only ever wants the path.
344
+ injectAppAndHead(withPreload(template, url.split("?")[0]), await render(url, request), cfg.mountId)
345
+ )
346
+ );
347
+ }
348
+ if (typeof mod.handleServerFn === "function" && typeof mod.isServerFnRequest === "function") {
349
+ const render = core;
350
+ core = async (request) => mod.isServerFnRequest(request) ? mod.handleServerFn(request) : render(request);
351
+ }
352
+ if (typeof mod.handleApiRequest === "function" && typeof mod.isApiRequest === "function") {
353
+ const next = core;
354
+ core = async (request) => mod.isApiRequest(request) ? mod.handleApiRequest(request) : next(request);
355
+ }
356
+ if (!middleware) return guardHandler(core);
357
+ return guardHandler(composeMiddleware(normalizeMiddleware(middleware), core));
358
+ }
359
+
360
+ // src/preload.ts
361
+ var import_router = require("@fluixi/core/router");
362
+ function createPreloader(assets) {
363
+ const patterns = Object.keys(assets ?? {});
364
+ if (!patterns.length) return () => [];
365
+ const routes = patterns.map((path) => ({ path, meta: { path } }));
366
+ return (pathname) => {
367
+ const matched = (0, import_router.matchRoutes)(routes, pathname)?.matched;
368
+ const leaf = matched?.[matched.length - 1];
369
+ const pattern = leaf?.route.meta?.path;
370
+ return pattern ? assets[pattern] ?? [] : [];
371
+ };
372
+ }
373
+
374
+ // src/adapters/platforms.ts
375
+ var import_promises2 = require("node:fs/promises");
376
+ var import_node_fs2 = require("node:fs");
377
+ var import_node_path3 = require("node:path");
378
+
379
+ // src/adapters/entry.ts
380
+ function preamble({ serverEntry, middleware, template, ssr, mountId, routeAssets }) {
381
+ return [
382
+ `import { createHandlerFrom } from '@fluixi/start/handler-core';`,
383
+ `import { createPreloader } from '@fluixi/start/preload';`,
384
+ `import * as server from ${JSON.stringify(serverEntry)};`,
385
+ middleware ? `import * as middleware from ${JSON.stringify(middleware)};` : "",
386
+ ``,
387
+ `const template = ${JSON.stringify(template)};`,
388
+ // Inlined for the same reason as the template: this runs as an uploaded file, with
389
+ // no dist/server beside it to read.
390
+ `const routeAssets = ${JSON.stringify(routeAssets)};`,
391
+ `const handler = createHandlerFrom({`,
392
+ ` template,`,
393
+ ` mod: server,`,
394
+ ` cfg: { ssr: ${ssr}, mountId: ${JSON.stringify(mountId)} },`,
395
+ ` preload: createPreloader(routeAssets),`,
396
+ middleware ? ` middleware,` : "",
397
+ `});`
398
+ ].filter(Boolean).join("\n");
399
+ }
400
+ function cloudflareEntry(source) {
401
+ return `${preamble(source)}
402
+
403
+ const prerendered = new Set(${JSON.stringify(source.prerendered)});
404
+
405
+ export default {
406
+ async fetch(request, env, ctx) {
407
+ // Static first, but only for what is static. ASSETS answers "/" with index.html
408
+ // whether that is a prerendered page or the shell, so asking about every path
409
+ // costs an SSR app its home page. Extension means a file, prerendered means a
410
+ // page, the rest is the handler's — the rule \`withStaticFiles\` already uses.
411
+ const { pathname } = new URL(request.url);
412
+ if (env && env.ASSETS && (prerendered.has(pathname) || /\\.[^/]+$/.test(pathname))) {
413
+ const asset = await env.ASSETS.fetch(request.clone());
414
+ if (asset.status !== 404) return asset;
415
+ }
416
+ return handler(request, { env, ctx });
417
+ },
418
+ };
419
+ `;
420
+ }
421
+ function netlifyEntry(source) {
422
+ return `${preamble(source)}
423
+
424
+ export default async (request, context) => handler(request, { context });
425
+
426
+ export const config = { path: '/*', preferStatic: true };
427
+ `;
428
+ }
429
+ function vercelEntry(source) {
430
+ return `${preamble(source)}
431
+
432
+ export default async (req, res) => {
433
+ const proto = req.headers['x-forwarded-proto'] || 'https';
434
+ const host = req.headers['x-forwarded-host'] || req.headers.host;
435
+
436
+ const headers = new Headers();
437
+ for (const [name, value] of Object.entries(req.headers)) {
438
+ if (Array.isArray(value)) for (const one of value) headers.append(name, one);
439
+ else if (value !== undefined) headers.set(name, value);
440
+ }
441
+
442
+ // A body has to be read off the stream before it can be handed to Request; only
443
+ // GET and HEAD are guaranteed not to have one.
444
+ let body;
445
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
446
+ const chunks = [];
447
+ for await (const chunk of req) chunks.push(chunk);
448
+ if (chunks.length) body = new Blob(chunks);
449
+ }
450
+
451
+ const response = await handler(
452
+ new Request(new URL(req.url, \`\${proto}://\${host}\`), { method: req.method, headers, body }),
453
+ );
454
+
455
+ res.statusCode = response.status;
456
+ // set-cookie is the one header that legitimately repeats; folding it into one line
457
+ // breaks the cookies.
458
+ for (const [name, value] of response.headers) {
459
+ if (name.toLowerCase() !== 'set-cookie') res.setHeader(name, value);
460
+ }
461
+ const cookies = response.headers.getSetCookie?.() ?? [];
462
+ if (cookies.length) res.setHeader('set-cookie', cookies);
463
+
464
+ if (response.body) for await (const chunk of response.body) res.write(chunk);
465
+ res.end();
466
+ };
467
+ `;
468
+ }
469
+
470
+ // src/adapters/platforms.ts
471
+ async function entrySource(ctx, from, prerendered) {
472
+ const template = await readTemplate(ctx.clientDir, ctx.serverDir);
473
+ const assetFile = (0, import_node_path3.join)(ctx.serverDir, "route-assets.json");
474
+ const routeAssets = (0, import_node_fs2.existsSync)(assetFile) ? JSON.parse(await (0, import_promises2.readFile)(assetFile, "utf-8")) : {};
475
+ const middleware = (0, import_node_path3.join)(ctx.serverDir, "middleware.js");
476
+ const rel = (file) => {
477
+ const path = (0, import_node_path3.join)(ctx.serverDir, file).replace(/\\/g, "/");
478
+ return path.startsWith("/") ? path : `./${path}`;
479
+ };
480
+ return {
481
+ serverEntry: rel("entry-server.js"),
482
+ middleware: (0, import_node_fs2.existsSync)(middleware) ? rel("middleware.js") : null,
483
+ template,
484
+ ssr: ctx.cfg.ssr,
485
+ mountId: ctx.cfg.mountId,
486
+ prerendered,
487
+ routeAssets
488
+ };
489
+ }
490
+ function indexIsPage(template, mountId) {
491
+ const mount = new RegExp(`<([a-z-]+)[^>]*\\sid=["']${mountId}["'][^>]*>`, "i").exec(template);
492
+ if (!mount) return false;
493
+ return !template.slice(mount.index + mount[0].length).trimStart().startsWith("</");
494
+ }
495
+ function skipWhenStatic(ctx, name) {
496
+ if (ctx.hasServer) return false;
497
+ console.log(` fluixi: no server entry — ${name} gets the static output alone.`);
498
+ return true;
499
+ }
500
+ async function appendRedirect(clientDir, rule) {
501
+ const file = (0, import_node_path3.join)(clientDir, "_redirects");
502
+ const existing = await (0, import_promises2.readFile)(file, "utf-8").catch(() => "");
503
+ if (existing.includes(rule)) return;
504
+ const separator = existing && !existing.endsWith("\n") ? "\n" : "";
505
+ await (0, import_promises2.writeFile)(file, `${existing}${separator}${rule}
506
+ `);
507
+ }
508
+ var SPA_FALLBACK = "/* /index.html 200";
509
+ var CF_MAX_RULES = 100;
510
+ async function prerenderedRoutes(dir, mountId) {
511
+ const out = [];
512
+ const walk = async (current) => {
513
+ for (const entry of await (0, import_promises2.readdir)(current, { withFileTypes: true })) {
514
+ const path = (0, import_node_path3.join)(current, entry.name);
515
+ if (entry.isDirectory()) {
516
+ if (entry.name === "assets" || entry.name.startsWith(".")) continue;
517
+ await walk(path);
518
+ } else if (entry.name.endsWith(".html")) {
519
+ const rel = (0, import_node_path3.relative)(dir, path).replace(/\\/g, "/").replace(/index\.html$/, "").replace(/\.html$/, "");
520
+ out.push("/" + rel.replace(/\/$/, ""));
521
+ }
522
+ }
523
+ };
524
+ await walk(dir);
525
+ const index = await (0, import_promises2.readFile)((0, import_node_path3.join)(dir, "index.html"), "utf-8").catch(() => "");
526
+ const root = indexIsPage(index, mountId);
527
+ return out.filter((r) => r !== "/" || root).sort();
528
+ }
529
+ var cloudflareAdapter = {
530
+ name: "cloudflare",
531
+ bundle: "inline",
532
+ serve({ handler }) {
533
+ return { fetch: handler };
534
+ },
535
+ async build(ctx) {
536
+ if (skipWhenStatic(ctx, "cloudflare")) return;
537
+ const out = (0, import_node_path3.join)(ctx.clientDir, "_worker.js");
538
+ const prerendered = await prerenderedRoutes(ctx.clientDir, ctx.cfg.mountId);
539
+ await ctx.bundleEntry(cloudflareEntry(await entrySource(ctx, out, prerendered)), out);
540
+ const base = ["/assets/*", "/_worker.js"];
541
+ const room = CF_MAX_RULES - base.length;
542
+ const exclude = [...base, ...prerendered.slice(0, room)];
543
+ if (prerendered.length > room) {
544
+ console.warn(
545
+ ` fluixi: ${prerendered.length} prerendered routes exceed Cloudflare's ${CF_MAX_RULES}-rule limit for _routes.json; ${prerendered.length - room} will invoke the worker to serve a static file.`
546
+ );
547
+ }
548
+ await (0, import_promises2.writeFile)(
549
+ (0, import_node_path3.join)(ctx.clientDir, "_routes.json"),
550
+ JSON.stringify({ version: 1, include: ["/*"], exclude }, null, 2) + "\n"
551
+ );
552
+ }
553
+ };
554
+ var netlifyAdapter = {
555
+ name: "netlify",
556
+ bundle: "inline",
557
+ serve({ handler }) {
558
+ return { fetch: handler };
559
+ },
560
+ async build(ctx) {
561
+ if (skipWhenStatic(ctx, "netlify")) return appendRedirect(ctx.clientDir, SPA_FALLBACK);
562
+ const dir = (0, import_node_path3.join)(ctx.root, ".netlify", "functions-internal");
563
+ await (0, import_promises2.mkdir)(dir, { recursive: true });
564
+ const out = (0, import_node_path3.join)(dir, "fluixi-server.mjs");
565
+ const prerendered = await prerenderedRoutes(ctx.clientDir, ctx.cfg.mountId);
566
+ await ctx.bundleEntry(netlifyEntry(await entrySource(ctx, out, prerendered)), out);
567
+ await (0, import_promises2.writeFile)(
568
+ (0, import_node_path3.join)(dir, "fluixi-server.json"),
569
+ JSON.stringify({ config: { path: "/*", preferStatic: true }, version: 1 }, null, 2) + "\n"
570
+ );
571
+ if (!prerendered.includes("/")) {
572
+ await appendRedirect(ctx.clientDir, "/ /.netlify/functions/fluixi-server 200!");
573
+ }
574
+ }
575
+ };
576
+ var vercelAdapter = {
577
+ name: "vercel",
578
+ bundle: "inline",
579
+ serve({ handler }) {
580
+ return { fetch: handler };
581
+ },
582
+ async build(ctx) {
583
+ const output = (0, import_node_path3.join)(ctx.root, ".vercel", "output");
584
+ await (0, import_promises2.mkdir)(output, { recursive: true });
585
+ await (0, import_promises2.cp)(ctx.clientDir, (0, import_node_path3.join)(output, "static"), { recursive: true });
586
+ if (skipWhenStatic(ctx, "vercel")) {
587
+ await (0, import_promises2.writeFile)(
588
+ (0, import_node_path3.join)(output, "config.json"),
589
+ JSON.stringify(
590
+ {
591
+ version: 3,
592
+ // The filesystem phase alone answers 404 for a client route, since nothing
593
+ // is on disk at that path; the catch-all is what makes it a SPA.
594
+ routes: [{ handle: "filesystem" }, { src: "/(.*)", dest: "/index.html" }]
595
+ },
596
+ null,
597
+ 2
598
+ ) + "\n"
599
+ );
600
+ return;
601
+ }
602
+ const fn = (0, import_node_path3.join)(output, "functions", "index.func");
603
+ await (0, import_promises2.mkdir)(fn, { recursive: true });
604
+ const out = (0, import_node_path3.join)(fn, "index.mjs");
605
+ const prerendered = await prerenderedRoutes(ctx.clientDir, ctx.cfg.mountId);
606
+ await ctx.bundleEntry(vercelEntry(await entrySource(ctx, out, prerendered)), out);
607
+ await (0, import_promises2.writeFile)(
608
+ (0, import_node_path3.join)(fn, ".vc-config.json"),
609
+ JSON.stringify(
610
+ { runtime: "nodejs20.x", handler: "index.mjs", launcherType: "Nodejs", shouldAddHelpers: false },
611
+ null,
612
+ 2
613
+ ) + "\n"
614
+ );
615
+ await (0, import_promises2.writeFile)(
616
+ (0, import_node_path3.join)(output, "config.json"),
617
+ JSON.stringify(
618
+ {
619
+ version: 3,
620
+ routes: [
621
+ // The filesystem holds a shell at `/index.html`, so `/` has to be claimed
622
+ // before that phase or it is served unrendered. Skipped when `/` really is
623
+ // a prerendered page, which the filesystem should answer.
624
+ ...prerendered.includes("/") ? [] : [{ src: "/", dest: "/index" }],
625
+ // A prerendered page or an asset wins; only a miss reaches the function.
626
+ { handle: "filesystem" },
627
+ { src: "/(.*)", dest: "/index" }
628
+ ]
629
+ },
630
+ null,
631
+ 2
632
+ ) + "\n"
633
+ );
634
+ }
635
+ };
636
+
637
+ // src/adapter.ts
638
+ async function createProdHandler(config = {}) {
639
+ const cfg = resolveConfig(config);
640
+ const clientDir = (0, import_node_path4.resolve)(cfg.root, "dist/client");
641
+ const template = await readTemplate(clientDir, (0, import_node_path4.resolve)(cfg.root, "dist/server"));
642
+ const serverEntry = (0, import_node_path4.resolve)(cfg.root, "dist/server", "entry-server.js");
643
+ const mod = (0, import_node_fs3.existsSync)(serverEntry) ? await import(
644
+ /* @vite-ignore */
645
+ (0, import_node_url.pathToFileURL)(serverEntry).href
646
+ ) : {};
647
+ const mwFile = (0, import_node_path4.resolve)(cfg.root, "dist/server", "middleware.js");
648
+ const middleware = (0, import_node_fs3.existsSync)(mwFile) ? await import(
649
+ /* @vite-ignore */
650
+ (0, import_node_url.pathToFileURL)(mwFile).href
651
+ ) : void 0;
652
+ return createHandlerFrom({ template, mod, cfg, middleware, preload: await loadPreloader(cfg) });
653
+ }
654
+ async function readTemplate(clientDir, serverDir) {
655
+ const stashed = (0, import_node_path4.join)(serverDir, "template.html");
656
+ return (0, import_promises3.readFile)((0, import_node_fs3.existsSync)(stashed) ? stashed : (0, import_node_path4.join)(clientDir, "index.html"), "utf-8");
657
+ }
658
+ async function loadPreloader(cfg) {
659
+ const file = (0, import_node_path4.resolve)(cfg.root, "dist/server", "route-assets.json");
660
+ if (!(0, import_node_fs3.existsSync)(file)) return void 0;
661
+ try {
662
+ return createPreloader(JSON.parse(await (0, import_promises3.readFile)(file, "utf-8")));
663
+ } catch {
664
+ return void 0;
665
+ }
666
+ }
667
+ var nodeAdapter = {
668
+ name: "node",
669
+ // A Node server runs from the app directory, so node_modules is right there: keep the
670
+ // framework as imports instead of copying it into the bundle.
671
+ bundle: "external",
672
+ async serve({ handler, cfg, clientDir }) {
673
+ serveNode(withStaticFiles(handler, clientDir), {
674
+ port: cfg.port,
675
+ onListen: (p) => console.log(` fluixi start (node) → http://localhost:${p}`)
676
+ });
677
+ }
678
+ };
679
+ var webAdapter = {
680
+ name: "web",
681
+ // An edge/serverless runtime uploads a file, not an install: nothing may be left to
682
+ // resolve at runtime, so everything goes in the bundle.
683
+ bundle: "inline",
684
+ serve({ handler }) {
685
+ return { fetch: handler };
686
+ }
687
+ };
688
+ var GENERATED_SUBPATHS = /* @__PURE__ */ new Set(["./routes", "./server-fns", "./api-routes"]);
689
+ function ssrBuildOptions(cfg) {
690
+ const noExternal = cfg.ssrNoExternal.length ? cfg.ssrNoExternal : void 0;
691
+ const mode = cfg.adapter?.bundle;
692
+ if (mode === "inline") return { noExternal: true };
693
+ if (mode !== "external") return { noExternal };
694
+ const external = frameworkDeps(cfg.root).filter((name) => !cfg.ssrNoExternal.includes(name)).flatMap((name) => withSubpaths(cfg.root, name));
695
+ if (!external.length) {
696
+ console.warn(
697
+ ` fluixi: adapter "${cfg.adapter?.name}" builds an externalized server, but no fluixi or @fluixi/* dependency was found in ${(0, import_node_path4.join)(cfg.root, "package.json")} — bundling everything.`
698
+ );
699
+ }
700
+ return { noExternal, external: external.length ? external : void 0 };
701
+ }
702
+ function frameworkDeps(root) {
703
+ const pkg = readPackage((0, import_node_path4.join)(root, "package.json"));
704
+ if (!pkg) return [];
705
+ const declared = { ...pkg.dependencies, ...pkg.peerDependencies, ...pkg.optionalDependencies };
706
+ return Object.keys(declared).filter((id) => id === "@fluixi/core" || id.startsWith("@fluixi/"));
707
+ }
708
+ function withSubpaths(root, name) {
709
+ const exports2 = resolvePackage(root, name)?.exports;
710
+ if (!exports2 || typeof exports2 !== "object") return [name];
711
+ const ids = [name];
712
+ for (const key of Object.keys(exports2)) {
713
+ if (!key.startsWith("./") || key.includes("*")) continue;
714
+ if (key === "./package.json" || GENERATED_SUBPATHS.has(key)) continue;
715
+ ids.push(`${name}/${key.slice(2)}`);
716
+ }
717
+ return ids;
718
+ }
719
+ function resolvePackage(root, name) {
720
+ try {
721
+ return readPackage((0, import_node_module.createRequire)((0, import_node_path4.join)(root, "index.js")).resolve(`${name}/package.json`));
722
+ } catch {
723
+ }
724
+ for (let dir = root; ; dir = (0, import_node_path4.dirname)(dir)) {
725
+ const pkg = readPackage((0, import_node_path4.join)(dir, "node_modules", name, "package.json"));
726
+ if (pkg) return pkg;
727
+ if ((0, import_node_path4.dirname)(dir) === dir) return void 0;
728
+ }
729
+ }
730
+ function readPackage(file) {
731
+ if (!(0, import_node_fs3.existsSync)(file)) return void 0;
732
+ try {
733
+ return JSON.parse((0, import_node_fs3.readFileSync)(file, "utf-8"));
734
+ } catch {
735
+ return void 0;
736
+ }
737
+ }
738
+ // Annotate the CommonJS export names for ESM import in node:
739
+ 0 && (module.exports = {
740
+ cloudflareAdapter,
741
+ createProdHandler,
742
+ netlifyAdapter,
743
+ nodeAdapter,
744
+ readTemplate,
745
+ ssrBuildOptions,
746
+ vercelAdapter,
747
+ webAdapter
748
+ });