@seip/bluebird-js 0.0.0-stage → 0.0.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.
- package/.env_example +54 -0
- package/AGENTS.md +403 -0
- package/LICENSE +21 -0
- package/README.md +284 -2
- package/app/routes/api.js +50 -0
- package/app/routes/web.js +53 -0
- package/app/views/about.html +161 -0
- package/app/views/dashboard.html +140 -0
- package/app/views/index.html +150 -0
- package/app/views/login.html +144 -0
- package/core/app.d.ts +18 -0
- package/core/app.js +644 -0
- package/core/auth.d.ts +13 -0
- package/core/auth.js +326 -0
- package/core/cache.d.ts +17 -0
- package/core/cache.js +475 -0
- package/core/cli/doctor.js +287 -0
- package/core/cli/ecosystem.js +162 -0
- package/core/cli/init.js +779 -0
- package/core/cli/migrate.js +541 -0
- package/core/cli/model.js +66 -0
- package/core/cli/nginx.js +199 -0
- package/core/cli/route.js +121 -0
- package/core/cli/swagger.js +45 -0
- package/core/cli/view.js +77 -0
- package/core/config.d.ts +3 -0
- package/core/config.js +111 -0
- package/core/csrf.d.ts +3 -0
- package/core/csrf.js +114 -0
- package/core/database.d.ts +15 -0
- package/core/database.js +636 -0
- package/core/debug.d.ts +3 -0
- package/core/debug.js +250 -0
- package/core/hash.d.ts +3 -0
- package/core/hash.js +194 -0
- package/core/index.d.ts +1071 -0
- package/core/logger.d.ts +3 -0
- package/core/logger.js +124 -0
- package/core/middleware.d.ts +3 -0
- package/core/middleware.js +28 -0
- package/core/model.d.ts +19 -0
- package/core/model.js +600 -0
- package/core/queue.d.ts +13 -0
- package/core/queue.js +172 -0
- package/core/ratelimit.d.ts +3 -0
- package/core/ratelimit.js +145 -0
- package/core/redis.d.ts +21 -0
- package/core/redis.js +230 -0
- package/core/render.d.ts +3 -0
- package/core/render.js +676 -0
- package/core/router.d.ts +3 -0
- package/core/router.js +171 -0
- package/core/seo.d.ts +3 -0
- package/core/seo.js +106 -0
- package/core/swagger.d.ts +3 -0
- package/core/swagger.js +60 -0
- package/core/upload.d.ts +13 -0
- package/core/upload.js +102 -0
- package/core/util/colors.js +82 -0
- package/core/validate.d.ts +15 -0
- package/core/validate.js +364 -0
- package/core/vite.d.ts +3 -0
- package/core/vite.js +145 -0
- package/core/ws.d.ts +13 -0
- package/core/ws.js +245 -0
- package/index.js +18 -0
- package/jsconfig.json +15 -0
- package/package.json +84 -3
- package/production.md +273 -0
- package/public/css/bluebird.min.css +2 -0
- package/public/images/favicon.ico +0 -0
- package/public/js/bluebird-client.js +1663 -0
- package/public/js/bluebird.min.js +1073 -0
package/core/render.js
ADDED
|
@@ -0,0 +1,676 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { getRedisClient } from "./cache.js";
|
|
4
|
+
import Config from "./config.js";
|
|
5
|
+
import Vite from "./vite.js";
|
|
6
|
+
|
|
7
|
+
const props = Config.props();
|
|
8
|
+
const DEBUG = props.debug;
|
|
9
|
+
const PM2_INSTANCES = parseInt(process.env.PM2_INSTANCES || "1", 10);
|
|
10
|
+
const RENDER_CACHE_MAX = parseInt(process.env.RENDER_CACHE_MAX || "500", 10);
|
|
11
|
+
const RENDER_CACHE_TTL = parseInt(process.env.RENDER_CACHE_TTL || "300", 10);
|
|
12
|
+
const VIEWS_DIR = path.join(process.cwd(), process.env.VIEWS_PATH || "app/views");
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Resolves the writable render file cache directory.
|
|
16
|
+
* @returns {string}
|
|
17
|
+
*/
|
|
18
|
+
function getFileCacheDir() {
|
|
19
|
+
return path.join(Config.userDataDir(), "app/cache");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const isMultiInstance = PM2_INSTANCES > 1;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* In-memory LRU cache for rendered route HTML strings.
|
|
26
|
+
* @type {Map<string, {html: string, expiry: number}>}
|
|
27
|
+
*/
|
|
28
|
+
const lru = new Map();
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* In-memory template file cache (L0) to avoid disk I/O on dynamic uncached routes in production.
|
|
32
|
+
* @type {Map<string, {content: string, ext: string}>}
|
|
33
|
+
*/
|
|
34
|
+
const templateMemoryCache = new Map();
|
|
35
|
+
|
|
36
|
+
let fileCacheEnabled = false;
|
|
37
|
+
|
|
38
|
+
if (!DEBUG) {
|
|
39
|
+
try {
|
|
40
|
+
const cacheDir = getFileCacheDir();
|
|
41
|
+
fs.mkdirSync(cacheDir, { recursive: true });
|
|
42
|
+
fs.accessSync(cacheDir, fs.constants.W_OK);
|
|
43
|
+
fileCacheEnabled = true;
|
|
44
|
+
} catch {
|
|
45
|
+
console.warn("[RENDER] app/cache/ is not writable — file cache disabled.");
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Evicts the oldest LRU entry when the cap is exceeded.
|
|
51
|
+
*/
|
|
52
|
+
function evictLru() {
|
|
53
|
+
if (lru.size >= RENDER_CACHE_MAX) {
|
|
54
|
+
const key = lru.keys().next().value;
|
|
55
|
+
if (key !== undefined) lru.delete(key);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Returns a safe filesystem key derived from the cache key string.
|
|
61
|
+
* @param {string} key
|
|
62
|
+
* @returns {string}
|
|
63
|
+
*/
|
|
64
|
+
function toCacheFileName(key) {
|
|
65
|
+
return key.replace(/[^a-z0-9_-]/gi, "_").substring(0, 200) + ".html";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Reads an HTML string from the file cache, respecting TTL.
|
|
70
|
+
* @param {string} key
|
|
71
|
+
* @returns {string|null}
|
|
72
|
+
*/
|
|
73
|
+
function readFileCache(key) {
|
|
74
|
+
if (!fileCacheEnabled) return null;
|
|
75
|
+
const file = path.join(getFileCacheDir(), toCacheFileName(key));
|
|
76
|
+
try {
|
|
77
|
+
const stats = fs.statSync(file);
|
|
78
|
+
const age = (Date.now() - stats.mtimeMs) / 1000;
|
|
79
|
+
if (age > RENDER_CACHE_TTL) return null;
|
|
80
|
+
return fs.readFileSync(file, "utf8");
|
|
81
|
+
} catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Writes an HTML string to the file cache.
|
|
88
|
+
* @param {string} key
|
|
89
|
+
* @param {string} html
|
|
90
|
+
*/
|
|
91
|
+
function writeFileCache(key, html) {
|
|
92
|
+
if (!fileCacheEnabled) return;
|
|
93
|
+
try {
|
|
94
|
+
const file = path.join(getFileCacheDir(), toCacheFileName(key));
|
|
95
|
+
fs.writeFileSync(file, html, "utf8");
|
|
96
|
+
} catch {}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Resolves a dot-notation key against a data object.
|
|
101
|
+
* @param {Object} obj
|
|
102
|
+
* @param {string} keyPath
|
|
103
|
+
* @returns {any}
|
|
104
|
+
*/
|
|
105
|
+
function resolvePath(obj, keyPath) {
|
|
106
|
+
if (!obj || typeof obj !== "object" || !keyPath) return undefined;
|
|
107
|
+
if (keyPath === "this" || keyPath === ".") return obj.this !== undefined ? obj.this : obj;
|
|
108
|
+
return keyPath.split(".").reduce((acc, k) => (acc && acc[k] !== undefined ? acc[k] : undefined), obj);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Escapes HTML special characters to prevent XSS in interpolated values.
|
|
113
|
+
* @param {string} str
|
|
114
|
+
* @returns {string}
|
|
115
|
+
*/
|
|
116
|
+
function escapeHtml(str) {
|
|
117
|
+
return str
|
|
118
|
+
.replace(/&/g, "&")
|
|
119
|
+
.replace(/</g, "<")
|
|
120
|
+
.replace(/>/g, ">")
|
|
121
|
+
.replace(/"/g, """)
|
|
122
|
+
.replace(/'/g, "'");
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Parses inline partial/component arguments like: title="Hello" count=10 user=currentUser
|
|
127
|
+
* @param {string} argsStr
|
|
128
|
+
* @param {Object} scopeData
|
|
129
|
+
* @returns {Object}
|
|
130
|
+
*/
|
|
131
|
+
function parsePartialProps(argsStr, scopeData) {
|
|
132
|
+
const propsObj = {};
|
|
133
|
+
if (!argsStr || !argsStr.trim()) return propsObj;
|
|
134
|
+
|
|
135
|
+
const propRegex = /([a-zA-Z0-9_$-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"']+))/g;
|
|
136
|
+
let match;
|
|
137
|
+
while ((match = propRegex.exec(argsStr)) !== null) {
|
|
138
|
+
const key = match[1];
|
|
139
|
+
if (match[2] !== undefined) {
|
|
140
|
+
propsObj[key] = match[2];
|
|
141
|
+
} else if (match[3] !== undefined) {
|
|
142
|
+
propsObj[key] = match[3];
|
|
143
|
+
} else if (match[4] !== undefined) {
|
|
144
|
+
const rawVal = match[4];
|
|
145
|
+
if (rawVal === "true") propsObj[key] = true;
|
|
146
|
+
else if (rawVal === "false") propsObj[key] = false;
|
|
147
|
+
else if (rawVal === "null") propsObj[key] = null;
|
|
148
|
+
else if (!Number.isNaN(Number(rawVal)) && rawVal.trim() !== "") propsObj[key] = Number(rawVal);
|
|
149
|
+
else propsObj[key] = resolvePath(scopeData, rawVal);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return propsObj;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Evaluates a conditional expression from {{#if expr}} against the current scope.
|
|
157
|
+
* Supports negation (!expr) and simple equality (a == "b").
|
|
158
|
+
* @param {string} expr
|
|
159
|
+
* @param {Object} data
|
|
160
|
+
* @returns {boolean}
|
|
161
|
+
*/
|
|
162
|
+
function evaluateCondition(expr, data) {
|
|
163
|
+
const clean = expr.trim();
|
|
164
|
+
if (!clean) return false;
|
|
165
|
+
|
|
166
|
+
if (clean.startsWith("!")) {
|
|
167
|
+
return !evaluateCondition(clean.slice(1), data);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const eqMatch = clean.match(/^([\w.]+)\s*(===|==|!==|!=)\s*(?:"([^"]*)"|'([^']*)'|(\S+))$/);
|
|
171
|
+
if (eqMatch) {
|
|
172
|
+
const leftVal = resolvePath(data, eqMatch[1]);
|
|
173
|
+
const op = eqMatch[2];
|
|
174
|
+
let rightVal;
|
|
175
|
+
if (eqMatch[3] !== undefined) rightVal = eqMatch[3];
|
|
176
|
+
else if (eqMatch[4] !== undefined) rightVal = eqMatch[4];
|
|
177
|
+
else {
|
|
178
|
+
const raw = eqMatch[5];
|
|
179
|
+
if (raw === "true") rightVal = true;
|
|
180
|
+
else if (raw === "false") rightVal = false;
|
|
181
|
+
else if (raw === "null") rightVal = null;
|
|
182
|
+
else if (!Number.isNaN(Number(raw))) rightVal = Number(raw);
|
|
183
|
+
else rightVal = resolvePath(data, raw);
|
|
184
|
+
}
|
|
185
|
+
if (op === "===" || op === "==") return leftVal == rightVal;
|
|
186
|
+
if (op === "!==" || op === "!=") return leftVal != rightVal;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const val = resolvePath(data, clean);
|
|
190
|
+
if (Array.isArray(val)) return val.length > 0;
|
|
191
|
+
return Boolean(val);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Reads a view, partial, or layout file from disk (or L0 memory cache in production).
|
|
196
|
+
* Searches direct path, partials/<name>, components/<name>, and layouts/<name>.
|
|
197
|
+
* @param {string} viewName
|
|
198
|
+
* @returns {{content: string, ext: string}|null}
|
|
199
|
+
*/
|
|
200
|
+
function readViewFile(viewName) {
|
|
201
|
+
if (!DEBUG && templateMemoryCache.has(viewName)) {
|
|
202
|
+
return templateMemoryCache.get(viewName);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const cleanName = viewName.replace(/^\/+/, "");
|
|
206
|
+
const candidates = [
|
|
207
|
+
cleanName,
|
|
208
|
+
path.join("partials", cleanName),
|
|
209
|
+
path.join("components", cleanName),
|
|
210
|
+
path.join("layouts", cleanName),
|
|
211
|
+
];
|
|
212
|
+
|
|
213
|
+
for (const candidate of candidates) {
|
|
214
|
+
const htmlPath = path.join(VIEWS_DIR, `${candidate}.html`);
|
|
215
|
+
if (fs.existsSync(htmlPath)) {
|
|
216
|
+
const result = { content: fs.readFileSync(htmlPath, "utf8"), ext: "html" };
|
|
217
|
+
if (!DEBUG) templateMemoryCache.set(viewName, result);
|
|
218
|
+
return result;
|
|
219
|
+
}
|
|
220
|
+
const ejsPath = path.join(VIEWS_DIR, `${candidate}.ejs`);
|
|
221
|
+
if (fs.existsSync(ejsPath)) {
|
|
222
|
+
const result = { content: fs.readFileSync(ejsPath, "utf8"), ext: "ejs" };
|
|
223
|
+
if (!DEBUG) templateMemoryCache.set(viewName, result);
|
|
224
|
+
return result;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Processes loops ({{#each}}), conditionals ({{#if}}), partials ({{> name props}}),
|
|
233
|
+
* and variable interpolations ({{{raw}}} and {{escaped}}) in an HTML template string.
|
|
234
|
+
* @param {string} html - Raw HTML template string.
|
|
235
|
+
* @param {Object} data - Key-value pairs to inject.
|
|
236
|
+
* @param {number} [depth=0] - Recursion depth guard for nested partials.
|
|
237
|
+
* @returns {string} Interpolated HTML.
|
|
238
|
+
*/
|
|
239
|
+
function interpolate(html, data, depth = 0) {
|
|
240
|
+
if (!html || typeof html !== "string") return "";
|
|
241
|
+
if (!data || typeof data !== "object") data = {};
|
|
242
|
+
if (depth > 15) return html;
|
|
243
|
+
|
|
244
|
+
let result = html;
|
|
245
|
+
|
|
246
|
+
const eachRegex = /\{\{#each\s+([\w.]+)(?:\s+as\s+(\w+))?(?:\s*,\s*(\w+))?\s*\}\}([\s\S]*?)\{\{\/each\}\}/g;
|
|
247
|
+
let safetyCounter = 0;
|
|
248
|
+
while (eachRegex.test(result) && safetyCounter++ < 50) {
|
|
249
|
+
result = result.replace(eachRegex, (_, listKey, itemVar, indexVar, innerBlock) => {
|
|
250
|
+
const list = resolvePath(data, listKey);
|
|
251
|
+
if (!Array.isArray(list) || list.length === 0) return "";
|
|
252
|
+
return list
|
|
253
|
+
.map((item, idx) => {
|
|
254
|
+
const itemScope = {
|
|
255
|
+
...data,
|
|
256
|
+
this: item,
|
|
257
|
+
"@index": idx,
|
|
258
|
+
"@first": idx === 0,
|
|
259
|
+
"@last": idx === list.length - 1,
|
|
260
|
+
};
|
|
261
|
+
if (typeof item === "object" && item !== null && !itemVar) {
|
|
262
|
+
Object.assign(itemScope, item);
|
|
263
|
+
}
|
|
264
|
+
if (itemVar) {
|
|
265
|
+
itemScope[itemVar] = item;
|
|
266
|
+
itemScope[`${itemVar}_index`] = idx;
|
|
267
|
+
}
|
|
268
|
+
if (indexVar) itemScope[indexVar] = idx;
|
|
269
|
+
return interpolate(innerBlock, itemScope, depth + 1);
|
|
270
|
+
})
|
|
271
|
+
.join("");
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const ifRegex = /\{\{#if\s+([^}]+)\}\}((?:(?!\{\{#if\b)[\s\S])*?)\{\{\/if\}\}/g;
|
|
276
|
+
safetyCounter = 0;
|
|
277
|
+
while (ifRegex.test(result) && safetyCounter++ < 50) {
|
|
278
|
+
result = result.replace(ifRegex, (_, conditionExpr, innerContent) => {
|
|
279
|
+
const parts = innerContent.split(/\{\{\s*else\s*\}\}/);
|
|
280
|
+
const trueBranch = parts[0] || "";
|
|
281
|
+
const falseBranch = parts[1] || "";
|
|
282
|
+
const isTruthy = evaluateCondition(conditionExpr, data);
|
|
283
|
+
return interpolate(isTruthy ? trueBranch : falseBranch, data, depth + 1);
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
result = result.replace(/\{\{>\s*([a-zA-Z0-9_/-]+)((?:\s+[^}]*)?)\}\}/g, (_, partialName, argsStr) => {
|
|
288
|
+
const partialView = readViewFile(partialName.trim());
|
|
289
|
+
if (!partialView) return "";
|
|
290
|
+
const inlineProps = parsePartialProps(argsStr, data);
|
|
291
|
+
const partialScope = { ...data, ...inlineProps };
|
|
292
|
+
return interpolate(partialView.content, partialScope, depth + 1);
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
result = result.replace(/\{\{\{\s*([\w.@]+)\s*\}\}\}/g, (_, key) => {
|
|
296
|
+
const val = key.startsWith("@") ? data[key] : resolvePath(data, key);
|
|
297
|
+
if (val === undefined || val === null) return "";
|
|
298
|
+
if (typeof val === "object") {
|
|
299
|
+
try {
|
|
300
|
+
return JSON.stringify(val);
|
|
301
|
+
} catch {
|
|
302
|
+
return String(val);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return String(val);
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
result = result.replace(/\{\{\s*([\w.@]+)\s*\}\}/g, (_, key) => {
|
|
309
|
+
const val = key.startsWith("@") ? data[key] : resolvePath(data, key);
|
|
310
|
+
if (val === undefined || val === null) return "";
|
|
311
|
+
if (typeof val === "object") {
|
|
312
|
+
try {
|
|
313
|
+
return escapeHtml(JSON.stringify(val));
|
|
314
|
+
} catch {
|
|
315
|
+
return escapeHtml(String(val));
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return escapeHtml(String(val));
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
return result;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Looks up a rendered HTML string from L1 (memory LRU), L2 (Redis), or L3 (file).
|
|
326
|
+
* @param {string} key
|
|
327
|
+
* @returns {Promise<string|null>}
|
|
328
|
+
*/
|
|
329
|
+
async function lookupCache(key) {
|
|
330
|
+
const entry = lru.get(key);
|
|
331
|
+
if (entry && entry.expiry > Date.now()) {
|
|
332
|
+
lru.delete(key);
|
|
333
|
+
lru.set(key, entry);
|
|
334
|
+
return entry.html;
|
|
335
|
+
}
|
|
336
|
+
if (entry) lru.delete(key);
|
|
337
|
+
|
|
338
|
+
if (isMultiInstance) {
|
|
339
|
+
const redis = getRedisClient();
|
|
340
|
+
if (redis) {
|
|
341
|
+
try {
|
|
342
|
+
const val = await redis.get(`render:${key}`);
|
|
343
|
+
if (val) {
|
|
344
|
+
evictLru();
|
|
345
|
+
lru.set(key, { html: val, expiry: Date.now() + RENDER_CACHE_TTL * 1000 });
|
|
346
|
+
return val;
|
|
347
|
+
}
|
|
348
|
+
} catch {}
|
|
349
|
+
} else {
|
|
350
|
+
const fromFile = readFileCache(key);
|
|
351
|
+
if (fromFile) {
|
|
352
|
+
evictLru();
|
|
353
|
+
lru.set(key, { html: fromFile, expiry: Date.now() + RENDER_CACHE_TTL * 1000 });
|
|
354
|
+
return fromFile;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Stores a rendered HTML string in all available cache layers.
|
|
364
|
+
* @param {string} key
|
|
365
|
+
* @param {string} html
|
|
366
|
+
* @param {number} [ttl=RENDER_CACHE_TTL]
|
|
367
|
+
* @returns {Promise<void>}
|
|
368
|
+
*/
|
|
369
|
+
async function storeCache(key, html, ttl = RENDER_CACHE_TTL) {
|
|
370
|
+
evictLru();
|
|
371
|
+
lru.set(key, { html, expiry: Date.now() + ttl * 1000 });
|
|
372
|
+
|
|
373
|
+
if (isMultiInstance) {
|
|
374
|
+
const redis = getRedisClient();
|
|
375
|
+
if (redis) {
|
|
376
|
+
try {
|
|
377
|
+
await redis.set(`render:${key}`, html, { EX: ttl });
|
|
378
|
+
return;
|
|
379
|
+
} catch {}
|
|
380
|
+
}
|
|
381
|
+
writeFileCache(key, html);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* HTML render engine for Bluebird.
|
|
387
|
+
*
|
|
388
|
+
* Features:
|
|
389
|
+
* - L0 In-Memory Template Caching (zero disk I/O in production even for dynamic routes)
|
|
390
|
+
* - Built-in Partials & Server Components: {{> card title="Users" count=stats.users }}
|
|
391
|
+
* - Shared Layouts: {{!< main }} at top of view or { _layout: "main" }
|
|
392
|
+
* - Loops & Conditionals: {{#each items as item}}...{{/each}} and {{#if cond}}...{{else}}...{{/if}}
|
|
393
|
+
* - Fragment / Partial responses for SPA & Dashboard updates: Render.partial()
|
|
394
|
+
* - React Islands helper: Render.island()
|
|
395
|
+
*/
|
|
396
|
+
class Render {
|
|
397
|
+
/**
|
|
398
|
+
* Generates a declarative HTML placeholder for a client-side React Island.
|
|
399
|
+
* @param {string} name - Island component name.
|
|
400
|
+
* @param {Object} [props={}] - Initial props passed to the component.
|
|
401
|
+
* @param {Object} [options={}] - Island options.
|
|
402
|
+
* @param {boolean} [options.persist=false] - Whether to preserve the island across page navigation.
|
|
403
|
+
* @param {string} [options.fallback=""] - HTML fallback content displayed before hydration.
|
|
404
|
+
* @param {string} [options.tag="div"] - HTML tag name.
|
|
405
|
+
* @returns {string} Declarative HTML markup.
|
|
406
|
+
*/
|
|
407
|
+
static island(name, props = {}, options = {}) {
|
|
408
|
+
const tag = options.tag || "div";
|
|
409
|
+
const persistAttr = options.persist ? ' data-persist="true"' : "";
|
|
410
|
+
const serializedProps = escapeHtml(JSON.stringify(props));
|
|
411
|
+
const fallback = options.fallback || "";
|
|
412
|
+
return `<${tag} data-island="${escapeHtml(name)}" data-props="${serializedProps}"${persistAttr}>${fallback}</${tag}>`;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Renders a partial/component or view to a raw HTML string synchronously from memory/disk.
|
|
417
|
+
* Can be used to compose components or generate HTML for emails and WebSockets.
|
|
418
|
+
* @param {string} viewName - Partial or view name (e.g. "partials/card" or "card").
|
|
419
|
+
* @param {Object} [data={}] - Props/data to interpolate.
|
|
420
|
+
* @returns {string} Rendered HTML string.
|
|
421
|
+
*/
|
|
422
|
+
static component(viewName, data = {}) {
|
|
423
|
+
const view = readViewFile(viewName);
|
|
424
|
+
if (!view) return "";
|
|
425
|
+
return interpolate(view.content, { bluebirdHead: Vite.tags(), ...data });
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* Sends a rendered HTML partial fragment without wrapping in a layout.
|
|
430
|
+
* Ideal for dynamic dashboard updates and AJAX/fetch partial swaps.
|
|
431
|
+
* @param {import('express').Response} res - Express response object.
|
|
432
|
+
* @param {string} partialName - Partial view name (e.g. "partials/table" or "user-card").
|
|
433
|
+
* @param {Object} [data={}] - Data to interpolate into the partial.
|
|
434
|
+
* @returns {Promise<any>}
|
|
435
|
+
*/
|
|
436
|
+
static async partial(res, partialName, data = {}) {
|
|
437
|
+
return this.send(res, partialName, { ...data, _layout: false });
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Sends a rendered HTML response from app/views/<viewName>.html.
|
|
442
|
+
* Supports shared layouts ({{!< layoutName}} or data._layout) and automatic partial responses
|
|
443
|
+
* when requested with the X-Bluebird-Partial header.
|
|
444
|
+
* @param {import('express').Response} res - Express response object.
|
|
445
|
+
* @param {string} viewName - View file name without extension (e.g., "index", "dashboard").
|
|
446
|
+
* @param {Object} [data={}] - Data to interpolate into the template.
|
|
447
|
+
* @param {number} [ttl] - Optional route cache TTL in seconds when static.
|
|
448
|
+
* @returns {Promise<any>}
|
|
449
|
+
*/
|
|
450
|
+
static async send(res, viewName, data = {}, ttl) {
|
|
451
|
+
const locals = res.locals || {};
|
|
452
|
+
const appLocals = res.req?.app?.locals || {};
|
|
453
|
+
const isPartialRequest =
|
|
454
|
+
data._layout === false ||
|
|
455
|
+
res.req?.headers?.["x-bluebird-partial"] === "1" ||
|
|
456
|
+
res.req?.query?._partial === "1";
|
|
457
|
+
|
|
458
|
+
const mergedData = {
|
|
459
|
+
bluebirdHead: Vite.tags(),
|
|
460
|
+
...appLocals,
|
|
461
|
+
...locals,
|
|
462
|
+
...data,
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
const view = readViewFile(viewName);
|
|
466
|
+
if (!view) {
|
|
467
|
+
return res.status(404).json({ message: `View '${viewName}' not found.` });
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
let rendered;
|
|
471
|
+
|
|
472
|
+
if (view.ext === "ejs") {
|
|
473
|
+
try {
|
|
474
|
+
const ejs = await import("ejs");
|
|
475
|
+
rendered = await ejs.render(view.content, mergedData, { async: true });
|
|
476
|
+
} catch {
|
|
477
|
+
return res.status(500).json({ message: "EJS is not installed. Run: npm install ejs" });
|
|
478
|
+
}
|
|
479
|
+
} else {
|
|
480
|
+
let rawTemplate = view.content;
|
|
481
|
+
let layoutName = data._layout || null;
|
|
482
|
+
|
|
483
|
+
const layoutDirective = rawTemplate.match(/^\s*\{\{!<\s*([a-zA-Z0-9_/-]+)\s*\}\}\s*/);
|
|
484
|
+
if (layoutDirective) {
|
|
485
|
+
rawTemplate = rawTemplate.slice(layoutDirective[0].length);
|
|
486
|
+
if (layoutName === null) {
|
|
487
|
+
layoutName = layoutDirective[1].trim();
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
const bodyHtml = interpolate(rawTemplate, mergedData);
|
|
492
|
+
|
|
493
|
+
if (layoutName && !isPartialRequest) {
|
|
494
|
+
const layoutView = readViewFile(layoutName);
|
|
495
|
+
if (layoutView) {
|
|
496
|
+
rendered = interpolate(layoutView.content, {
|
|
497
|
+
...mergedData,
|
|
498
|
+
body: bodyHtml,
|
|
499
|
+
content: bodyHtml,
|
|
500
|
+
});
|
|
501
|
+
} else {
|
|
502
|
+
rendered = bodyHtml;
|
|
503
|
+
}
|
|
504
|
+
} else {
|
|
505
|
+
rendered = bodyHtml;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
if (ttl !== undefined && ttl > 0 && !DEBUG) {
|
|
510
|
+
const cacheKey = `view:${viewName}`;
|
|
511
|
+
await storeCache(cacheKey, rendered, ttl);
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
res.set("Content-Type", "text/html; charset=utf-8");
|
|
515
|
+
if (isPartialRequest) {
|
|
516
|
+
res.set("X-Bluebird-Partial", "1");
|
|
517
|
+
}
|
|
518
|
+
res.set("X-Bluebird-Cache", "MISS");
|
|
519
|
+
return res.send(rendered);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Streams a rendered HTML view in chunks, resolving async data promises progressively.
|
|
524
|
+
* Flushes the head/shell immediately for faster First Contentful Paint (FCP) on heavy dashboards.
|
|
525
|
+
* @param {import('express').Response} res - Express response object.
|
|
526
|
+
* @param {string} viewName - View file name.
|
|
527
|
+
* @param {Object} [data={}] - Data object (values may be Promises).
|
|
528
|
+
* @returns {Promise<void>}
|
|
529
|
+
*/
|
|
530
|
+
static async stream(res, viewName, data = {}) {
|
|
531
|
+
const view = readViewFile(viewName);
|
|
532
|
+
if (!view) {
|
|
533
|
+
res.status(404).json({ message: `View '${viewName}' not found.` });
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
538
|
+
res.setHeader("Transfer-Encoding", "chunked");
|
|
539
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
540
|
+
|
|
541
|
+
const resolvedData = {};
|
|
542
|
+
const entries = Object.entries(data);
|
|
543
|
+
await Promise.all(
|
|
544
|
+
entries.map(async ([k, v]) => {
|
|
545
|
+
resolvedData[k] = v instanceof Promise || (v && typeof v.then === "function") ? await v : v;
|
|
546
|
+
})
|
|
547
|
+
);
|
|
548
|
+
|
|
549
|
+
const locals = res.locals || {};
|
|
550
|
+
const appLocals = res.req?.app?.locals || {};
|
|
551
|
+
const mergedData = {
|
|
552
|
+
bluebirdHead: Vite.tags(),
|
|
553
|
+
...appLocals,
|
|
554
|
+
...locals,
|
|
555
|
+
...resolvedData,
|
|
556
|
+
};
|
|
557
|
+
|
|
558
|
+
const html = interpolate(view.content, mergedData);
|
|
559
|
+
const headCloseIdx = html.indexOf("</head>");
|
|
560
|
+
if (headCloseIdx !== -1) {
|
|
561
|
+
const headChunk = html.slice(0, headCloseIdx + 7);
|
|
562
|
+
const bodyChunk = html.slice(headCloseIdx + 7);
|
|
563
|
+
res.write(headChunk);
|
|
564
|
+
res.write(bodyChunk);
|
|
565
|
+
res.end();
|
|
566
|
+
} else {
|
|
567
|
+
res.write(html);
|
|
568
|
+
res.end();
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* Returns an Express route handler that renders a view.
|
|
574
|
+
* Designed to be used directly as a route callback.
|
|
575
|
+
* @param {string} viewName - View file name without extension.
|
|
576
|
+
* @param {Object} [staticData={}] - Static data merged before request-time data.
|
|
577
|
+
* @returns {Function} Express route handler (req, res) => void.
|
|
578
|
+
* @example
|
|
579
|
+
* web.get("/", Render.view("index"));
|
|
580
|
+
* web.get("/about", Render.view("about", { company: "Blue Bird" }));
|
|
581
|
+
*/
|
|
582
|
+
static view(viewName, staticData = {}) {
|
|
583
|
+
return (req, res) => Render.send(res, viewName, staticData);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Express middleware that caches the full rendered HTML response for a route.
|
|
588
|
+
* Respects partial requests by separating full-page and partial cache keys.
|
|
589
|
+
* @param {number} [seconds] - Cache duration in seconds (defaults to RENDER_CACHE_TTL env).
|
|
590
|
+
* @returns {Function} Express middleware.
|
|
591
|
+
* @example
|
|
592
|
+
* web.get("/dashboard", Auth.protect(), Render.cache(600), Render.view("dashboard"));
|
|
593
|
+
*/
|
|
594
|
+
static cache(seconds) {
|
|
595
|
+
const ttl = seconds ?? RENDER_CACHE_TTL;
|
|
596
|
+
|
|
597
|
+
return async (req, res, next) => {
|
|
598
|
+
if (DEBUG || req.method !== "GET") return next();
|
|
599
|
+
|
|
600
|
+
const isPartial = req.headers?.["x-bluebird-partial"] === "1" || req.query?._partial === "1";
|
|
601
|
+
const key = `route:${isPartial ? "partial:" : ""}${req.originalUrl}`;
|
|
602
|
+
const cached = await lookupCache(key);
|
|
603
|
+
if (cached) {
|
|
604
|
+
res.set("Content-Type", "text/html; charset=utf-8");
|
|
605
|
+
res.set("X-Bluebird-Cache", "HIT");
|
|
606
|
+
return res.send(cached);
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
const originalSend = res.send.bind(res);
|
|
610
|
+
res.send = async (body) => {
|
|
611
|
+
if (typeof body === "string" && res.statusCode === 200) {
|
|
612
|
+
await storeCache(key, body, ttl);
|
|
613
|
+
}
|
|
614
|
+
res.set("X-Bluebird-Cache", "MISS");
|
|
615
|
+
return originalSend(body);
|
|
616
|
+
};
|
|
617
|
+
|
|
618
|
+
next();
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* Clears the L0 in-memory raw template cache.
|
|
624
|
+
* @returns {void}
|
|
625
|
+
*/
|
|
626
|
+
static clearTemplateCache() {
|
|
627
|
+
templateMemoryCache.clear();
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* Invalidates the render cache for one or more view names or route URLs.
|
|
632
|
+
* Also clears L0 template memory cache entries.
|
|
633
|
+
* @param {string|string[]} [keys] - View names or route URLs to invalidate. If omitted, clears all template cache.
|
|
634
|
+
* @returns {Promise<void>}
|
|
635
|
+
*/
|
|
636
|
+
static async invalidate(keys) {
|
|
637
|
+
if (!keys) {
|
|
638
|
+
lru.clear();
|
|
639
|
+
templateMemoryCache.clear();
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
const list = Array.isArray(keys) ? keys : [keys];
|
|
644
|
+
for (const key of list) {
|
|
645
|
+
const viewKey = `view:${key}`;
|
|
646
|
+
const routeKey = `route:${key}`;
|
|
647
|
+
const partialRouteKey = `route:partial:${key}`;
|
|
648
|
+
lru.delete(viewKey);
|
|
649
|
+
lru.delete(routeKey);
|
|
650
|
+
lru.delete(partialRouteKey);
|
|
651
|
+
templateMemoryCache.delete(key);
|
|
652
|
+
|
|
653
|
+
const redis = getRedisClient();
|
|
654
|
+
if (redis) {
|
|
655
|
+
try {
|
|
656
|
+
await redis.del(`render:${viewKey}`);
|
|
657
|
+
await redis.del(`render:${routeKey}`);
|
|
658
|
+
await redis.del(`render:${partialRouteKey}`);
|
|
659
|
+
} catch {}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
if (fileCacheEnabled) {
|
|
663
|
+
const cacheDir = getFileCacheDir();
|
|
664
|
+
for (const k of [viewKey, routeKey, partialRouteKey]) {
|
|
665
|
+
try {
|
|
666
|
+
const f = path.join(cacheDir, toCacheFileName(k));
|
|
667
|
+
if (fs.existsSync(f)) fs.unlinkSync(f);
|
|
668
|
+
} catch {}
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
export { Render };
|
|
676
|
+
export default Render;
|
package/core/router.d.ts
ADDED