exta2 0.0.1-beta.29

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/index.js ADDED
@@ -0,0 +1,851 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+ var dist_exports = {};
29
+ __export(dist_exports, {
30
+ compilePage: () => compilePage,
31
+ exta: () => exta
32
+ });
33
+ module.exports = __toCommonJS(dist_exports);
34
+ var import_node_fs = require("node:fs");
35
+ var import_node_url = require("node:url");
36
+ var import_node_util = require("node:util");
37
+ var import_node_path = require("node:path");
38
+ var import_node_fs2 = require("node:fs");
39
+ var import_node_path2 = require("node:path");
40
+ var import_node_fs3 = require("node:fs");
41
+ var import_node_path3 = require("node:path");
42
+ var import_node_path4 = require("node:path");
43
+ var import_promises = require("node:fs/promises");
44
+ var import_node_path5 = require("node:path");
45
+ var import_esbuild = require("esbuild");
46
+ var import_promises2 = require("node:fs/promises");
47
+ var import_node_path6 = require("node:path");
48
+ var import_oxc_parser = __toESM(require("oxc-parser"), 1);
49
+ var import_colors = require("colors");
50
+ var import_node_path7 = require("node:path");
51
+ var import_node_module = require("node:module");
52
+ var import_node_path8 = require("node:path");
53
+ var fs = __toESM(require("node:fs"), 1);
54
+ var path = __toESM(require("node:path"), 1);
55
+ var import_node_fs4 = require("node:fs");
56
+ var import_node_path9 = require("node:path");
57
+ var import_vite = require("vite");
58
+ var import_node_fs5 = require("node:fs");
59
+ var import_node_path10 = require("node:path");
60
+ var import_node_perf_hooks = require("node:perf_hooks");
61
+ var import_node_url2 = require("node:url");
62
+ var import_server = require("react-dom/server");
63
+ var import_react = __toESM(require("react"), 1);
64
+ var import_react2 = __toESM(require("react"), 1);
65
+ var import_react3 = __toESM(require("react"), 1);
66
+ var import_node_readline = __toESM(require("node:readline"), 1);
67
+ var import_colors2 = require("colors");
68
+ var import_node_fs6 = require("node:fs");
69
+ var import_node_path11 = require("node:path");
70
+ var import_node_perf_hooks2 = require("node:perf_hooks");
71
+ var import_node_url3 = require("node:url");
72
+ var cache;
73
+ function getIndexHtml() {
74
+ if (cache)
75
+ return cache;
76
+ let path2 = (0, import_node_path3.join)(process.cwd(), "index.html");
77
+ return (0, import_node_fs3.existsSync)(path2) ? (cache = (0, import_node_fs3.readFileSync)(path2, "utf-8"), cache) : `<!doctype html>
78
+ <html lang="en">
79
+ <head>
80
+ <meta charset="UTF-8" />
81
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
82
+ %head%
83
+ </head>
84
+ <body>
85
+ %body%
86
+ </body>
87
+ </html>`;
88
+ }
89
+ function initialize(dist = (0, import_node_path2.join)(process.cwd(), ".exta"), pages) {
90
+ (0, import_node_fs2.mkdirSync)(dist, { recursive: true }), (0, import_node_fs2.writeFileSync)(
91
+ (0, import_node_path2.join)(dist, "index.html"),
92
+ getIndexHtml().replace("%body%", '<div id="_app"></div>').replace("%head%", '<script src="/.exta/client.js" type="module"><\/script>')
93
+ ), (0, import_node_fs2.writeFileSync)((0, import_node_path2.join)(dist, "client.js"), 'import "$exta-client";'), (0, import_node_fs2.writeFileSync)(
94
+ (0, import_node_path2.join)(dist, "manifest.js"),
95
+ `export default {${Object.keys(pages).map(
96
+ (page) => ` "${page}": () => import("./${(0, import_node_path2.relative)(dist, pages[page].client).replace(/\\/g, "/")}"),
97
+ `
98
+ ).join(`
99
+ `)}}`
100
+ );
101
+ }
102
+ var PAGE_STATIC_DATA_FUNCTION = "getStaticProps", PAGE_STATIC_PARAMS_FUNCTION = "getStaticParams";
103
+ process.env.EXTA_DEBUG && (global.COMPILER_LOG_LEVEL = "debug");
104
+ function getLogLevel(logLevel) {
105
+ if (!logLevel)
106
+ return 2;
107
+ switch (logLevel.toUpperCase()) {
108
+ case "ERROR":
109
+ return 0;
110
+ case "WARN":
111
+ return 1;
112
+ case "INFO":
113
+ return 2;
114
+ case "DEBUG":
115
+ return 3;
116
+ default:
117
+ return 2;
118
+ }
119
+ }
120
+ var currentLogLevel = getLogLevel(
121
+ global.COMPILER_LOG_LEVEL
122
+ );
123
+ function error(message) {
124
+ currentLogLevel >= 0 && console.error(`[ERROR]: ${message}`.red);
125
+ }
126
+ function warn(message) {
127
+ currentLogLevel >= 1 && console.warn(`[WARN]: ${message}`.yellow);
128
+ }
129
+ function debug(message) {
130
+ currentLogLevel >= 3 && console.debug(`[DEBUG]: ${message}`.cyan);
131
+ }
132
+ function changeExtension(filename, to) {
133
+ let { dir, name } = (0, import_node_path7.parse)(filename);
134
+ return (0, import_node_path7.join)(dir, name + to).replace(/\\/g, "/");
135
+ }
136
+ async function getExports(code, filename = "@virtual.ts") {
137
+ let result = await import_oxc_parser.default.parseAsync(filename, code, {
138
+ lang: "tsx",
139
+ sourceType: "module"
140
+ });
141
+ if (result.errors && process.argv.includes("--show-parser-error"))
142
+ for (let parserError of result.errors)
143
+ error(
144
+ `[exta/compiler:oxc-parser] ${parserError.message}
145
+ - ${JSON.stringify(parserError).red}`
146
+ );
147
+ let exports = [];
148
+ for (let _export_entries of result.module.staticExports)
149
+ for (let [, _export] of Object.entries(_export_entries.entries))
150
+ _export.exportName.name ? exports.push(_export.exportName.name) : _export.exportName ? exports.push("__default") : warn(`Cannot resolve export name - ${code.slice(_export.start, _export.end)}`);
151
+ return exports;
152
+ }
153
+ async function generateOriginalServerFile(filename, hasFunction, cwd = process.cwd()) {
154
+ (0, import_node_path6.isAbsolute)(filename) || (filename = (0, import_node_path6.join)(cwd, filename));
155
+ let basePageDirectory = (0, import_node_path6.join)(cwd, "pages"), relativeFilename = (0, import_node_path6.relative)(basePageDirectory, filename), outdirectory = (0, import_node_path6.join)(cwd, ".exta"), funcList = [];
156
+ hasFunction.params && funcList.push(PAGE_STATIC_PARAMS_FUNCTION), hasFunction.data && funcList.push(PAGE_STATIC_DATA_FUNCTION);
157
+ let outServerFile = (0, import_node_path6.join)(
158
+ outdirectory,
159
+ "intermediate",
160
+ "server",
161
+ changeExtension(relativeFilename, ".ts")
162
+ ), outClientFile = (0, import_node_path6.join)(
163
+ outdirectory,
164
+ "intermediate",
165
+ "client",
166
+ changeExtension(relativeFilename, ".tsx")
167
+ );
168
+ return await (0, import_promises2.mkdir)((0, import_node_path6.dirname)(outServerFile), { recursive: true }), await (0, import_promises2.mkdir)((0, import_node_path6.dirname)(outClientFile), { recursive: true }), await (0, import_promises2.writeFile)(
169
+ outServerFile,
170
+ `export { ${funcList.join(", ")} } from "${(0, import_node_path6.relative)((0, import_node_path6.dirname)(outServerFile), filename).replace(/\\/g, "/")}";`
171
+ ), await (0, import_promises2.writeFile)(
172
+ outClientFile,
173
+ hasFunction.default ? `export { default as _page } from "${(0, import_node_path6.relative)((0, import_node_path6.dirname)(outClientFile), filename).replace(/\\/g, "/")}";export const __exta_page=true;` : "export const _page = () => null;export const __exta_page=true;"
174
+ ), {
175
+ outServerFile,
176
+ outClientFile
177
+ };
178
+ }
179
+ var BUILTIN_MODULES = import_node_module.builtinModules.concat(import_node_module.builtinModules.map((m) => `node:${m}`));
180
+ function sideEffectPlugin(options) {
181
+ return {
182
+ name: "exta/esbuild-sideeffect-plugin",
183
+ setup(build2) {
184
+ build2.onResolve({ filter: /.*/ }, async (args) => {
185
+ if (BUILTIN_MODULES.includes(args.path) || options?.ignoreSideEffects && (options?.preserveSideEffects || []).includes(args.path))
186
+ return {
187
+ sideEffects: false,
188
+ path: args.path,
189
+ external: true
190
+ };
191
+ });
192
+ }
193
+ };
194
+ }
195
+ function vmPlugin() {
196
+ return {
197
+ name: "my-virtual-module-plugin",
198
+ setup(build2) {
199
+ build2.onResolve({ filter: /^\$exta-router$/ }, (args) => ({ path: args.path, namespace: "virtual" })), build2.onLoad({ filter: /^\$exta-router$/, namespace: "virtual" }, () => ({
200
+ contents: "module.exports = {};",
201
+ loader: "js"
202
+ }));
203
+ }
204
+ };
205
+ }
206
+ function onlyReact(extensions = [".css", ".scss", ".sass", ".less"], isServerSide = false, options) {
207
+ return options.assetsExtensions && extensions.push(...options.assetsExtensions), {
208
+ name: "exta/esbuild-react-plugin",
209
+ setup(build2) {
210
+ build2.onResolve(
211
+ {
212
+ filter: new RegExp(
213
+ `\\.(${extensions.map((ext) => ext.replace(".", "")).join("|")})$`
214
+ )
215
+ },
216
+ (args) => isServerSide ? {
217
+ path: args.path,
218
+ namespace: "exta:ignore"
219
+ } : args.path.startsWith(".") ? {
220
+ path: (0, import_node_path8.join)(args.resolveDir, args.path),
221
+ external: true
222
+ } : {
223
+ path: args.path,
224
+ external: true
225
+ }
226
+ ), build2.onLoad({ filter: /.*/, namespace: "exta:ignore" }, () => ({
227
+ contents: "",
228
+ loader: "js"
229
+ }));
230
+ }
231
+ };
232
+ }
233
+ async function compilePage(filename, options = {}, ignoreAssets) {
234
+ let cwd = process.cwd(), source = await (0, import_promises.readFile)(filename, "utf-8"), exports = await getExports(source, filename), hasStaticPropsFunction = exports.includes(PAGE_STATIC_DATA_FUNCTION), hasStaticParamsFunction = exports.includes(PAGE_STATIC_PARAMS_FUNCTION), intermeddiateFiles = await generateOriginalServerFile(filename, {
235
+ data: hasStaticPropsFunction,
236
+ params: hasStaticParamsFunction,
237
+ default: exports.includes("__default")
238
+ }), basePageDirectory = (0, import_node_path5.join)(cwd, "pages"), relativeFilename = (0, import_node_path5.relative)(basePageDirectory, filename), outdirectory = options.outdir ?? (0, import_node_path5.join)(cwd, ".exta"), outfiles = {
239
+ client: (0, import_node_path5.join)(outdirectory, "client", changeExtension(relativeFilename, ".js")),
240
+ server: (0, import_node_path5.join)(outdirectory, "server", changeExtension(relativeFilename, ".mjs"))
241
+ };
242
+ return await (0, import_esbuild.build)({
243
+ entryPoints: [intermeddiateFiles.outClientFile],
244
+ outfile: outfiles.client,
245
+ packages: "external",
246
+ sourcemap: "inline",
247
+ format: "esm",
248
+ platform: "browser",
249
+ treeShaking: true,
250
+ bundle: true,
251
+ jsx: "automatic",
252
+ ignoreAnnotations: true,
253
+ plugins: [sideEffectPlugin(options), onlyReact(void 0, ignoreAssets, options)]
254
+ }), await (0, import_esbuild.build)({
255
+ entryPoints: [intermeddiateFiles.outServerFile],
256
+ outfile: outfiles.server,
257
+ packages: "external",
258
+ format: "esm",
259
+ platform: "node",
260
+ treeShaking: true,
261
+ bundle: true,
262
+ ignoreAnnotations: true,
263
+ plugins: [sideEffectPlugin(options), onlyReact(void 0, true, options), vmPlugin()]
264
+ }), { outfiles };
265
+ }
266
+ function scanDirectory(directoryPath, fileList = []) {
267
+ return fs.readdirSync(directoryPath).forEach((item) => {
268
+ let fullPath = path.join(directoryPath, item);
269
+ fs.statSync(fullPath).isDirectory() ? scanDirectory(fullPath, fileList) : fileList.push(fullPath);
270
+ }), fileList;
271
+ }
272
+ function prettyURL(path2) {
273
+ return path2 === "." && (path2 = ""), path2.startsWith("/") || (path2 = `/${path2}`), path2.endsWith("/") && (path2 = path2.slice(0, -1)), path2;
274
+ }
275
+ async function compilePages(compileOptions, ignoreAssets = false) {
276
+ let baseDir = (0, import_node_path4.join)(process.cwd(), "pages"), pages = scanDirectory(baseDir), output = {};
277
+ for await (let page of pages) {
278
+ let pageName = (0, import_node_path4.parse)(page).name, name = prettyURL((0, import_node_path4.relative)(baseDir, page).replace(/\\/g, "/"));
279
+ pageName === "_layout" ? name = "[layout]" : pageName === "_error" && (name = "[error]"), output[name] = (await compilePage(page, compileOptions, ignoreAssets)).outfiles;
280
+ }
281
+ return output;
282
+ }
283
+ function matchUrlToRoute(url, routeResult) {
284
+ let { regex, params } = routeResult, match = regex.exec(url);
285
+ if (!match)
286
+ return null;
287
+ let result = {};
288
+ for (let i = 0; i < params.length; i++) {
289
+ let paramName = params[i], capturedValue = match[i + 1];
290
+ if (paramName.startsWith("..."))
291
+ throw new Error(
292
+ "[... file names are not supported due to static data generation issues."
293
+ );
294
+ result[paramName] = capturedValue;
295
+ }
296
+ return result;
297
+ }
298
+ function encodeJSON(input) {
299
+ if (typeof input == "string")
300
+ try {
301
+ return encodeURIComponent(input);
302
+ } catch {
303
+ return input;
304
+ }
305
+ else {
306
+ if (Array.isArray(input))
307
+ return input.map((item) => encodeJSON(item));
308
+ if (input && typeof input == "object") {
309
+ let result = {};
310
+ for (let [key, value] of Object.entries(input))
311
+ result[key] = encodeJSON(value);
312
+ return result;
313
+ }
314
+ }
315
+ return input;
316
+ }
317
+ function convertToRegex(path2) {
318
+ let params = [], processedPath = path2.replace(/\.[^/.]+$/, "");
319
+ processedPath.endsWith("/index") && (processedPath = processedPath.slice(0, -6));
320
+ let regexString = `^/${processedPath.split("/").filter((part) => part !== "").map((part) => {
321
+ if (part.startsWith("[...") && part.endsWith("]")) {
322
+ let paramName = part.slice(4, -1);
323
+ return params.push(paramName), "(.*)";
324
+ }
325
+ if (part.startsWith("[") && part.endsWith("]")) {
326
+ let paramName = part.slice(1, -1);
327
+ return params.push(paramName), "([^/]+)";
328
+ }
329
+ return part;
330
+ }).join("/")}/?$`;
331
+ return { regex: new RegExp(regexString), params };
332
+ }
333
+ var findPage = (url, _manifest_object) => {
334
+ let sortedManifest = [..._manifest_object].sort(
335
+ (a, b) => a.params.length - b.params.length
336
+ );
337
+ for (let route of sortedManifest)
338
+ if (route.regexp.test(decodeURIComponent(url)) && !route.path.startsWith("[") && !route.path.endsWith("]"))
339
+ return route;
340
+ return null;
341
+ };
342
+ var containerStyle = {
343
+ display: "flex",
344
+ justifyContent: "center",
345
+ alignItems: "center",
346
+ width: "100%",
347
+ height: "100vh",
348
+ textAlign: "center",
349
+ flexDirection: "column"
350
+ }, defaultProps = {
351
+ status: 404,
352
+ message: "Page not found"
353
+ }, DefaultError = ({ status, message } = defaultProps) => (status = status ?? defaultProps.status, message = message ?? defaultProps.message, import_react2.default.createElement("div", { style: containerStyle }, [
354
+ import_react2.default.createElement("h1", { key: "status" }, String(status)),
355
+ import_react2.default.createElement("p", { key: "message" }, message)
356
+ ]));
357
+ var DefaultLayout = ({ children }) => import_react3.default.createElement(import_react3.default.Fragment, null, children);
358
+ function replaceParamsInRoute(route, params) {
359
+ let result = route, paramRegex = /\[([^\]]+)\]/g;
360
+ return result = result.replace(paramRegex, (match, paramName) => params[paramName] || match), result = result.replace(/\.[^/.]+$/, ""), result = result.replace(/\/index$/, "") || "/", result;
361
+ }
362
+ var stream = process.stdout, defaultSpinner = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"].map(
363
+ (item) => item.cyan
364
+ ), Spinner = class {
365
+ tick;
366
+ spinner;
367
+ message;
368
+ processor;
369
+ constructor(opts = {}) {
370
+ this.tick = opts.tick || 50, this.spinner = opts.spinner || defaultSpinner, this.message = opts.message || "";
371
+ }
372
+ clearLine() {
373
+ return import_node_readline.default.clearLine(stream, 0), import_node_readline.default.cursorTo(stream, 0), this;
374
+ }
375
+ start() {
376
+ let index = 0;
377
+ return this.processor = setInterval(() => {
378
+ this.clearLine(), stream.write(`${this.spinner[index % this.spinner.length]} ${this.message}`), index += 1;
379
+ }, this.tick), this;
380
+ }
381
+ stop(message = "") {
382
+ return this.processor && (clearInterval(this.processor), this.clearLine(), stream.write(message)), this;
383
+ }
384
+ edit(message) {
385
+ return this.message = message, this;
386
+ }
387
+ };
388
+ function getUniqueArray(arr) {
389
+ return [...new Set(arr)];
390
+ }
391
+ var fileRegexp = /^[^/\\]+[\\/]/;
392
+ function parsePathname(url) {
393
+ let { pathname } = new URL(url, "http://localhost/");
394
+ return pathname.endsWith("/") && (pathname = pathname.slice(0, -1)), pathname;
395
+ }
396
+ function collectCssFiles(manifest, entry) {
397
+ let result = [], visited = /* @__PURE__ */ new Set();
398
+ function recurse(key) {
399
+ if (visited.has(key))
400
+ return;
401
+ visited.add(key);
402
+ let chunk = manifest[key];
403
+ if (chunk && (chunk.css && result.push(...chunk.css), chunk.imports))
404
+ for (let imported of chunk.imports)
405
+ recurse(imported);
406
+ }
407
+ return recurse(entry), result;
408
+ }
409
+ function collectJavaScriptFiles(manifest, entry) {
410
+ let result = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
411
+ function recurse(key) {
412
+ if (visited.has(key))
413
+ return;
414
+ visited.add(key);
415
+ let chunk = manifest[key];
416
+ if (chunk) {
417
+ if (chunk.imports)
418
+ for (let importedKey of chunk.imports)
419
+ recurse(importedKey);
420
+ result.add(chunk.file);
421
+ }
422
+ }
423
+ return recurse(entry), [...result];
424
+ }
425
+ var serverRendering = (children, { Layout, props, template, cssFiles, staticManifest, path: path2, scripts }) => {
426
+ global.__EXTA_SSR_DATA__ = {
427
+ pathname: path2,
428
+ params: props.params || {},
429
+ preload: [],
430
+ head: []
431
+ };
432
+ let component = import_react.default.createElement(children, {
433
+ ...props,
434
+ key: path2
435
+ }), string = (0, import_server.renderToString)(import_react.default.createElement(Layout, null, component)), insert = [];
436
+ for (let cssChunk of cssFiles)
437
+ insert.push(`<link rel="stylesheet" href="/${cssChunk}" />`);
438
+ for (let preloadFile of global.__EXTA_SSR_DATA__.preload)
439
+ insert.push(`<link rel="prefetch" href="${preloadFile}" />`);
440
+ for (let script of scripts)
441
+ insert.push(`<link rel="modulepreload" href="/${script}"></link>`);
442
+ insert.push(
443
+ `<script id="__STATIC_MANIFEST__" type="application/json">${JSON.stringify(staticManifest)}<\/script>`
444
+ );
445
+ for (let head of global.__EXTA_SSR_DATA__.head)
446
+ switch (head.type) {
447
+ case "html":
448
+ insert.push(head.data);
449
+ break;
450
+ case "preload-data-link": {
451
+ let page = parsePathname(head.data).replace(/\//g, "_") + ".json";
452
+ staticManifest[page] ? insert.push(
453
+ `<link rel="preload" href="/data/${staticManifest[page]}.json" as="fetch"></link>`
454
+ ) : insert.push(`<!--${head.data}-->`);
455
+ break;
456
+ }
457
+ default:
458
+ break;
459
+ }
460
+ return template = template.replace(/<head[^>]*>([\s\S]*?)<\/head>/, (match, inner) => `<head${match.match(/<head([^>]*)>/)?.[1] || ""}>${insert.join("")}
461
+ ${inner}</head>`), template.replace('<div id="_app"></div>', `<div id="_app">${string}</div>`);
462
+ };
463
+ async function createStaticHTML(pages, outdir, vite, template, manifest, staticManifest) {
464
+ let startTime = import_node_perf_hooks.performance.now(), spinner = new Spinner();
465
+ spinner.message = "Generating html files...", spinner.start();
466
+ let getLayout = async () => pages["[layout]"] ? (await vite.ssrLoadModule(pages["[layout]"].client))._page : DefaultLayout, getError = async () => pages["[error]"] ? (await vite.ssrLoadModule(pages["[error]"].client))._page : DefaultError, getClientComponent = async (path2) => (await vite.ssrLoadModule(path2))._page, ErrorComponent = await getError(), Layout = await getLayout(), layoutCompiledFile = `.exta/${pages["[layout]"].client.replace(fileRegexp, "")}`.replace(/\\/g, "/"), layoutCss = pages["[layout]"] ? collectCssFiles(manifest, layoutCompiledFile) : [], layoutScript = manifest[layoutCompiledFile]?.file;
467
+ (0, import_node_fs5.writeFileSync)((0, import_node_path10.join)(outdir, "data", "_empty.json"), "{}");
468
+ for (let pageName in pages) {
469
+ let page = pages[pageName], data = await import((0, import_node_url2.pathToFileURL)(page.server).href), compiledFile = `.exta/${page.client.replace(fileRegexp, "")}`.replace(
470
+ /\\/g,
471
+ "/"
472
+ ), cssFiles = collectCssFiles(manifest, compiledFile), script = collectJavaScriptFiles(manifest, compiledFile);
473
+ if (data[PAGE_STATIC_PARAMS_FUNCTION]) {
474
+ let paramsModule = await data[PAGE_STATIC_PARAMS_FUNCTION]();
475
+ if (!Array.isArray(paramsModule))
476
+ throw new Error(
477
+ `An error occurred while generating HTML file. - Static params function must return array. (in ${pageName})`
478
+ );
479
+ for (let params of paramsModule) {
480
+ let route = replaceParamsInRoute(pageName, params), outStaticPage = changeExtension((0, import_node_path10.join)(outdir, route), ".html"), staticDataPath = changeExtension(
481
+ (0, import_node_path10.join)(
482
+ outdir,
483
+ "data",
484
+ staticManifest[route.replace(/\//g, "_") + ".json"] || "_empty"
485
+ ),
486
+ ".json"
487
+ );
488
+ spinner.message = `Generating html files... - ${route}`;
489
+ let Client = await getClientComponent(page.client), ssrProps2 = {
490
+ Layout,
491
+ props: {
492
+ props: JSON.parse((0, import_node_fs5.readFileSync)(staticDataPath).toString()),
493
+ params: matchUrlToRoute(route, convertToRegex(pageName))
494
+ },
495
+ template,
496
+ cssFiles: getUniqueArray([...cssFiles, ...layoutCss]),
497
+ staticManifest,
498
+ path: route,
499
+ scripts: getUniqueArray([layoutScript, ...script])
500
+ };
501
+ (0, import_node_fs5.mkdirSync)((0, import_node_path10.dirname)(outStaticPage), { recursive: true }), (0, import_node_fs5.writeFileSync)(outStaticPage, serverRendering(Client, ssrProps2));
502
+ }
503
+ } else {
504
+ if (pageName.startsWith("[") && pageName.endsWith("]"))
505
+ continue;
506
+ let route = replaceParamsInRoute(pageName, {}), outStaticPage = (0, import_node_path10.join)(outdir, route) + "/index.html", staticDataPath = changeExtension(
507
+ (0, import_node_path10.join)(
508
+ outdir,
509
+ "data",
510
+ staticManifest[route.replace(/\//g, "_") + ".json"] || "_empty"
511
+ ),
512
+ ".json"
513
+ );
514
+ spinner.message = `Generating html files... - ${route}`;
515
+ let Client = await getClientComponent(page.client), ssrProps2 = {
516
+ Layout,
517
+ props: {
518
+ props: JSON.parse((0, import_node_fs5.readFileSync)(staticDataPath).toString()),
519
+ params: {}
520
+ },
521
+ template,
522
+ cssFiles: getUniqueArray([...cssFiles, ...layoutCss]),
523
+ staticManifest,
524
+ path: route,
525
+ scripts: getUniqueArray([layoutScript, ...script])
526
+ };
527
+ (0, import_node_fs5.mkdirSync)((0, import_node_path10.dirname)(outStaticPage), { recursive: true }), (0, import_node_fs5.writeFileSync)(outStaticPage, serverRendering(Client, ssrProps2));
528
+ }
529
+ }
530
+ let ssrProps = {
531
+ Layout,
532
+ props: {},
533
+ template,
534
+ cssFiles: [...layoutCss],
535
+ staticManifest,
536
+ path: ".exta/ssr:unknown",
537
+ scripts: []
538
+ };
539
+ (0, import_node_fs5.writeFileSync)((0, import_node_path10.join)(outdir, "404.html"), serverRendering(ErrorComponent, ssrProps)), spinner.stop(
540
+ `html files generated. (${((import_node_perf_hooks.performance.now() - startTime) / 1e3).toFixed(2)}s)`
541
+ );
542
+ }
543
+ function randomString16() {
544
+ let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
545
+ return Array.from(
546
+ { length: 16 },
547
+ () => chars[Math.floor(Math.random() * chars.length)]
548
+ ).join("");
549
+ }
550
+ async function createStaticProps(pages, outdir) {
551
+ let startTime = import_node_perf_hooks2.performance.now(), staticManifest = {}, spinner = new Spinner();
552
+ spinner.message = "Generating static data", spinner.start();
553
+ for (let pageName in pages) {
554
+ spinner.message = `Generating static data - collecting pages (${pageName})`;
555
+ let page = pages[pageName], data = await import((0, import_node_url3.pathToFileURL)(page.server).href);
556
+ if (data[PAGE_STATIC_PARAMS_FUNCTION]) {
557
+ let paramsModule = await data[PAGE_STATIC_PARAMS_FUNCTION]();
558
+ if (!Array.isArray(paramsModule))
559
+ throw new Error(
560
+ `An error occurred while building the page. - Static params function must return array. (in ${pageName})`
561
+ );
562
+ for (let params of paramsModule) {
563
+ let originalURL = replaceParamsInRoute(pageName, params), outfile = changeExtension(originalURL, ".json").replace(/\//g, "_"), random = randomString16(), outStaticPage = (0, import_node_path11.join)(outdir, "data", `${random}.json`);
564
+ if (spinner.message = `Generating static data - ${originalURL}`, (0, import_node_fs6.mkdirSync)((0, import_node_path11.dirname)(outStaticPage), { recursive: true }), staticManifest[outfile] = random, data[PAGE_STATIC_DATA_FUNCTION]) {
565
+ let staticProps = await data[PAGE_STATIC_DATA_FUNCTION]({ params });
566
+ (0, import_node_fs6.writeFileSync)(outStaticPage, JSON.stringify(staticProps));
567
+ } else
568
+ staticManifest[outfile] = null;
569
+ }
570
+ } else {
571
+ let originalURL = replaceParamsInRoute(pageName, {}), outfile = changeExtension(originalURL, ".json").replace(/\//g, "_"), random = randomString16(), outStaticPage = (0, import_node_path11.join)(outdir, "data", `${random}.json`);
572
+ if (spinner.message = `Generating static data - ${originalURL}`, staticManifest[outfile] = random, (0, import_node_fs6.mkdirSync)((0, import_node_path11.dirname)(outStaticPage), { recursive: true }), data[PAGE_STATIC_DATA_FUNCTION]) {
573
+ let staticProps = await data[PAGE_STATIC_DATA_FUNCTION]();
574
+ (0, import_node_fs6.writeFileSync)(outStaticPage, JSON.stringify(staticProps));
575
+ } else
576
+ staticManifest[outfile] = null;
577
+ }
578
+ }
579
+ return spinner.stop(
580
+ `Static props generated. (${((import_node_perf_hooks2.performance.now() - startTime) / 1e3).toFixed(2)}s)`
581
+ ), staticManifest;
582
+ }
583
+ function extaBuild(compilerOptions = {}) {
584
+ let viteConfig, pageMap = {}, pages, vite, staticManifest;
585
+ function generatePageMap(bundle) {
586
+ if (Object.keys(pageMap).length !== 0)
587
+ return pageMap;
588
+ for (let key in bundle) {
589
+ if (bundle[key].type === "asset" || !bundle[key].isDynamicEntry && !bundle[key].exports.includes("__exta_page"))
590
+ continue;
591
+ let setKey = (0, import_node_path9.relative)(
592
+ (0, import_node_path9.join)(".exta", "client").replace(/\\/g, "/"),
593
+ bundle[key].facadeModuleId
594
+ ), pageName = (0, import_node_path9.parse)(setKey).name;
595
+ pageName === "_layout" && (setKey = "[layout]"), pageName === "_error" && (setKey = "[error]"), pageMap[setKey] = key;
596
+ }
597
+ return pageMap;
598
+ }
599
+ return {
600
+ name: "exta:build",
601
+ apply: "build",
602
+ async config(config) {
603
+ initialize(config.build.outDir || "dist", {}), pages = await compilePages({
604
+ ...compilerOptions,
605
+ outdir: config.build.outDir || "dist"
606
+ }), config.build ??= {}, config.build.rollupOptions ??= {}, config.build.rollupOptions.input ??= {}, config.build.manifest = true, config.build.rollupOptions.input["index.html"] = "index.html", vite = await (0, import_vite.createServer)({
607
+ server: { middlewareMode: true, hmr: false },
608
+ ...config
609
+ });
610
+ },
611
+ async configResolved(config) {
612
+ viteConfig = config;
613
+ },
614
+ async buildStart() {
615
+ },
616
+ async generateBundle(options, bundle) {
617
+ pages = await compilePages({ ...compilerOptions, outdir: viteConfig.build.outDir }), initialize(viteConfig.build.outDir, pages), console.log(), console.log(), staticManifest = await createStaticProps(pages, viteConfig.build.outDir), console.log(), (0, import_node_fs4.writeFileSync)(
618
+ (0, import_node_path9.join)(viteConfig.build.outDir, "map.json"),
619
+ JSON.stringify(generatePageMap(bundle))
620
+ );
621
+ },
622
+ async writeBundle() {
623
+ let { outDir } = viteConfig.build, indexHTML = (0, import_node_fs4.readFileSync)((0, import_node_path9.join)(outDir, "index.html")).toString();
624
+ pages = await compilePages(
625
+ { ...compilerOptions, outdir: viteConfig.build.outDir },
626
+ true
627
+ );
628
+ let manifestPath = (0, import_node_path9.join)(outDir, ".vite/manifest.json"), manifest = JSON.parse((0, import_node_fs4.readFileSync)(manifestPath).toString());
629
+ if (console.log(), await createStaticHTML(
630
+ pages,
631
+ viteConfig.build.outDir,
632
+ vite,
633
+ indexHTML,
634
+ manifest,
635
+ staticManifest
636
+ ), await vite.close(), (0, import_node_fs4.rmSync)((0, import_node_path9.join)(outDir, "map.json"), { recursive: true, force: true }), (0, import_node_fs4.rmSync)((0, import_node_path9.join)(outDir, "manifest.js"), { recursive: true, force: true }), (0, import_node_fs4.rmSync)((0, import_node_path9.join)(outDir, "client.js"), { recursive: true, force: true }), (0, import_node_fs4.rmSync)((0, import_node_path9.join)(outDir, "server"), { recursive: true, force: true }), (0, import_node_fs4.rmSync)((0, import_node_path9.join)(outDir, "client"), { recursive: true, force: true }), process.env.BUILD_SUMMARY) {
637
+ let buildSummary = [];
638
+ buildSummary.push("Build Summary");
639
+ for (let staticFile in staticManifest) {
640
+ let filename = changeExtension(staticFile.replace(/_/g, "/"), "");
641
+ if (!staticManifest[staticFile]) {
642
+ buildSummary.push(`${filename}`);
643
+ continue;
644
+ }
645
+ buildSummary.push(
646
+ `${filename.padEnd(60)}${`${staticManifest[staticFile] || "null"}.json`}`
647
+ );
648
+ }
649
+ (0, import_node_fs4.writeFileSync)((0, import_node_path9.join)(__dirname, "../summary.txt"), buildSummary.join(`
650
+ `)), console.log(
651
+ `
652
+ Check the ${(0, import_node_path9.join)(__dirname, "../summary.txt")} file to view the build summary.`
653
+ );
654
+ }
655
+ console.log();
656
+ },
657
+ transformIndexHtml(html) {
658
+ return {
659
+ html,
660
+ tags: [
661
+ {
662
+ tag: "script",
663
+ injectTo: "head",
664
+ attrs: { id: "__PAGE_MAP__", type: "text/javascript" },
665
+ children: `window.__EXTA_PAGEMAP__ = ${JSON.stringify(pageMap)}`
666
+ }
667
+ ]
668
+ };
669
+ }
670
+ };
671
+ }
672
+ var manifestModuleId = "$exta-manifest", resolvedManifestModuleId = "\0" + manifestModuleId, clientModuleId = "$exta-client", resolvedClientModuleId = "\0" + clientModuleId, routerModuleId = "$exta-router", resolvedRouterModuleId = "\0" + routerModuleId;
673
+ function exta(options) {
674
+ let isDev = true, dist = options?.compileOptions.outdir ?? (0, import_node_path.join)(process.cwd(), ".exta"), _manifest_object = [], _server_props = /* @__PURE__ */ new Map(), _pages, _manifest = null, logger, env;
675
+ (0, import_node_fs.existsSync)(dist) && (0, import_node_fs.rmSync)(dist, { recursive: true, force: true }), (0, import_node_fs.mkdirSync)(dist);
676
+ function generateManifest(rawManif, force = false) {
677
+ if (_manifest && !force)
678
+ return _manifest;
679
+ let manifest = [];
680
+ for (let path2 in rawManif) {
681
+ let converted = convertToRegex(path2), relativePath = (0, import_node_path.relative)(
682
+ (0, import_node_path.join)(process.cwd(), ".exta"),
683
+ rawManif[path2].client
684
+ ).replace(/\\/g, "/"), code = `{path: ${JSON.stringify(path2)}, regexp: ${converted.regex.toString()}, params: ${JSON.stringify(converted.params)}, buildPath: ${JSON.stringify(relativePath)}, originalPath: ${JSON.stringify(path2)}}`;
685
+ manifest.push(code), _manifest_object.push({
686
+ path: path2,
687
+ originalPath: path2,
688
+ regexp: converted.regex,
689
+ params: converted.params,
690
+ buildPath: relativePath,
691
+ buildServerPath: rawManif[path2].server
692
+ });
693
+ }
694
+ return _manifest = `export const PAGES_MANIFEST = [
695
+ ${manifest.join(`,
696
+ `)}
697
+ ]`, _manifest;
698
+ }
699
+ let findPage2 = (url) => findPage(url, _manifest_object);
700
+ return [
701
+ {
702
+ name: "exta",
703
+ config(config, _env) {
704
+ env = _env, config.server ??= {}, config.server.watch ??= {}, config.server.watch.ignored = [
705
+ "/.exta/**",
706
+ ...Array.isArray(config.server.watch.ignored) ? config.server.watch.ignored : config.server.watch.ignored ? [config.server.watch.ignored] : []
707
+ ], config.resolve ??= {}, config.resolve.alias ??= {}, config.resolve.alias["$exta-pages"] = (0, import_node_path.join)(
708
+ env.command === "serve" ? dist : config.build.outDir || "dist",
709
+ "manifest.js"
710
+ );
711
+ },
712
+ configResolved(config) {
713
+ logger = config.logger;
714
+ },
715
+ async handleHotUpdate({ server, file }) {
716
+ if (file.includes(".exta"))
717
+ return [];
718
+ let dist2 = options?.compileOptions?.outdir || (0, import_node_path.join)(process.cwd(), ".exta");
719
+ _pages = await compilePages(options?.compileOptions), _server_props.clear();
720
+ let beforeManifest = `${_manifest}`, afterManifest = generateManifest(_pages, true);
721
+ if (beforeManifest !== afterManifest)
722
+ return server.ws.send({ type: "full-reload" }), [];
723
+ (0, import_node_fs.writeFileSync)(
724
+ (0, import_node_path.join)(dist2, "manifest.js"),
725
+ `export default {${Object.keys(_pages).map(
726
+ (page) => ` "${page}": () => import("./${(0, import_node_path.relative)(dist2, _pages[page].client).replace(/\\/g, "/")}"),
727
+ `
728
+ ).join(`
729
+ `)}}`
730
+ );
731
+ let invalidateAndUpdate = (modid, isVirtual = true) => {
732
+ if (!modid)
733
+ return;
734
+ let mod = server.moduleGraph.getModuleById(modid);
735
+ mod && (server.moduleGraph.invalidateModule(mod), server.ws.send({
736
+ type: "update",
737
+ updates: [
738
+ {
739
+ type: "js-update",
740
+ path: isVirtual ? "/@id/" + mod.id : mod.url,
741
+ acceptedPath: isVirtual ? "/@id/" + mod.id : mod.url,
742
+ timestamp: Date.now()
743
+ }
744
+ ]
745
+ }));
746
+ };
747
+ invalidateAndUpdate(resolvedManifestModuleId), invalidateAndUpdate(
748
+ (await server.moduleGraph.getModuleByUrl("$exta-pages"))?.id ?? null
749
+ );
750
+ let normalizedFile = file.replace(/\\/g, "/"), pagesDirectory = (0, import_node_path.join)(process.cwd(), "pages"), pagesFiles = scanDirectory(pagesDirectory).map(
751
+ (p) => p.replace(/\\/g, "/")
752
+ ), compiledFile = changeExtension(
753
+ (0, import_node_path.join)(
754
+ process.cwd(),
755
+ ".exta",
756
+ "client",
757
+ (0, import_node_path.relative)(pagesDirectory, normalizedFile)
758
+ ),
759
+ ".js"
760
+ ).replace(/\\/g, "/");
761
+ if (pagesFiles.includes(normalizedFile)) {
762
+ let modules = Array.from(server.moduleGraph.urlToModuleMap.values()).filter(
763
+ (mod) => mod.file && mod.file.replace(/\\/g, "/") === compiledFile
764
+ );
765
+ for (let mod of modules)
766
+ invalidateAndUpdate(mod.id, false);
767
+ }
768
+ logger.info(
769
+ `${"[exta]".gray} ${(0, import_node_path.relative)(process.cwd(), file).cyan.bold} updated`,
770
+ {}
771
+ );
772
+ },
773
+ async buildStart() {
774
+ _pages = await compilePages(options?.compileOptions);
775
+ },
776
+ async configureServer(server) {
777
+ _pages = await compilePages(options?.compileOptions), initialize(options?.compileOptions?.outdir, _pages), isDev && server.middlewares.use("/.exta/__page_data", async (req, res) => {
778
+ let page = new URL(req.url, "http://localhost").searchParams.get("page") || "/";
779
+ if (debug(`Requested "${page}"`), page === "$IS_CONNECTED$")
780
+ return res.end(JSON.stringify({ connected: true }));
781
+ let clientURL = new URL(page, "http://localhost"), pageManifest = findPage2(page), prettyPathname = prettyURL(decodeURIComponent(clientURL.pathname));
782
+ if (res.setHeader("Content-Type", "application/json"), !pageManifest?.buildServerPath)
783
+ return res.end(JSON.stringify({ props: {}, status: 404 }));
784
+ if (_server_props.has(prettyPathname))
785
+ return res.end(
786
+ JSON.stringify({
787
+ props: _server_props.get(prettyPathname),
788
+ status: 200,
789
+ cached: true
790
+ })
791
+ );
792
+ try {
793
+ let serverModule = await import(`${(0, import_node_url.pathToFileURL)(pageManifest.buildServerPath).href}?v=${Date.now()}`), params = matchUrlToRoute(clientURL.pathname, {
794
+ regex: pageManifest.regexp,
795
+ params: pageManifest.params
796
+ }), data = {};
797
+ if (serverModule[PAGE_STATIC_PARAMS_FUNCTION]) {
798
+ let availableParams = await serverModule[PAGE_STATIC_PARAMS_FUNCTION](), success = false;
799
+ for (let allowedParams of availableParams)
800
+ (0, import_node_util.isDeepStrictEqual)(encodeJSON(allowedParams), params) && (success = true);
801
+ if (!success)
802
+ return res.end(
803
+ JSON.stringify({
804
+ props: {},
805
+ status: 404
806
+ })
807
+ );
808
+ }
809
+ serverModule[PAGE_STATIC_DATA_FUNCTION] && (data = await serverModule[PAGE_STATIC_DATA_FUNCTION]({
810
+ params
811
+ })), _server_props.set(prettyPathname, data), res.end(JSON.stringify({ props: data, status: 200 })), debug(`Request ended "${page}"`);
812
+ } catch (e) {
813
+ console.error(e), res.end(
814
+ JSON.stringify({
815
+ message: "Internal Server Error",
816
+ detail: e.message,
817
+ status: 500
818
+ })
819
+ );
820
+ }
821
+ });
822
+ },
823
+ transformIndexHtml(html) {
824
+ return html.replace("%body%", '<div id="_app"></div>');
825
+ },
826
+ resolveId(id) {
827
+ if (id === manifestModuleId)
828
+ return resolvedManifestModuleId;
829
+ if (id === clientModuleId)
830
+ return resolvedClientModuleId;
831
+ if (id === routerModuleId)
832
+ return resolvedRouterModuleId;
833
+ },
834
+ load(id) {
835
+ if (id === resolvedClientModuleId)
836
+ return {
837
+ code: (0, import_node_fs.readFileSync)((0, import_node_path.join)(__dirname, "client.mjs"), "utf-8")
838
+ };
839
+ if (id === resolvedManifestModuleId)
840
+ return {
841
+ code: generateManifest(_pages)
842
+ };
843
+ if (id === resolvedRouterModuleId)
844
+ return {
845
+ code: (0, import_node_fs.readFileSync)((0, import_node_path.join)(__dirname, "router.mjs"), "utf-8")
846
+ };
847
+ }
848
+ },
849
+ extaBuild(options?.compileOptions || {})
850
+ ];
851
+ }