@seip/bluebird-js 0.1.7 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/AGENTS.md +727 -620
  2. package/README.md +670 -607
  3. package/app/models/user.js +19 -0
  4. package/app/resources/html/home.html +137 -0
  5. package/app/resources/html/layouts/main.html +55 -0
  6. package/app/resources/html/notFound.html +14 -0
  7. package/app/resources/html/table.html +15 -0
  8. package/app/resources/html/terms.html +46 -0
  9. package/app/resources/index.html +27 -0
  10. package/app/resources/layouts/AppLayout.jsx +92 -0
  11. package/app/resources/main.jsx +18 -0
  12. package/app/resources/pages/Dashboard.jsx +93 -0
  13. package/app/resources/pages/Home.jsx +140 -0
  14. package/app/resources/pages/Login.jsx +35 -0
  15. package/app/resources/pages/NotFound.jsx +16 -0
  16. package/app/resources/pages/Register.jsx +55 -0
  17. package/app/resources/pages/TableDemo.jsx +85 -0
  18. package/app/resources/routes.jsx +59 -0
  19. package/app/resources/spa.js +73 -0
  20. package/app/resources/styles.css +9 -0
  21. package/app/routes/api.js +129 -50
  22. package/app/routes/auth.js +209 -0
  23. package/app/routes/web.js +89 -47
  24. package/core/ai.js +30 -10
  25. package/core/app.d.ts +2 -18
  26. package/core/app.js +987 -801
  27. package/core/auth.d.ts +2 -13
  28. package/core/auth.js +444 -326
  29. package/core/cli/build.js +37 -0
  30. package/core/cli/dev.js +155 -0
  31. package/core/cli/doctor.js +37 -2
  32. package/core/cli/export.js +191 -0
  33. package/core/cli/init.js +91 -322
  34. package/core/cli/nginx.js +1 -1
  35. package/core/cli/templates.js +139 -0
  36. package/core/cli/view.js +98 -161
  37. package/core/config.js +44 -2
  38. package/core/csrf.js +156 -24
  39. package/core/database.js +1184 -1131
  40. package/core/debug.js +1 -1
  41. package/core/html.js +8 -1
  42. package/core/index.d.ts +126 -310
  43. package/core/paths.js +55 -0
  44. package/core/ratelimit.js +10 -1
  45. package/core/react/client/api.js +239 -0
  46. package/core/react/client/auth.js +236 -0
  47. package/core/react/client/components.js +1321 -0
  48. package/core/react/client/datatable.js +595 -0
  49. package/core/react/client/i18n.js +440 -0
  50. package/core/react/client/index.d.ts +314 -0
  51. package/core/react/client/index.js +50 -0
  52. package/core/react/client/router.js +26 -0
  53. package/core/react/client/theme.css +512 -0
  54. package/core/render-cache.js +250 -212
  55. package/core/render.d.ts +25 -21
  56. package/core/render.js +738 -736
  57. package/core/router.d.ts +2 -3
  58. package/core/router.js +171 -171
  59. package/core/seo.js +10 -0
  60. package/core/spa.js +599 -0
  61. package/core/view-loader.js +155 -613
  62. package/core/vite-plugin.d.ts +18 -0
  63. package/core/vite-plugin.js +162 -0
  64. package/core/vite.js +250 -145
  65. package/index.js +22 -18
  66. package/jsconfig.json +5 -3
  67. package/package.json +114 -92
  68. package/production.md +8 -3
  69. package/public/js/bluebird.js +1886 -0
  70. package/templates/_auth/app/database.js +19 -0
  71. package/templates/_auth/app/models/user.js +22 -0
  72. package/templates/_auth/app/routes/auth-router.js +304 -0
  73. package/templates/_base/app/resources/html/layouts/main.html +55 -0
  74. package/templates/_base/app/resources/html/notFound.html +14 -0
  75. package/templates/_base/app/resources/index.html +27 -0
  76. package/templates/_base/app/resources/styles.css +9 -0
  77. package/templates/api/app/models/note.js +18 -0
  78. package/templates/api/app/routes/api.js +82 -0
  79. package/templates/api/app/routes/auth.js +11 -0
  80. package/templates/api/index.js +19 -0
  81. package/templates/api/template.json +13 -0
  82. package/templates/auth/app/mail.js +11 -0
  83. package/templates/auth/app/models/password_reset.js +18 -0
  84. package/templates/auth/app/resources/html/home.html +21 -0
  85. package/templates/auth/app/resources/html/partials/nav.html +2 -0
  86. package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
  87. package/templates/auth/app/resources/main.jsx +18 -0
  88. package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
  89. package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
  90. package/templates/auth/app/resources/pages/Login.jsx +36 -0
  91. package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
  92. package/templates/auth/app/resources/pages/Profile.jsx +99 -0
  93. package/templates/auth/app/resources/pages/Register.jsx +50 -0
  94. package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
  95. package/templates/auth/app/resources/routes.jsx +54 -0
  96. package/templates/auth/app/resources/spa.js +29 -0
  97. package/templates/auth/app/routes/api.js +17 -0
  98. package/templates/auth/app/routes/auth.js +13 -0
  99. package/templates/auth/app/routes/web.js +21 -0
  100. package/templates/auth/index.js +19 -0
  101. package/templates/auth/template.json +15 -0
  102. package/templates/blank/app/models/.gitkeep +0 -0
  103. package/templates/blank/app/resources/html/home.html +27 -0
  104. package/templates/blank/app/resources/html/partials/nav.html +1 -0
  105. package/templates/blank/app/resources/main.jsx +16 -0
  106. package/templates/blank/app/resources/pages/Home.jsx +42 -0
  107. package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
  108. package/templates/blank/app/resources/routes.jsx +15 -0
  109. package/templates/blank/app/resources/spa.js +24 -0
  110. package/templates/blank/app/routes/api.js +11 -0
  111. package/templates/blank/app/routes/web.js +21 -0
  112. package/templates/blank/index.js +13 -0
  113. package/templates/blank/template.json +12 -0
  114. package/templates/blog/app/lib/blog.js +149 -0
  115. package/templates/blog/app/models/post.js +22 -0
  116. package/templates/blog/app/resources/html/home.html +28 -0
  117. package/templates/blog/app/resources/html/not-found.html +5 -0
  118. package/templates/blog/app/resources/html/partials/nav.html +2 -0
  119. package/templates/blog/app/resources/html/partials/post-card.html +9 -0
  120. package/templates/blog/app/resources/html/post.html +8 -0
  121. package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
  122. package/templates/blog/app/resources/main.jsx +18 -0
  123. package/templates/blog/app/resources/pages/Login.jsx +31 -0
  124. package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
  125. package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
  126. package/templates/blog/app/resources/pages/Posts.jsx +83 -0
  127. package/templates/blog/app/resources/pages/Register.jsx +43 -0
  128. package/templates/blog/app/resources/routes.jsx +51 -0
  129. package/templates/blog/app/resources/spa.js +25 -0
  130. package/templates/blog/app/resources/styles.css +40 -0
  131. package/templates/blog/app/routes/api.js +77 -0
  132. package/templates/blog/app/routes/auth.js +10 -0
  133. package/templates/blog/app/routes/web.js +114 -0
  134. package/templates/blog/index.js +21 -0
  135. package/templates/blog/template.json +14 -0
  136. package/vite.config.js +11 -0
  137. package/app/views/components/Header.jsx +0 -42
  138. package/app/views/components/LiveCounter.jsx +0 -67
  139. package/app/views/layouts/main/view.jsx +0 -201
  140. package/app/views/legal/terms.html +0 -29
  141. package/app/views/pages/about.jsx +0 -98
  142. package/app/views/pages/dashboard.jsx +0 -278
  143. package/app/views/pages/index.jsx +0 -123
  144. package/app/views/pages/login.jsx +0 -141
  145. package/core/actions.d.ts +0 -4
  146. package/core/actions.js +0 -355
  147. package/core/jsx.d.ts +0 -38
  148. package/core/jsx.js +0 -1597
  149. package/core/vite.d.ts +0 -3
  150. package/public/js/bluebird-client.js +0 -3265
  151. package/public/js/tailwind.js +0 -8
@@ -1,613 +1,155 @@
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;
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import Config from "./config.js";
4
+ import { PATHS } from "./paths.js";
5
+
6
+ const DEBUG = Config.props().debug;
7
+
8
+ /**
9
+ * Returns the base views directory relative to `Config.appDir()`.
10
+ * @returns {string}
11
+ */
12
+ function getViewsDir() {
13
+ return path.resolve(Config.appDir(), process.env.VIEWS_PATH || PATHS.html);
14
+ }
15
+
16
+ const fileCache = new Map();
17
+ const resolveCache = new Map();
18
+
19
+ /**
20
+ * Checks whether a candidate path stays inside the views directory.
21
+ * @param {string} candidatePath
22
+ * @returns {boolean}
23
+ */
24
+ function isSafePath(candidatePath) {
25
+ const viewsDir = getViewsDir();
26
+ const resolved = path.resolve(viewsDir, candidatePath);
27
+ return resolved === viewsDir || resolved.startsWith(viewsDir + path.sep);
28
+ }
29
+
30
+ /**
31
+ * Reads an HTML template file with production memoization and `.asar.unpacked` fallback.
32
+ * @param {string} fullPath
33
+ * @returns {{type: "html", filePath: string, content: string}}
34
+ */
35
+ function readHtmlFile(fullPath) {
36
+ if (!DEBUG && fileCache.has(fullPath)) return fileCache.get(fullPath);
37
+
38
+ let targetPath = fullPath;
39
+ if (fullPath.includes(".asar")) {
40
+ const unpacked = fullPath.replace(/\.asar(?=[\/\\]|$)/, ".asar.unpacked");
41
+ if (fs.existsSync(unpacked)) targetPath = unpacked;
42
+ }
43
+
44
+ const entry = { type: "html", filePath: fullPath, content: fs.readFileSync(targetPath, "utf-8") };
45
+ if (!DEBUG) fileCache.set(fullPath, entry);
46
+ return entry;
47
+ }
48
+
49
+ /**
50
+ * Resolver and loader for `.html` views, partials, and layouts inside `app/resources/html/`.
51
+ */
52
+ export class ViewLoader {
53
+ /**
54
+ * Returns the configured views base directory.
55
+ * @returns {string}
56
+ */
57
+ static getViewsDir() {
58
+ return getViewsDir();
59
+ }
60
+
61
+ /**
62
+ * Resolves the absolute file path of a view inside `app/resources/html/`.
63
+ * @param {string} viewName
64
+ * @returns {string|null}
65
+ */
66
+ static resolve(viewName) {
67
+ if (!viewName || typeof viewName !== "string") return null;
68
+ const viewsDir = getViewsDir();
69
+ const cacheKey = `${viewsDir}:${viewName}`;
70
+ const cached = resolveCache.get(cacheKey);
71
+ if (cached && (!DEBUG || fs.existsSync(cached))) return cached;
72
+
73
+ const raw = viewName.replace(/^\/+/, "");
74
+ const clean = raw.replace(/\.(html|htm)$/i, "");
75
+ const candidates = [
76
+ raw,
77
+ `${clean}.html`,
78
+ `${clean}/view.html`,
79
+ `${clean}/index.html`,
80
+ `partials/${clean}.html`,
81
+ `layouts/${clean}.html`,
82
+ ];
83
+
84
+ for (const candidate of candidates) {
85
+ if (!isSafePath(candidate)) continue;
86
+ const fullPath = path.resolve(viewsDir, candidate);
87
+ try {
88
+ if (fs.statSync(fullPath).isFile()) {
89
+ resolveCache.set(cacheKey, fullPath);
90
+ return fullPath;
91
+ }
92
+ } catch {}
93
+ }
94
+ return null;
95
+ }
96
+
97
+ /**
98
+ * Loads an HTML view by name.
99
+ * @param {string} viewName
100
+ * @returns {Promise<{type: "html", filePath: string, content: string}|null>}
101
+ */
102
+ static async load(viewName) {
103
+ const fullPath = ViewLoader.resolve(viewName);
104
+ if (!fullPath) return null;
105
+ return readHtmlFile(fullPath);
106
+ }
107
+
108
+ /**
109
+ * Loads a partial HTML file (`app/resources/html/partials/<name>.html` or `<name>.html`).
110
+ * @param {string} partialName
111
+ * @returns {Promise<{type: "html", filePath: string, content: string}|null>}
112
+ */
113
+ static async loadPartial(partialName) {
114
+ if (!partialName || typeof partialName !== "string") return null;
115
+ const clean = partialName.replace(/^\/+/, "").replace(/\.(html|htm)$/i, "");
116
+ const viewsDir = getViewsDir();
117
+ for (const candidate of [`partials/${clean}.html`, `${clean}.html`, `${clean}/view.html`]) {
118
+ if (!isSafePath(candidate)) continue;
119
+ const fullPath = path.resolve(viewsDir, candidate);
120
+ try {
121
+ if (fs.statSync(fullPath).isFile()) return readHtmlFile(fullPath);
122
+ } catch {}
123
+ }
124
+ return null;
125
+ }
126
+
127
+ /**
128
+ * Loads an HTML layout (`app/resources/html/layouts/<name>.html`).
129
+ * @param {string} layoutName
130
+ * @returns {Promise<{type: "html", filePath: string, content: string}|null>}
131
+ */
132
+ static async loadLayout(layoutName) {
133
+ if (!layoutName || typeof layoutName !== "string") return null;
134
+ const clean = layoutName.replace(/^\/+/, "").replace(/\.(html|htm)$/i, "");
135
+ const viewsDir = getViewsDir();
136
+ for (const candidate of [`layouts/${clean}.html`, `layouts/${clean}/view.html`, `layouts/${clean}/index.html`]) {
137
+ if (!isSafePath(candidate)) continue;
138
+ const fullPath = path.resolve(viewsDir, candidate);
139
+ try {
140
+ if (fs.statSync(fullPath).isFile()) return readHtmlFile(fullPath);
141
+ } catch {}
142
+ }
143
+ return null;
144
+ }
145
+
146
+ /**
147
+ * Clears in-memory file and resolution caches.
148
+ */
149
+ static clearCache() {
150
+ fileCache.clear();
151
+ resolveCache.clear();
152
+ }
153
+ }
154
+
155
+ export default ViewLoader;