@seip/bluebird-js 0.1.5 → 0.1.7

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.
@@ -1,529 +1,613 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import { pathToFileURL } from "node:url";
4
- import Config from "./config.js";
5
- import html from "./html.js";
6
- import { compileJsx, registerJsxLoader, stripTsTypes } from "./jsx.js";
7
-
8
- registerJsxLoader();
9
-
10
- const props = Config.props();
11
- const DEBUG = props.debug;
12
-
13
- /**
14
- * Returns the base views directory dynamically relative to Config.appDir().
15
- * @returns {string}
16
- */
17
- function getViewsDir() {
18
- return path.resolve(Config.appDir(), process.env.VIEWS_PATH || "app/views");
19
- }
20
-
21
- /**
22
- * Module and raw file cache for production mode.
23
- * @type {Map<string, Object>}
24
- */
25
- const moduleCache = new Map();
26
-
27
- /**
28
- * Checks whether a candidate path safely resides inside the views directory.
29
- * Prevents directory traversal attacks.
30
- * @param {string} candidatePath
31
- * @returns {boolean}
32
- */
33
- function isSafePath(candidatePath) {
34
- const viewsDir = getViewsDir();
35
- const resolved = path.resolve(viewsDir, candidatePath);
36
- return resolved.startsWith(viewsDir);
37
- }
38
-
39
- /**
40
- * Parses JSX-like attribute strings inside legacy `html\`...\`` template literals.
41
- * @param {string} attrs
42
- * @returns {string}
43
- */
44
- function transformJsxAttributes(attrs) {
45
- const trimmed = attrs.trim();
46
- if (!trimmed) return "{}";
47
-
48
- if (trimmed.startsWith("props=")) {
49
- let propVal = trimmed.slice(6).trim();
50
- if (propVal.startsWith("{{") && propVal.endsWith("}}")) {
51
- return propVal.slice(1, -1);
52
- }
53
- if (propVal.startsWith("{") && propVal.endsWith("}")) {
54
- const inner = propVal.slice(1, -1).trim();
55
- if (inner.startsWith("{") && inner.endsWith("}")) {
56
- return inner;
57
- }
58
- return `{ ${inner} }`;
59
- }
60
- return propVal;
61
- }
62
-
63
- const entries = [];
64
- const regex = /([a-zA-Z0-9_\-]+)(?:\s*=\s*(?:\{([\s\S]*?)\}|"([^"]*)"|'([^']*)'))?/g;
65
- let m;
66
- let hasParsed = false;
67
- while ((m = regex.exec(trimmed)) !== null) {
68
- hasParsed = true;
69
- const key = m[1];
70
- if (key.startsWith("...")) {
71
- entries.push(key);
72
- continue;
73
- }
74
- if (m[2] !== undefined) {
75
- entries.push(`${key}: (${m[2]})`);
76
- } else if (m[3] !== undefined) {
77
- entries.push(`${key}: "${m[3]}"`);
78
- } else if (m[4] !== undefined) {
79
- entries.push(`${key}: '${m[4]}'`);
80
- } else {
81
- entries.push(`${key}: true`);
82
- }
83
- }
84
-
85
- if (!hasParsed) return "{}";
86
- return `{ ${entries.join(", ")} }`;
87
- }
88
-
89
- /**
90
- * Transforms legacy JSX component tags inside `html\`...\`` view source code into JavaScript calls.
91
- * @param {string} code
92
- * @returns {string}
93
- */
94
- function transformViewJsx(code) {
95
- let transformed = code;
96
- transformed = transformed.replace(
97
- /\$\{\s*<([A-Z][a-zA-Z0-9_]*)([\s\S]*?)\/>\s*\}/g,
98
- (match, compName, attrs) => {
99
- return `\${${compName}(${transformJsxAttributes(attrs)})}`;
100
- }
101
- );
102
- transformed = transformed.replace(
103
- /<([A-Z][a-zA-Z0-9_]*)\s+props=\{\s*\{?([^}]*)\}?\s*\}\s*\/>/g,
104
- (match, compName, inner) => {
105
- return `\${${compName}({ ${inner.trim()} })}`;
106
- }
107
- );
108
- return transformed;
109
- }
110
-
111
- /**
112
- * Automatically discovers and registers components from views directories.
113
- */
114
- async function autoRegisterComponents() {
115
- const viewsDir = getViewsDir();
116
- const dirs = [path.join(viewsDir, "components"), path.join(viewsDir, "partials")];
117
-
118
- for (const dir of dirs) {
119
- if (!fs.existsSync(dir)) continue;
120
- try {
121
- const files = fs.readdirSync(dir);
122
- for (const file of files) {
123
- if ((!file.endsWith(".js") && !file.endsWith(".jsx")) || file.startsWith(".")) continue;
124
- const ext = path.extname(file);
125
- const compName = path.basename(file, ext);
126
- if (html.getComponent(compName)) continue;
127
- const fullPath = path.join(dir, file);
128
- try {
129
- const mod = await importModule(fullPath);
130
- const compFn = mod.default || mod[compName];
131
- if (typeof compFn === "function") {
132
- html.register({ [compName]: compFn });
133
- }
134
- } catch {}
135
- }
136
- } catch {}
137
- }
138
- }
139
-
140
- /**
141
- * Loads a JavaScript or React JSX view module with development cache-busting, .asar unpacked fallback,
142
- * zero-disk in-memory JSX compilation, or production memoization.
143
- * @param {string} absolutePath
144
- * @returns {Promise<Object>}
145
- */
146
- async function importModule(absolutePath) {
147
- if (!DEBUG && moduleCache.has(absolutePath)) {
148
- return moduleCache.get(absolutePath);
149
- }
150
-
151
- let targetPath = absolutePath;
152
- if (absolutePath.includes(".asar")) {
153
- const unpackedPath = absolutePath.replace(/\.asar(?=[\/\\]|$)/, ".asar.unpacked");
154
- if (fs.existsSync(unpackedPath)) {
155
- targetPath = unpackedPath;
156
- }
157
- }
158
-
159
- const isJsxFile = targetPath.endsWith(".jsx");
160
- const isTsxFile = targetPath.endsWith(".tsx");
161
- const isTsFile = targetPath.endsWith(".ts");
162
- const isJsxOrTsx = isJsxFile || isTsxFile;
163
- const rawCode = fs.readFileSync(targetPath, "utf-8");
164
- const hasTemplateJsx = !isJsxOrTsx && (/\$\{\s*<[A-Z]|<[A-Z][a-zA-Z0-9_]*\s+props=/.test(rawCode));
165
-
166
- let mod;
167
- if (hasTemplateJsx) {
168
- const transformedCode = transformViewJsx(rawCode);
169
- const uniqueSuffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
170
- const tempFile = path.join(
171
- path.dirname(targetPath),
172
- `.bb-${uniqueSuffix}-${path.basename(targetPath)}`
173
- );
174
- fs.writeFileSync(tempFile, transformedCode, "utf-8");
175
- try {
176
- const fileUrl = pathToFileURL(tempFile).href;
177
- mod = await import(fileUrl);
178
- } finally {
179
- try {
180
- if (fs.existsSync(tempFile)) fs.unlinkSync(tempFile);
181
- } catch {}
182
- }
183
- } else {
184
- const stats = fs.statSync(targetPath);
185
- const fileUrl = pathToFileURL(targetPath).href;
186
- const targetUrl = DEBUG ? `${fileUrl}?t=${stats.mtimeMs}` : fileUrl;
187
-
188
- try {
189
- mod = await import(targetUrl);
190
- } catch (err) {
191
- if (isJsxOrTsx || isTsFile || absolutePath.includes(".asar")) {
192
- let sourceToLoad = isJsxOrTsx ? compileJsx(rawCode, { ts: isTsxFile }) : rawCode;
193
- if (isTsxFile || isTsFile) {
194
- sourceToLoad = stripTsTypes(sourceToLoad);
195
- }
196
- const dataUrl = `data:text/javascript;base64,${Buffer.from(sourceToLoad).toString("base64")}`;
197
- mod = await import(dataUrl);
198
- } else {
199
- throw err;
200
- }
201
- }
202
- }
203
-
204
- if (!DEBUG) {
205
- moduleCache.set(absolutePath, mod);
206
- }
207
- return mod;
208
- }
209
-
210
- /**
211
- * View loader and resolver for Bluebird.js.
212
- * Resolves React JSX views (.jsx), modular directory views (e.g. "dashboard/view.jsx" or "dashboard/view.js"),
213
- * single-file views, components, and layouts.
214
- */
215
- export class ViewLoader {
216
- /**
217
- * Returns the configured views base directory.
218
- * @returns {string}
219
- */
220
- static getViewsDir() {
221
- return getViewsDir();
222
- }
223
-
224
- /**
225
- * Resolves and loads a view by name.
226
- * Searches React JSX (.jsx) and JS (.js) conventions first, then subdirectories,
227
- * and finally static HTML files.
228
- *
229
- * @param {string} viewName - Logical view identifier.
230
- * @returns {Promise<{type: "jsx"|"js"|"html", module?: Object, filePath: string, content?: string}|null>}
231
- */
232
- static async load(viewName) {
233
- if (!viewName || typeof viewName !== "string") {
234
- return null;
235
- }
236
-
237
- await autoRegisterComponents();
238
-
239
- const clean = viewName.replace(/^\/+/, "").replace(/\.(jsx|js|html|ejs)$/, "");
240
-
241
- const candidates = [
242
- `${clean}.tsx`,
243
- `${clean}.jsx`,
244
- `${clean}.ts`,
245
- `${clean}.js`,
246
- `${clean}/view.tsx`,
247
- `${clean}/view.jsx`,
248
- `${clean}/view.ts`,
249
- `${clean}/view.js`,
250
- path.join("pages", `${clean}.tsx`),
251
- path.join("pages", `${clean}.jsx`),
252
- path.join("pages", `${clean}.ts`),
253
- path.join("pages", `${clean}.js`),
254
- path.join("pages", `${clean}/view.tsx`),
255
- path.join("pages", `${clean}/view.jsx`),
256
- path.join("pages", `${clean}/view.ts`),
257
- path.join("pages", `${clean}/view.js`),
258
- path.join("components", `${clean}.tsx`),
259
- path.join("components", `${clean}.jsx`),
260
- path.join("components", `${clean}.ts`),
261
- path.join("components", `${clean}.js`),
262
- path.join("components", `${clean}/view.tsx`),
263
- path.join("components", `${clean}/view.jsx`),
264
- path.join("components", `${clean}/view.ts`),
265
- path.join("components", `${clean}/view.js`),
266
- path.join("partials", `${clean}.tsx`),
267
- path.join("partials", `${clean}.jsx`),
268
- path.join("partials", `${clean}.ts`),
269
- path.join("partials", `${clean}.js`),
270
- path.join("partials", `${clean}/view.tsx`),
271
- path.join("partials", `${clean}/view.jsx`),
272
- path.join("partials", `${clean}/view.ts`),
273
- path.join("partials", `${clean}/view.js`),
274
- path.join("islands", `${clean}.tsx`),
275
- path.join("islands", `${clean}.jsx`),
276
- path.join("islands", `${clean}.ts`),
277
- path.join("islands", `${clean}.js`),
278
- path.join("layouts", `${clean}/view.tsx`),
279
- path.join("layouts", `${clean}/view.jsx`),
280
- path.join("layouts", `${clean}/view.ts`),
281
- path.join("layouts", `${clean}/view.js`),
282
- path.join("layouts", `${clean}.tsx`),
283
- path.join("layouts", `${clean}.jsx`),
284
- path.join("layouts", `${clean}.ts`),
285
- path.join("layouts", `${clean}.js`),
286
- `${clean}.html`,
287
- path.join("pages", `${clean}.html`),
288
- path.join("components", `${clean}.html`),
289
- path.join("partials", `${clean}.html`),
290
- path.join("layouts", `${clean}.html`),
291
- ];
292
-
293
- const viewsDir = getViewsDir();
294
- for (const candidate of candidates) {
295
- if (!isSafePath(candidate)) continue;
296
-
297
- const fullPath = path.resolve(viewsDir, candidate);
298
- if (fs.existsSync(fullPath)) {
299
- if (candidate.endsWith(".jsx") || candidate.endsWith(".tsx")) {
300
- const mod = await importModule(fullPath);
301
- return { type: "jsx", module: mod, filePath: fullPath };
302
- }
303
-
304
- if (candidate.endsWith(".js") || candidate.endsWith(".ts")) {
305
- const mod = await importModule(fullPath);
306
- return { type: "js", module: mod, filePath: fullPath };
307
- }
308
-
309
- if (candidate.endsWith(".html")) {
310
- const content = fs.readFileSync(fullPath, "utf-8");
311
- return { type: "html", filePath: fullPath, content };
312
- }
313
- }
314
- }
315
-
316
- return null;
317
- }
318
-
319
- /**
320
- * Resolves and loads a layout module by name.
321
- * Defaults to searching in app/views/layouts/.
322
- *
323
- * @param {string} layoutName - Layout name (e.g. "main").
324
- * @returns {Promise<{type: "jsx"|"js"|"html", module?: Object, filePath: string, content?: string}|null>}
325
- */
326
- static async loadLayout(layoutName) {
327
- if (!layoutName) return null;
328
- const clean = layoutName.replace(/^\/+/, "").replace(/\.(jsx|tsx|js|ts|html)$/, "");
329
-
330
- const candidates = [
331
- path.join("layouts", `${clean}/view.tsx`),
332
- path.join("layouts", `${clean}/view.jsx`),
333
- path.join("layouts", `${clean}/view.ts`),
334
- path.join("layouts", `${clean}/view.js`),
335
- path.join("layouts", `${clean}.tsx`),
336
- path.join("layouts", `${clean}.jsx`),
337
- path.join("layouts", `${clean}.ts`),
338
- path.join("layouts", `${clean}.js`),
339
- `${clean}/view.tsx`,
340
- `${clean}/view.jsx`,
341
- `${clean}/view.ts`,
342
- `${clean}/view.js`,
343
- `${clean}.tsx`,
344
- `${clean}.jsx`,
345
- `${clean}.ts`,
346
- `${clean}.js`,
347
- path.join("layouts", `${clean}.html`),
348
- ];
349
-
350
- const viewsDir = getViewsDir();
351
- for (const candidate of candidates) {
352
- if (!isSafePath(candidate)) continue;
353
-
354
- const fullPath = path.resolve(viewsDir, candidate);
355
- if (fs.existsSync(fullPath)) {
356
- if (candidate.endsWith(".jsx") || candidate.endsWith(".tsx")) {
357
- const mod = await importModule(fullPath);
358
- return { type: "jsx", module: mod, filePath: fullPath };
359
- }
360
-
361
- if (candidate.endsWith(".js") || candidate.endsWith(".ts")) {
362
- const mod = await importModule(fullPath);
363
- return { type: "js", module: mod, filePath: fullPath };
364
- }
365
-
366
- if (candidate.endsWith(".html")) {
367
- const content = fs.readFileSync(fullPath, "utf-8");
368
- return { type: "html", filePath: fullPath, content };
369
- }
370
- }
371
- }
372
-
373
- return null;
374
- }
375
-
376
- /**
377
- * Clears in-memory module cache in production.
378
- */
379
- static clearCache() {
380
- moduleCache.clear();
381
- }
382
-
383
- /**
384
- * Scans `app/views/` (excluding `layouts`, `components`, `partials`, `islands`, and `api`)
385
- * to discover page view modules and their declarative route configurations.
386
- *
387
- * Supported exports in any view module:
388
- * - `export const route = "/custom-path" | false` (defaults to file-based route path)
389
- * - `export const cache = 300` (applies `Render.cache(300)` automatically)
390
- * - `export const middlewares = [...]` (applies custom route middlewares)
391
- * - `export const seo = true | false` (defaults to `true` for public routes without middlewares)
392
- * - `export const layout = "main"`
393
- *
394
- * @returns {Promise<Array<{viewName: string, routePath: string, cache: number, middlewares: Function[], seo: boolean, module: Object}>>}
395
- */
396
- static async discoverRoutes() {
397
- const viewsDir = getViewsDir();
398
- if (!fs.existsSync(viewsDir)) return [];
399
-
400
- const ignoredDirs = new Set([
401
- "layouts",
402
- "components",
403
- "partials",
404
- "islands",
405
- "api",
406
- "node_modules",
407
- ]);
408
-
409
- const discovered = [];
410
- const seenViews = new Set();
411
-
412
- /**
413
- * Recursively walks a directory relative to viewsDir.
414
- * @param {string} currentDir
415
- * @param {string} relPrefix
416
- */
417
- const walk = async (currentDir, relPrefix = "") => {
418
- let entries = [];
419
- try {
420
- entries = fs.readdirSync(currentDir, { withFileTypes: true });
421
- } catch {
422
- return;
423
- }
424
-
425
- entries.sort((a, b) => {
426
- if (a.isFile() && b.isFile()) {
427
- const aIsJsx = a.name.endsWith(".jsx") || a.name.endsWith(".tsx");
428
- const bIsJsx = b.name.endsWith(".jsx") || b.name.endsWith(".tsx");
429
- if (aIsJsx && !bIsJsx) return -1;
430
- if (!aIsJsx && bIsJsx) return 1;
431
- }
432
- return a.name.localeCompare(b.name);
433
- });
434
-
435
- for (const entry of entries) {
436
- if (entry.name.startsWith(".") || entry.name.startsWith("_")) continue;
437
-
438
- const fullPath = path.join(currentDir, entry.name);
439
- const relPath = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
440
-
441
- if (entry.isDirectory()) {
442
- if (ignoredDirs.has(entry.name.toLowerCase())) continue;
443
- await walk(fullPath, relPath);
444
- continue;
445
- }
446
-
447
- if (!entry.isFile()) continue;
448
- if (
449
- !entry.name.endsWith(".jsx") &&
450
- !entry.name.endsWith(".tsx") &&
451
- !entry.name.endsWith(".js") &&
452
- !entry.name.endsWith(".ts")
453
- ) {
454
- continue;
455
- }
456
-
457
- const ext = path.extname(entry.name);
458
- const rawViewName = relPath.slice(0, -ext.length).replace(/\\/g, "/");
459
-
460
- if (seenViews.has(rawViewName)) continue;
461
- seenViews.add(rawViewName);
462
-
463
- let mod;
464
- try {
465
- mod = await importModule(fullPath);
466
- } catch {
467
- continue;
468
- }
469
-
470
- if (!mod || typeof mod.default !== "function") continue;
471
- if (mod.route === false) continue;
472
-
473
- let routePath;
474
- if (typeof mod.route === "string" && mod.route.trim()) {
475
- routePath = mod.route.trim();
476
- if (!routePath.startsWith("/")) routePath = `/${routePath}`;
477
- } else {
478
- let normalized = rawViewName;
479
- if (normalized.startsWith("pages/")) {
480
- normalized = normalized.slice("pages/".length);
481
- }
482
- if (normalized === "index" || normalized === "view") {
483
- routePath = "/";
484
- } else if (normalized.endsWith("/index")) {
485
- routePath = "/" + normalized.slice(0, -"/index".length);
486
- } else if (normalized.endsWith("/view")) {
487
- routePath = "/" + normalized.slice(0, -"/view".length);
488
- } else {
489
- routePath = "/" + normalized;
490
- }
491
-
492
- routePath = routePath.replace(/\[([^\]]+)\]/g, ":$1");
493
- }
494
-
495
- if (routePath === "/api" || routePath.startsWith("/api/")) {
496
- continue;
497
- }
498
-
499
- const middlewares = Array.isArray(mod.middlewares)
500
- ? mod.middlewares.filter((fn) => typeof fn === "function")
501
- : typeof mod.middleware === "function"
502
- ? [mod.middleware]
503
- : [];
504
-
505
- const cache = typeof mod.cache === "number" && mod.cache > 0 ? mod.cache : 0;
506
- const seo = mod.seo !== undefined ? Boolean(mod.seo) : middlewares.length === 0;
507
- const actions =
508
- mod.actions && (typeof mod.actions === "object" || typeof mod.actions === "function")
509
- ? mod.actions
510
- : null;
511
-
512
- discovered.push({
513
- viewName: rawViewName,
514
- routePath,
515
- cache,
516
- middlewares,
517
- seo,
518
- actions,
519
- module: mod,
520
- });
521
- }
522
- };
523
-
524
- await walk(viewsDir, "");
525
- return discovered;
526
- }
527
- }
528
-
529
- export default ViewLoader;
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import Config from "./config.js";
5
+ import html from "./html.js";
6
+ import { compileJsx, registerJsxLoader, stripTsTypes } from "./jsx.js";
7
+
8
+ registerJsxLoader();
9
+
10
+ const props = Config.props();
11
+ const DEBUG = props.debug;
12
+
13
+ /**
14
+ * Returns the base views directory dynamically relative to Config.appDir().
15
+ * @returns {string}
16
+ */
17
+ function getViewsDir() {
18
+ return path.resolve(Config.appDir(), process.env.VIEWS_PATH || "app/views");
19
+ }
20
+
21
+ /**
22
+ * Module and raw file cache for production mode.
23
+ * @type {Map<string, Object>}
24
+ */
25
+ const moduleCache = new Map();
26
+
27
+ /**
28
+ * Checks whether a candidate path safely resides inside the views directory.
29
+ * Prevents directory traversal attacks.
30
+ * @param {string} candidatePath
31
+ * @returns {boolean}
32
+ */
33
+ function isSafePath(candidatePath) {
34
+ const viewsDir = getViewsDir();
35
+ const resolved = path.resolve(viewsDir, candidatePath);
36
+ return resolved.startsWith(viewsDir);
37
+ }
38
+
39
+ /**
40
+ * Parses JSX-like attribute strings inside legacy `html\`...\`` template literals.
41
+ * @param {string} attrs
42
+ * @returns {string}
43
+ */
44
+ function transformJsxAttributes(attrs) {
45
+ const trimmed = attrs.trim();
46
+ if (!trimmed) return "{}";
47
+
48
+ if (trimmed.startsWith("props=")) {
49
+ let propVal = trimmed.slice(6).trim();
50
+ if (propVal.startsWith("{{") && propVal.endsWith("}}")) {
51
+ return propVal.slice(1, -1);
52
+ }
53
+ if (propVal.startsWith("{") && propVal.endsWith("}")) {
54
+ const inner = propVal.slice(1, -1).trim();
55
+ if (inner.startsWith("{") && inner.endsWith("}")) {
56
+ return inner;
57
+ }
58
+ return `{ ${inner} }`;
59
+ }
60
+ return propVal;
61
+ }
62
+
63
+ const entries = [];
64
+ const regex = /([a-zA-Z0-9_\-]+)(?:\s*=\s*(?:\{([\s\S]*?)\}|"([^"]*)"|'([^']*)'))?/g;
65
+ let m;
66
+ let hasParsed = false;
67
+ while ((m = regex.exec(trimmed)) !== null) {
68
+ hasParsed = true;
69
+ const key = m[1];
70
+ if (key.startsWith("...")) {
71
+ entries.push(key);
72
+ continue;
73
+ }
74
+ if (m[2] !== undefined) {
75
+ entries.push(`${key}: (${m[2]})`);
76
+ } else if (m[3] !== undefined) {
77
+ entries.push(`${key}: "${m[3]}"`);
78
+ } else if (m[4] !== undefined) {
79
+ entries.push(`${key}: '${m[4]}'`);
80
+ } else {
81
+ entries.push(`${key}: true`);
82
+ }
83
+ }
84
+
85
+ if (!hasParsed) return "{}";
86
+ return `{ ${entries.join(", ")} }`;
87
+ }
88
+
89
+ /**
90
+ * Transforms legacy JSX component tags inside `html\`...\`` view source code into JavaScript calls.
91
+ * @param {string} code
92
+ * @returns {string}
93
+ */
94
+ function transformViewJsx(code) {
95
+ let transformed = code;
96
+ transformed = transformed.replace(
97
+ /\$\{\s*<([A-Z][a-zA-Z0-9_]*)([\s\S]*?)\/>\s*\}/g,
98
+ (match, compName, attrs) => {
99
+ return `\${${compName}(${transformJsxAttributes(attrs)})}`;
100
+ }
101
+ );
102
+ transformed = transformed.replace(
103
+ /<([A-Z][a-zA-Z0-9_]*)\s+props=\{\s*\{?([^}]*)\}?\s*\}\s*\/>/g,
104
+ (match, compName, inner) => {
105
+ return `\${${compName}({ ${inner.trim()} })}`;
106
+ }
107
+ );
108
+ return transformed;
109
+ }
110
+
111
+ /**
112
+ * Automatically discovers and registers components from views directories.
113
+ */
114
+ async function autoRegisterComponents() {
115
+ const viewsDir = getViewsDir();
116
+ const dirs = [path.join(viewsDir, "components"), path.join(viewsDir, "partials")];
117
+
118
+ for (const dir of dirs) {
119
+ if (!fs.existsSync(dir)) continue;
120
+ try {
121
+ const files = fs.readdirSync(dir);
122
+ for (const file of files) {
123
+ if ((!file.endsWith(".js") && !file.endsWith(".jsx")) || file.startsWith(".")) continue;
124
+ const ext = path.extname(file);
125
+ const compName = path.basename(file, ext);
126
+ if (html.getComponent(compName)) continue;
127
+ const fullPath = path.join(dir, file);
128
+ try {
129
+ const mod = await importModule(fullPath);
130
+ const compFn = mod.default || mod[compName];
131
+ if (typeof compFn === "function") {
132
+ html.register({ [compName]: compFn });
133
+ }
134
+ } catch { }
135
+ }
136
+ } catch { }
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Loads a JavaScript or React JSX view module with development cache-busting, .asar unpacked fallback,
142
+ * zero-disk in-memory JSX compilation, or production memoization.
143
+ * @param {string} absolutePath
144
+ * @returns {Promise<Object>}
145
+ */
146
+ async function importModule(absolutePath) {
147
+ if (!DEBUG && moduleCache.has(absolutePath)) {
148
+ return moduleCache.get(absolutePath);
149
+ }
150
+
151
+ let targetPath = absolutePath;
152
+ if (absolutePath.includes(".asar")) {
153
+ const unpackedPath = absolutePath.replace(/\.asar(?=[\/\\]|$)/, ".asar.unpacked");
154
+ if (fs.existsSync(unpackedPath)) {
155
+ targetPath = unpackedPath;
156
+ }
157
+ }
158
+
159
+ const isJsxFile = targetPath.endsWith(".jsx");
160
+ const isTsxFile = targetPath.endsWith(".tsx");
161
+ const isTsFile = targetPath.endsWith(".ts");
162
+ const isJsxOrTsx = isJsxFile || isTsxFile;
163
+ const rawCode = fs.readFileSync(targetPath, "utf-8");
164
+ const hasTemplateJsx = !isJsxOrTsx && (/\$\{\s*<[A-Z]|<[A-Z][a-zA-Z0-9_]*\s+props=/.test(rawCode));
165
+
166
+ let mod;
167
+ if (hasTemplateJsx) {
168
+ const transformedCode = transformViewJsx(rawCode);
169
+ const uniqueSuffix = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
170
+ const tempFile = path.join(
171
+ path.dirname(targetPath),
172
+ `.bb-${uniqueSuffix}-${path.basename(targetPath)}`
173
+ );
174
+ fs.writeFileSync(tempFile, transformedCode, "utf-8");
175
+ try {
176
+ const fileUrl = pathToFileURL(tempFile).href;
177
+ mod = await import(fileUrl);
178
+ } finally {
179
+ try {
180
+ if (fs.existsSync(tempFile)) fs.unlinkSync(tempFile);
181
+ } catch { }
182
+ }
183
+ } else {
184
+ const stats = fs.statSync(targetPath);
185
+ const fileUrl = pathToFileURL(targetPath).href;
186
+ const targetUrl = DEBUG ? `${fileUrl}?t=${stats.mtimeMs}` : fileUrl;
187
+
188
+ try {
189
+ mod = await import(targetUrl);
190
+ } catch (err) {
191
+ if (isJsxOrTsx || isTsFile || absolutePath.includes(".asar")) {
192
+ let sourceToLoad = isJsxOrTsx ? compileJsx(rawCode, { ts: isTsxFile }) : rawCode;
193
+ if (isTsxFile || isTsFile) {
194
+ sourceToLoad = stripTsTypes(sourceToLoad);
195
+ }
196
+ const dataUrl = `data:text/javascript;base64,${Buffer.from(sourceToLoad).toString("base64")}`;
197
+ mod = await import(dataUrl);
198
+ } else {
199
+ throw err;
200
+ }
201
+ }
202
+ }
203
+
204
+ if (!DEBUG) {
205
+ moduleCache.set(absolutePath, mod);
206
+ }
207
+ return mod;
208
+ }
209
+
210
+ /**
211
+ * View loader and resolver for Bluebird.js.
212
+ * Resolves React JSX views (.jsx), modular directory views (e.g. "dashboard/view.jsx" or "dashboard/view.js"),
213
+ * single-file views, components, and layouts.
214
+ */
215
+ export class ViewLoader {
216
+ /**
217
+ * Returns the configured views base directory.
218
+ * @returns {string}
219
+ */
220
+ static getViewsDir() {
221
+ return getViewsDir();
222
+ }
223
+
224
+ /**
225
+ * Returns the pages directory path (app/views/pages).
226
+ * Falls back to app/views if app/views/pages does not exist yet for backwards compatibility.
227
+ * @returns {string}
228
+ */
229
+ static getPagesDir() {
230
+ const viewsDir = ViewLoader.getViewsDir();
231
+ const pagesDir = path.join(viewsDir, "pages");
232
+ return fs.existsSync(pagesDir) ? pagesDir : viewsDir;
233
+ }
234
+
235
+ /**
236
+ * Resolves the absolute file path for a view name.
237
+ * Searches in app/views/pages/${viewName} first, then falls back to app/views/${viewName},
238
+ * followed by subdirectories (components, partials, islands, layouts).
239
+ *
240
+ * @param {string} viewName - Logical view identifier.
241
+ * @returns {string|null} Resolved absolute file path or null.
242
+ */
243
+ static resolve(viewName) {
244
+ if (!viewName || typeof viewName !== "string") {
245
+ return null;
246
+ }
247
+
248
+ const viewsDir = ViewLoader.getViewsDir();
249
+ const pagesDir = path.join(viewsDir, "pages");
250
+ const hasPagesDir = fs.existsSync(pagesDir);
251
+
252
+ const clean = viewName.replace(/^\/+/, "").replace(/\.(jsx|tsx|js|ts|html|ejs)$/, "");
253
+ const subName = clean.startsWith("pages/") ? clean.slice("pages/".length) : clean;
254
+
255
+ const rawClean = viewName.replace(/^\/+/, "");
256
+ const rawSub = rawClean.startsWith("pages/") ? rawClean.slice("pages/".length) : rawClean;
257
+
258
+ const extensions = [
259
+ ".tsx",
260
+ ".jsx",
261
+ ".ts",
262
+ ".js",
263
+ "/view.tsx",
264
+ "/view.jsx",
265
+ "/view.ts",
266
+ "/view.js",
267
+ ".html",
268
+ ];
269
+
270
+ const candidateRels = [];
271
+
272
+ if (!clean.startsWith("pages/")) {
273
+ // 1. Search in app/views/pages/ first (if pages directory exists)
274
+ if (hasPagesDir) {
275
+ for (const ext of extensions) {
276
+ candidateRels.push(`pages/${clean}${ext}`);
277
+ }
278
+ candidateRels.push(`pages/${rawClean}`);
279
+ }
280
+
281
+ // 2. Search in app/views/
282
+ for (const ext of extensions) {
283
+ candidateRels.push(`${clean}${ext}`);
284
+ }
285
+ candidateRels.push(rawClean);
286
+ } else {
287
+ // viewName explicitly starts with "pages/"
288
+ for (const ext of extensions) {
289
+ candidateRels.push(`${clean}${ext}`);
290
+ }
291
+ candidateRels.push(rawClean);
292
+
293
+ // Fallback without "pages/" prefix
294
+ for (const ext of extensions) {
295
+ candidateRels.push(`${subName}${ext}`);
296
+ }
297
+ candidateRels.push(rawSub);
298
+ }
299
+
300
+ // 3. Fallback to subdirectories: components, partials, islands, layouts
301
+ const folders = ["components", "partials", "islands", "layouts"];
302
+ for (const folder of folders) {
303
+ for (const ext of extensions) {
304
+ candidateRels.push(`${folder}/${subName}${ext}`);
305
+ }
306
+ candidateRels.push(`${folder}/${rawSub}`);
307
+ }
308
+
309
+ for (const candidate of candidateRels) {
310
+ if (!isSafePath(candidate)) continue;
311
+ const fullPath = path.resolve(viewsDir, candidate);
312
+ if (fs.existsSync(fullPath)) {
313
+ try {
314
+ const stat = fs.statSync(fullPath);
315
+ if (stat.isFile()) {
316
+ return fullPath;
317
+ }
318
+ } catch { }
319
+ }
320
+ }
321
+
322
+ return null;
323
+ }
324
+
325
+ /**
326
+ * Resolves and loads a view by name.
327
+ * Searches React JSX (.jsx) and JS (.js) conventions first, then subdirectories,
328
+ * and finally static HTML files.
329
+ *
330
+ * @param {string} viewName - Logical view identifier.
331
+ * @returns {Promise<{type: "jsx"|"js"|"html", module?: Object, filePath: string, content?: string}|null>}
332
+ */
333
+ static async load(viewName) {
334
+ if (!viewName || typeof viewName !== "string") {
335
+ return null;
336
+ }
337
+
338
+ await autoRegisterComponents();
339
+
340
+ const fullPath = ViewLoader.resolve(viewName);
341
+ if (!fullPath) return null;
342
+
343
+ if (fullPath.endsWith(".jsx") || fullPath.endsWith(".tsx")) {
344
+ const mod = await importModule(fullPath);
345
+ return { type: "jsx", module: mod, filePath: fullPath };
346
+ }
347
+
348
+ if (fullPath.endsWith(".js") || fullPath.endsWith(".ts")) {
349
+ const mod = await importModule(fullPath);
350
+ return { type: "js", module: mod, filePath: fullPath };
351
+ }
352
+
353
+ if (fullPath.endsWith(".html")) {
354
+ const content = fs.readFileSync(fullPath, "utf-8");
355
+ return { type: "html", filePath: fullPath, content };
356
+ }
357
+
358
+ return null;
359
+ }
360
+
361
+ /**
362
+ * Resolves and loads a layout module by name.
363
+ * Defaults to searching in app/views/layouts/.
364
+ *
365
+ * @param {string} layoutName - Layout name (e.g. "main").
366
+ * @returns {Promise<{type: "jsx"|"js"|"html", module?: Object, filePath: string, content?: string}|null>}
367
+ */
368
+ static async loadLayout(layoutName) {
369
+ if (!layoutName) return null;
370
+ const clean = layoutName.replace(/^\/+/, "").replace(/\.(jsx|tsx|js|ts|html)$/, "");
371
+
372
+ const candidates = [
373
+ path.join("layouts", `${clean}/view.tsx`),
374
+ path.join("layouts", `${clean}/view.jsx`),
375
+ path.join("layouts", `${clean}/view.ts`),
376
+ path.join("layouts", `${clean}/view.js`),
377
+ path.join("layouts", `${clean}.tsx`),
378
+ path.join("layouts", `${clean}.jsx`),
379
+ path.join("layouts", `${clean}.ts`),
380
+ path.join("layouts", `${clean}.js`),
381
+ `${clean}/view.tsx`,
382
+ `${clean}/view.jsx`,
383
+ `${clean}/view.ts`,
384
+ `${clean}/view.js`,
385
+ `${clean}.tsx`,
386
+ `${clean}.jsx`,
387
+ `${clean}.ts`,
388
+ `${clean}.js`,
389
+ path.join("layouts", `${clean}.html`),
390
+ ];
391
+
392
+ const viewsDir = getViewsDir();
393
+ for (const candidate of candidates) {
394
+ if (!isSafePath(candidate)) continue;
395
+
396
+ const fullPath = path.resolve(viewsDir, candidate);
397
+ if (fs.existsSync(fullPath)) {
398
+ if (candidate.endsWith(".jsx") || candidate.endsWith(".tsx")) {
399
+ const mod = await importModule(fullPath);
400
+ return { type: "jsx", module: mod, filePath: fullPath };
401
+ }
402
+
403
+ if (candidate.endsWith(".js") || candidate.endsWith(".ts")) {
404
+ const mod = await importModule(fullPath);
405
+ return { type: "js", module: mod, filePath: fullPath };
406
+ }
407
+
408
+ if (candidate.endsWith(".html")) {
409
+ const content = fs.readFileSync(fullPath, "utf-8");
410
+ return { type: "html", filePath: fullPath, content };
411
+ }
412
+ }
413
+ }
414
+
415
+ return null;
416
+ }
417
+
418
+ /**
419
+ * Clears in-memory module cache in production.
420
+ */
421
+ static clearCache() {
422
+ moduleCache.clear();
423
+ }
424
+
425
+ /**
426
+ * Scans `app/views/pages/` (or `app/views/` if `pages/` does not exist,
427
+ * excluding `layouts`, `components`, `partials`, `islands`, `actions`, `client`, and `api`)
428
+ * to discover page view modules and their declarative route configurations.
429
+ *
430
+ * Supported exports in any view module:
431
+ * - `export const route = "/custom-path" | false` (defaults to file-based route path)
432
+ * - `export const cache = 300` (applies `Render.cache(300)` automatically)
433
+ * - `export const middlewares = [...]` (applies custom route middlewares)
434
+ * - `export const seo = true | false` (defaults to `true` for public routes without middlewares)
435
+ * - `export const layout = "main"`
436
+ * - `export const actions = { ... }`
437
+ *
438
+ * @returns {Promise<Array<{viewName: string, routePath: string, cache: number, middlewares: Function[], seo: boolean, actions: any, module: Object}>>}
439
+ */
440
+ static async discoverRoutes() {
441
+ const viewsDir = ViewLoader.getViewsDir();
442
+ const pagesDir = path.join(viewsDir, "pages");
443
+ const hasPagesDir = fs.existsSync(pagesDir);
444
+ const scanRoot = hasPagesDir ? pagesDir : viewsDir;
445
+
446
+ if (!fs.existsSync(scanRoot)) return [];
447
+
448
+ const discovered = [];
449
+ const seenViews = new Set();
450
+ const ignoredFolders = new Set([
451
+ "layouts",
452
+ "components",
453
+ "partials",
454
+ "islands",
455
+ "actions",
456
+ "client",
457
+ "api",
458
+ "node_modules",
459
+ ]);
460
+
461
+ const actionsDir = path.join(viewsDir, "actions");
462
+ const sharedActions = {};
463
+ if (fs.existsSync(actionsDir)) {
464
+ try {
465
+ const actionFiles = fs.readdirSync(actionsDir);
466
+ for (const file of actionFiles) {
467
+ if (!/\.(js|ts|jsx|tsx)$/.test(file) || file.endsWith(".d.ts") || file.startsWith(".")) continue;
468
+ try {
469
+ const actionMod = await importModule(path.join(actionsDir, file));
470
+ if (actionMod.actions && typeof actionMod.actions === "object") {
471
+ Object.assign(sharedActions, actionMod.actions);
472
+ }
473
+ for (const [key, val] of Object.entries(actionMod)) {
474
+ if (
475
+ val &&
476
+ (typeof val === "object" || typeof val === "function") &&
477
+ (val.__isBluebirdAction || val.__bb_action__)
478
+ ) {
479
+ val.__actionName = val.__actionName || key;
480
+ sharedActions[key] = val;
481
+ }
482
+ }
483
+ } catch {}
484
+ }
485
+ } catch {}
486
+ }
487
+
488
+ async function scanDir(currentDir, relativePrefix = "") {
489
+ let entries = [];
490
+ try {
491
+ entries = fs.readdirSync(currentDir, { withFileTypes: true });
492
+ } catch {
493
+ return;
494
+ }
495
+
496
+ entries.sort((a, b) => {
497
+ if (a.isFile() && b.isFile()) {
498
+ const aIsJsx = a.name.endsWith(".jsx") || a.name.endsWith(".tsx");
499
+ const bIsJsx = b.name.endsWith(".jsx") || b.name.endsWith(".tsx");
500
+ if (aIsJsx && !bIsJsx) return -1;
501
+ if (!aIsJsx && bIsJsx) return 1;
502
+ }
503
+ return a.name.localeCompare(b.name);
504
+ });
505
+
506
+ for (const entry of entries) {
507
+ if (entry.name.startsWith(".") || entry.name.startsWith("_")) continue;
508
+
509
+ if (entry.isDirectory()) {
510
+ if (entry.name.toLowerCase() === "node_modules") continue;
511
+
512
+ // If app/views/pages does not exist, keep ignoring reserved folders at root
513
+ if (!hasPagesDir && !relativePrefix && ignoredFolders.has(entry.name.toLowerCase())) {
514
+ continue;
515
+ }
516
+
517
+ await scanDir(
518
+ path.join(currentDir, entry.name),
519
+ relativePrefix ? `${relativePrefix}/${entry.name}` : entry.name
520
+ );
521
+ continue;
522
+ }
523
+
524
+ if (!/\.(jsx|tsx|js|ts)$/.test(entry.name) || entry.name.endsWith(".d.ts")) continue;
525
+
526
+ const ext = path.extname(entry.name);
527
+ const baseName = entry.name.slice(0, -ext.length);
528
+ const routeRel = (relativePrefix ? `${relativePrefix}/${baseName}` : baseName).replace(/\\/g, "/");
529
+
530
+ if (seenViews.has(routeRel)) continue;
531
+ seenViews.add(routeRel);
532
+
533
+ const fullPath = path.join(currentDir, entry.name);
534
+
535
+ let mod;
536
+ try {
537
+ mod = await importModule(fullPath);
538
+ } catch {
539
+ continue;
540
+ }
541
+
542
+ if (!mod || typeof mod.default !== "function") continue;
543
+ if (mod.route === false) continue;
544
+
545
+ // viewName is relative to app/views/ (e.g. "pages/dashboard" or "pages/index")
546
+ const viewName = hasPagesDir ? `pages/${routeRel}` : routeRel;
547
+
548
+ // URL inference from pages/: "index" -> "/", "users/index" -> "/users"
549
+ let defaultRoutePath = "/" + routeRel.replace(/\/(index|view)$/, "");
550
+ if (defaultRoutePath === "/index" || defaultRoutePath === "/view" || defaultRoutePath === "") {
551
+ defaultRoutePath = "/";
552
+ }
553
+ defaultRoutePath = defaultRoutePath.replace(/\[([^\]]+)\]/g, ":$1");
554
+
555
+ let routePath;
556
+ if (typeof mod.route === "string" && mod.route.trim()) {
557
+ routePath = mod.route.trim();
558
+ if (!routePath.startsWith("/")) routePath = `/${routePath}`;
559
+ } else {
560
+ routePath = defaultRoutePath;
561
+ }
562
+
563
+ routePath = routePath.replace(/\[([^\]]+)\]/g, ":$1");
564
+
565
+ if (routePath === "/api" || routePath.startsWith("/api/")) {
566
+ continue;
567
+ }
568
+
569
+ const middlewares = Array.isArray(mod.middlewares)
570
+ ? mod.middlewares.filter((fn) => typeof fn === "function")
571
+ : typeof mod.middleware === "function"
572
+ ? [mod.middleware]
573
+ : [];
574
+
575
+ const cache = typeof mod.cache === "number" && mod.cache > 0 ? mod.cache : 0;
576
+ const seo = mod.seo !== undefined ? Boolean(mod.seo) : middlewares.length === 0;
577
+ const discoveredActions = { ...sharedActions };
578
+ if (mod.actions && typeof mod.actions === "object") {
579
+ Object.assign(discoveredActions, mod.actions);
580
+ }
581
+ for (const [exportKey, exportVal] of Object.entries(mod)) {
582
+ if (
583
+ exportVal &&
584
+ (typeof exportVal === "object" || typeof exportVal === "function") &&
585
+ (exportVal.__isBluebirdAction || exportVal.__bb_action__)
586
+ ) {
587
+ exportVal.__actionName = exportVal.__actionName || exportKey;
588
+ discoveredActions[exportKey] = exportVal;
589
+ }
590
+ }
591
+ const actions =
592
+ Object.keys(discoveredActions).length > 0
593
+ ? discoveredActions
594
+ : (typeof mod.actions === "function" ? mod.actions : null);
595
+
596
+ discovered.push({
597
+ viewName,
598
+ routePath,
599
+ cache,
600
+ middlewares,
601
+ seo,
602
+ actions,
603
+ module: mod,
604
+ });
605
+ }
606
+ }
607
+
608
+ await scanDir(scanRoot);
609
+ return discovered;
610
+ }
611
+ }
612
+
613
+ export default ViewLoader;