webspresso 0.0.86 → 0.0.88
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/README.md +1 -1
- package/core/kernel/events.js +11 -3
- package/core/orm/cache/listeners.js +22 -15
- package/core/orm/events.js +26 -15
- package/package.json +1 -1
- package/plugins/admin-panel/core/admin-module.js +1 -0
- package/plugins/admin-panel/core/registry.js +1 -0
- package/plugins/admin-panel/modules/custom-pages.js +41 -1
- package/plugins/csrf/index.js +23 -10
- package/plugins/site-analytics/tracking.js +16 -2
- package/src/file-router.js +61 -16
- package/src/helpers.js +10 -1
package/README.md
CHANGED
|
@@ -885,7 +885,7 @@ if (adminApi) {
|
|
|
885
885
|
| `scripts` | External script URLs, script objects, or inline scripts injected into SSR Admin Panel (`registerScript`) |
|
|
886
886
|
| `styles` | External stylesheet URLs or inline CSS injected into SSR Admin Panel (`registerStyle`) |
|
|
887
887
|
|
|
888
|
-
Pages support JavaScript client components (`componentFile`, `pagesDir`, `component`)
|
|
888
|
+
Pages support JavaScript client components (`componentFile`, `pagesDir`, `component`), external URLs (`url` or `iframeUrl` inside `<iframe>`), as well as **native custom HTML pages** (`html` or `htmlFile` for local HTML files like EUIX Engine apps, Vue, or Alpine). HTML pages render directly in the page DOM with full Tailwind CSS styling, dark mode, and script execution without iframe overhead. Set `iframe: true` to isolate in an iframe if needed. By default (`layout: true`), custom page views are automatically wrapped in the Admin Layout with Breadcrumbs. Set `layout: false` for full-screen / custom canvas pages.
|
|
889
889
|
|
|
890
890
|
**Example component file (`admin/reports.js`):**
|
|
891
891
|
|
package/core/kernel/events.js
CHANGED
|
@@ -40,6 +40,8 @@ function buildContext(payload, meta) {
|
|
|
40
40
|
};
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
const EMPTY_ARRAY = Object.freeze([]);
|
|
44
|
+
|
|
43
45
|
/**
|
|
44
46
|
* @returns {{ dispatch: Function, publish: Function, on: Function, off: Function, buildContext: typeof buildContext }}
|
|
45
47
|
*/
|
|
@@ -74,7 +76,8 @@ function createEventBus() {
|
|
|
74
76
|
* @param {KernelEventContext} ctx
|
|
75
77
|
*/
|
|
76
78
|
async function dispatch(eventName, ctx) {
|
|
77
|
-
const list = listeners.get(eventName)
|
|
79
|
+
const list = listeners.get(eventName);
|
|
80
|
+
if (!list || list.length === 0) return undefined;
|
|
78
81
|
let last;
|
|
79
82
|
for (const fn of list) {
|
|
80
83
|
last = await fn(ctx);
|
|
@@ -87,8 +90,13 @@ function createEventBus() {
|
|
|
87
90
|
* @param {KernelEventContext} ctx
|
|
88
91
|
*/
|
|
89
92
|
async function publish(eventName, ctx) {
|
|
90
|
-
const list = listeners.get(eventName)
|
|
91
|
-
|
|
93
|
+
const list = listeners.get(eventName);
|
|
94
|
+
if (!list || list.length === 0) return;
|
|
95
|
+
const promises = [];
|
|
96
|
+
for (const fn of list) {
|
|
97
|
+
promises.push(Promise.resolve(fn(ctx)));
|
|
98
|
+
}
|
|
99
|
+
await Promise.all(promises);
|
|
92
100
|
}
|
|
93
101
|
|
|
94
102
|
return { dispatch, publish, on, off, buildContext };
|
|
@@ -10,6 +10,7 @@ const { getModel } = require('../model');
|
|
|
10
10
|
/** @type {Set<import('./layer').OrmCacheLayer>} */
|
|
11
11
|
const layers = new Set();
|
|
12
12
|
let hooked = false;
|
|
13
|
+
let unsubs = [];
|
|
13
14
|
|
|
14
15
|
/**
|
|
15
16
|
* @param {import('./layer').OrmCacheLayer} cacheLayer
|
|
@@ -37,21 +38,20 @@ function registerOrmCacheListeners(cacheLayer) {
|
|
|
37
38
|
}
|
|
38
39
|
}
|
|
39
40
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
});
|
|
41
|
+
unsubs = [
|
|
42
|
+
ModelEvents.on(`*.${Hooks.AFTER_CREATE}`, (record, ctx) => {
|
|
43
|
+
handleMutation(record, ctx, 'create');
|
|
44
|
+
}),
|
|
45
|
+
ModelEvents.on(`*.${Hooks.AFTER_UPDATE}`, (record, ctx) => {
|
|
46
|
+
handleMutation(record, ctx, 'update');
|
|
47
|
+
}),
|
|
48
|
+
ModelEvents.on(`*.${Hooks.AFTER_DELETE}`, (record, ctx) => {
|
|
49
|
+
handleMutation(record, ctx, 'delete');
|
|
50
|
+
}),
|
|
51
|
+
ModelEvents.on(`*.${Hooks.AFTER_RESTORE}`, (record, ctx) => {
|
|
52
|
+
handleMutation(record, ctx, 'restore');
|
|
53
|
+
}),
|
|
54
|
+
];
|
|
55
55
|
}
|
|
56
56
|
|
|
57
57
|
/**
|
|
@@ -59,6 +59,13 @@ function registerOrmCacheListeners(cacheLayer) {
|
|
|
59
59
|
*/
|
|
60
60
|
function unregisterOrmCacheListeners(cacheLayer) {
|
|
61
61
|
layers.delete(cacheLayer);
|
|
62
|
+
if (layers.size === 0 && hooked) {
|
|
63
|
+
for (const unsub of unsubs) {
|
|
64
|
+
if (typeof unsub === 'function') unsub();
|
|
65
|
+
}
|
|
66
|
+
unsubs = [];
|
|
67
|
+
hooked = false;
|
|
68
|
+
}
|
|
62
69
|
}
|
|
63
70
|
|
|
64
71
|
module.exports = {
|
package/core/orm/events.js
CHANGED
|
@@ -15,6 +15,13 @@
|
|
|
15
15
|
* @property {import('knex').Knex.Transaction|null} trx - Transaction if in one
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
|
+
const EMPTY_ARRAY = Object.freeze([]);
|
|
19
|
+
|
|
20
|
+
function cancelContext(reason = 'Operation cancelled') {
|
|
21
|
+
this.isCancelled = true;
|
|
22
|
+
this.cancelReason = reason;
|
|
23
|
+
}
|
|
24
|
+
|
|
18
25
|
/**
|
|
19
26
|
* Create a cancellation context for before hooks
|
|
20
27
|
* @param {string} model - Model name
|
|
@@ -23,18 +30,14 @@
|
|
|
23
30
|
* @returns {EventContext}
|
|
24
31
|
*/
|
|
25
32
|
function createEventContext(model, operation, trx = null) {
|
|
26
|
-
|
|
33
|
+
return {
|
|
27
34
|
model,
|
|
28
35
|
operation,
|
|
29
36
|
trx,
|
|
30
37
|
isCancelled: false,
|
|
31
38
|
cancelReason: null,
|
|
32
|
-
cancel
|
|
33
|
-
context.isCancelled = true;
|
|
34
|
-
context.cancelReason = reason;
|
|
35
|
-
},
|
|
39
|
+
cancel: cancelContext,
|
|
36
40
|
};
|
|
37
|
-
return context;
|
|
38
41
|
}
|
|
39
42
|
|
|
40
43
|
/**
|
|
@@ -114,6 +117,10 @@ class ModelEventsClass {
|
|
|
114
117
|
* @returns {Function[]} Array of matching listeners
|
|
115
118
|
*/
|
|
116
119
|
getMatchingListeners(model, hook) {
|
|
120
|
+
if (this.listeners.size === 0) {
|
|
121
|
+
return EMPTY_ARRAY;
|
|
122
|
+
}
|
|
123
|
+
|
|
117
124
|
const listeners = [];
|
|
118
125
|
const specificEvent = `${model}.${hook}`;
|
|
119
126
|
const wildcardModel = `*.${hook}`;
|
|
@@ -121,26 +128,30 @@ class ModelEventsClass {
|
|
|
121
128
|
const wildcardAll = '*.*';
|
|
122
129
|
|
|
123
130
|
// Check specific event
|
|
124
|
-
|
|
125
|
-
|
|
131
|
+
const sList = this.listeners.get(specificEvent);
|
|
132
|
+
if (sList) {
|
|
133
|
+
listeners.push(...sList);
|
|
126
134
|
}
|
|
127
135
|
|
|
128
136
|
// Check wildcard model (*.beforeCreate)
|
|
129
|
-
|
|
130
|
-
|
|
137
|
+
const wmList = this.listeners.get(wildcardModel);
|
|
138
|
+
if (wmList) {
|
|
139
|
+
listeners.push(...wmList);
|
|
131
140
|
}
|
|
132
141
|
|
|
133
142
|
// Check wildcard hook (User.*)
|
|
134
|
-
|
|
135
|
-
|
|
143
|
+
const whList = this.listeners.get(wildcardHook);
|
|
144
|
+
if (whList) {
|
|
145
|
+
listeners.push(...whList);
|
|
136
146
|
}
|
|
137
147
|
|
|
138
148
|
// Check full wildcard (*.*)
|
|
139
|
-
|
|
140
|
-
|
|
149
|
+
const waList = this.listeners.get(wildcardAll);
|
|
150
|
+
if (waList) {
|
|
151
|
+
listeners.push(...waList);
|
|
141
152
|
}
|
|
142
153
|
|
|
143
|
-
return listeners;
|
|
154
|
+
return listeners.length > 0 ? listeners : EMPTY_ARRAY;
|
|
144
155
|
}
|
|
145
156
|
|
|
146
157
|
/**
|
package/package.json
CHANGED
|
@@ -272,6 +272,7 @@ function registerPages(moduleId, pages, deps) {
|
|
|
272
272
|
description: page.description,
|
|
273
273
|
permission: page.permission,
|
|
274
274
|
layout: page.layout !== undefined ? page.layout : true,
|
|
275
|
+
iframe: page.iframe,
|
|
275
276
|
url: page.url || page.iframeUrl || undefined,
|
|
276
277
|
html: htmlContent || undefined,
|
|
277
278
|
});
|
|
@@ -479,6 +479,7 @@ class AdminRegistry {
|
|
|
479
479
|
description: p.description,
|
|
480
480
|
permission: p.permission,
|
|
481
481
|
layout: p.layout !== undefined ? p.layout : true,
|
|
482
|
+
iframe: p.iframe,
|
|
482
483
|
url: p.url || p.iframeUrl,
|
|
483
484
|
html: p.html,
|
|
484
485
|
hasClientComponent: this.clientComponents.has(p.id),
|
|
@@ -156,7 +156,7 @@ function generateCustomPageComponent() {
|
|
|
156
156
|
return `
|
|
157
157
|
// Custom Page Component Factory
|
|
158
158
|
function createCustomPage(pageConfig) {
|
|
159
|
-
if (pageConfig && (pageConfig.url || pageConfig.html)) {
|
|
159
|
+
if (pageConfig && (pageConfig.url || (pageConfig.html && pageConfig.iframe))) {
|
|
160
160
|
var iframeAttrs = {
|
|
161
161
|
src: pageConfig.url || undefined,
|
|
162
162
|
srcdoc: pageConfig.html || undefined,
|
|
@@ -187,6 +187,46 @@ function createCustomPage(pageConfig) {
|
|
|
187
187
|
};
|
|
188
188
|
}
|
|
189
189
|
|
|
190
|
+
if (pageConfig && pageConfig.html) {
|
|
191
|
+
var executeScripts = function(vnode) {
|
|
192
|
+
if (!vnode.dom) return;
|
|
193
|
+
var scripts = vnode.dom.querySelectorAll('script');
|
|
194
|
+
scripts.forEach(function(oldScript) {
|
|
195
|
+
if (oldScript.dataset && oldScript.dataset.executed) return;
|
|
196
|
+
var newScript = document.createElement('script');
|
|
197
|
+
Array.from(oldScript.attributes).forEach(function(attr) {
|
|
198
|
+
newScript.setAttribute(attr.name, attr.value);
|
|
199
|
+
});
|
|
200
|
+
newScript.dataset.executed = 'true';
|
|
201
|
+
newScript.appendChild(document.createTextNode(oldScript.innerHTML));
|
|
202
|
+
oldScript.parentNode.replaceChild(newScript, oldScript);
|
|
203
|
+
});
|
|
204
|
+
};
|
|
205
|
+
if (pageConfig.layout === false) {
|
|
206
|
+
return {
|
|
207
|
+
oncreate: executeScripts,
|
|
208
|
+
view: function() {
|
|
209
|
+
return m('div.custom-html-container', m.trust(pageConfig.html));
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
oncreate: executeScripts,
|
|
215
|
+
view: function() {
|
|
216
|
+
return m(Layout, [
|
|
217
|
+
m(Breadcrumb, { items: [{ label: pageConfig.title, href: pageConfig.path }] }),
|
|
218
|
+
m('div.mb-4.flex.items-start.justify-between.gap-4', [
|
|
219
|
+
m('div', [
|
|
220
|
+
m('h1.text-2xl.font-bold.text-gray-900.dark:text-slate-100', pageConfig.title),
|
|
221
|
+
pageConfig.description && m('p.text-gray-500.dark:text-slate-400.mt-1', pageConfig.description)
|
|
222
|
+
])
|
|
223
|
+
]),
|
|
224
|
+
m('div.custom-html-container', m.trust(pageConfig.html))
|
|
225
|
+
]);
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
190
230
|
return {
|
|
191
231
|
oninit(vnode) {
|
|
192
232
|
vnode.state.data = null;
|
package/plugins/csrf/index.js
CHANGED
|
@@ -11,6 +11,10 @@ const nunjucks = require('nunjucks');
|
|
|
11
11
|
// Storage to pass the active request to Nunjucks template helpers in a thread-safe manner
|
|
12
12
|
const csrfStorage = new AsyncLocalStorage();
|
|
13
13
|
|
|
14
|
+
const NOOP = () => {};
|
|
15
|
+
const EMPTY_OBJECT = Object.freeze({});
|
|
16
|
+
const ignoreRegexCache = new Map();
|
|
17
|
+
|
|
14
18
|
/**
|
|
15
19
|
* Compare two strings in constant time to prevent timing attacks
|
|
16
20
|
* @param {string} a
|
|
@@ -43,11 +47,18 @@ function isIgnored(req, ignorePaths) {
|
|
|
43
47
|
if (path.startsWith(pattern)) return true;
|
|
44
48
|
// Basic glob matching
|
|
45
49
|
if (pattern.includes('*')) {
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
50
|
+
let regex = ignoreRegexCache.get(pattern);
|
|
51
|
+
if (regex === undefined) {
|
|
52
|
+
const regexPattern = pattern
|
|
53
|
+
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
54
|
+
.replace(/\*\*/g, '.*')
|
|
55
|
+
.replace(/\*/g, '[^/]*');
|
|
56
|
+
regex = new RegExp(`^${regexPattern}$`);
|
|
57
|
+
if (ignoreRegexCache.size < 500) {
|
|
58
|
+
ignoreRegexCache.set(pattern, regex);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (regex.test(path)) return true;
|
|
51
62
|
}
|
|
52
63
|
} else if (pattern instanceof RegExp) {
|
|
53
64
|
if (pattern.test(path)) return true;
|
|
@@ -126,11 +137,14 @@ function csrfPlugin(options = {}) {
|
|
|
126
137
|
cookieOptions.maxAge = cookieOpts.maxAge;
|
|
127
138
|
}
|
|
128
139
|
|
|
140
|
+
const cookieSecret = cookieOptions.signed ? (cookieOpts.secret || process.env.SESSION_SECRET) : undefined;
|
|
141
|
+
const parseCookies = cookieParser(cookieSecret);
|
|
142
|
+
|
|
129
143
|
/**
|
|
130
144
|
* Internal middleware creator
|
|
131
145
|
* @param {Object} [overrideOpts]
|
|
132
146
|
*/
|
|
133
|
-
function createMiddleware(overrideOpts =
|
|
147
|
+
function createMiddleware(overrideOpts = EMPTY_OBJECT) {
|
|
134
148
|
const activeMethods = overrideOpts.methods || methods;
|
|
135
149
|
const activeIgnorePaths = overrideOpts.ignorePaths || ignorePaths;
|
|
136
150
|
|
|
@@ -140,8 +154,7 @@ function csrfPlugin(options = {}) {
|
|
|
140
154
|
|
|
141
155
|
// Initialize cookie parser dynamically if needed
|
|
142
156
|
if (useCookie && !req.cookies) {
|
|
143
|
-
|
|
144
|
-
cookieParser(secret)(req, res, () => {});
|
|
157
|
+
parseCookies(req, res, NOOP);
|
|
145
158
|
}
|
|
146
159
|
|
|
147
160
|
// 1. Retrieve or generate secret token
|
|
@@ -173,8 +186,8 @@ function csrfPlugin(options = {}) {
|
|
|
173
186
|
// 2. Perform CSRF verification for mutating HTTP methods
|
|
174
187
|
const method = req.method ? req.method.toUpperCase() : 'GET';
|
|
175
188
|
if (activeMethods.includes(method) && !isIgnored(req, activeIgnorePaths)) {
|
|
176
|
-
const body = req.body && typeof req.body === 'object' ? req.body :
|
|
177
|
-
const query = req.query && typeof req.query === 'object' ? req.query :
|
|
189
|
+
const body = req.body && typeof req.body === 'object' ? req.body : EMPTY_OBJECT;
|
|
190
|
+
const query = req.query && typeof req.query === 'object' ? req.query : EMPTY_OBJECT;
|
|
178
191
|
const submitted = (
|
|
179
192
|
body._csrf ||
|
|
180
193
|
query._csrf ||
|
|
@@ -82,6 +82,8 @@ function createTrackingMiddleware(options) {
|
|
|
82
82
|
// Sessions tracked in-memory (visitor_id -> last activity timestamp)
|
|
83
83
|
const sessionMap = new Map();
|
|
84
84
|
const SESSION_TIMEOUT = 30 * 60 * 1000; // 30 minutes
|
|
85
|
+
const MAX_SESSIONS = 10000;
|
|
86
|
+
const MAX_QUEUE_SIZE = 5000;
|
|
85
87
|
|
|
86
88
|
// Periodic session cleanup
|
|
87
89
|
setInterval(() => {
|
|
@@ -102,6 +104,11 @@ function createTrackingMiddleware(options) {
|
|
|
102
104
|
return existing.sessionId;
|
|
103
105
|
}
|
|
104
106
|
|
|
107
|
+
if (sessionMap.size >= MAX_SESSIONS) {
|
|
108
|
+
const firstKey = sessionMap.keys().next().value;
|
|
109
|
+
if (firstKey !== undefined) sessionMap.delete(firstKey);
|
|
110
|
+
}
|
|
111
|
+
|
|
105
112
|
const sessionId = quickHash(visitorId + '-' + now + '-' + Math.random());
|
|
106
113
|
sessionMap.set(visitorId, { sessionId, lastSeen: now });
|
|
107
114
|
return sessionId;
|
|
@@ -119,8 +126,15 @@ function createTrackingMiddleware(options) {
|
|
|
119
126
|
await knex(tableName).insert(batch);
|
|
120
127
|
} catch (e) {
|
|
121
128
|
console.error('[site-analytics] Batch insert failed:', e.message);
|
|
122
|
-
// Re-queue failed items
|
|
123
|
-
queue.
|
|
129
|
+
// Re-queue failed items with max size limit to prevent memory leak
|
|
130
|
+
if (queue.length + batch.length <= MAX_QUEUE_SIZE) {
|
|
131
|
+
queue.unshift(...batch);
|
|
132
|
+
} else {
|
|
133
|
+
const available = Math.max(0, MAX_QUEUE_SIZE - queue.length);
|
|
134
|
+
if (available > 0) {
|
|
135
|
+
queue.unshift(...batch.slice(batch.length - available));
|
|
136
|
+
}
|
|
137
|
+
}
|
|
124
138
|
}
|
|
125
139
|
}
|
|
126
140
|
|
package/src/file-router.js
CHANGED
|
@@ -16,9 +16,16 @@ const {
|
|
|
16
16
|
clearNjkFrontmatterCaches,
|
|
17
17
|
} = require('./njk-frontmatter');
|
|
18
18
|
|
|
19
|
+
const NOOP = () => {};
|
|
20
|
+
const EMPTY_OBJECT = Object.freeze({});
|
|
21
|
+
const EMPTY_ARRAY = Object.freeze([]);
|
|
22
|
+
|
|
19
23
|
// Cache for i18n files (key: filePath, value: { mtime, data })
|
|
20
24
|
const i18nCache = new Map();
|
|
21
25
|
|
|
26
|
+
// Cache for merged i18n (key: `${pagesDir}::${routeDir}::${locale}`, value: { globalMtime, routeMtime, data })
|
|
27
|
+
const mergedI18nCache = new Map();
|
|
28
|
+
|
|
22
29
|
// Cache for route configs in production
|
|
23
30
|
const configCache = new Map();
|
|
24
31
|
|
|
@@ -28,14 +35,25 @@ const routeConfigDevCache = new Map();
|
|
|
28
35
|
// Cache for API filename -> { method, baseName } (basename keys; stable per process)
|
|
29
36
|
const methodFromFilenameCache = new Map();
|
|
30
37
|
|
|
38
|
+
// Cache for translation param replacement regexes
|
|
39
|
+
const paramRegexCache = new Map();
|
|
40
|
+
|
|
31
41
|
const MAX_LOCALE_LEN = 16;
|
|
32
42
|
|
|
43
|
+
let cachedSupportedLocalesRaw = null;
|
|
44
|
+
let cachedSupportedLocaleSet = null;
|
|
45
|
+
|
|
33
46
|
/** @returns {Set<string>} */
|
|
34
47
|
function parseSupportedLocaleSet() {
|
|
35
48
|
const raw = process.env.SUPPORTED_LOCALES || 'en';
|
|
36
|
-
|
|
49
|
+
if (raw === cachedSupportedLocalesRaw && cachedSupportedLocaleSet !== null) {
|
|
50
|
+
return cachedSupportedLocaleSet;
|
|
51
|
+
}
|
|
52
|
+
cachedSupportedLocalesRaw = raw;
|
|
53
|
+
cachedSupportedLocaleSet = new Set(
|
|
37
54
|
raw.split(',').map((s) => s.trim().toLowerCase()).filter(Boolean)
|
|
38
55
|
);
|
|
56
|
+
return cachedSupportedLocaleSet;
|
|
39
57
|
}
|
|
40
58
|
|
|
41
59
|
/**
|
|
@@ -352,7 +370,7 @@ function scanDirectory(dir, baseDir = dir) {
|
|
|
352
370
|
*/
|
|
353
371
|
function loadI18nFile(filePath) {
|
|
354
372
|
if (!fs.existsSync(filePath)) {
|
|
355
|
-
return
|
|
373
|
+
return EMPTY_OBJECT;
|
|
356
374
|
}
|
|
357
375
|
|
|
358
376
|
try {
|
|
@@ -370,7 +388,7 @@ function loadI18nFile(filePath) {
|
|
|
370
388
|
return data;
|
|
371
389
|
} catch (err) {
|
|
372
390
|
console.error('Error loading i18n file:', filePath, err.message);
|
|
373
|
-
return
|
|
391
|
+
return EMPTY_OBJECT;
|
|
374
392
|
}
|
|
375
393
|
}
|
|
376
394
|
|
|
@@ -390,8 +408,28 @@ function loadI18n(pagesDir, routeDir, locale) {
|
|
|
390
408
|
const routePath = path.join(routeDir, 'locales', `${locale}.json`);
|
|
391
409
|
const routeTranslations = loadI18nFile(routePath);
|
|
392
410
|
|
|
411
|
+
const gEmpty = globalTranslations === EMPTY_OBJECT || !globalTranslations || Object.keys(globalTranslations).length === 0;
|
|
412
|
+
const rEmpty = routeTranslations === EMPTY_OBJECT || !routeTranslations || Object.keys(routeTranslations).length === 0;
|
|
413
|
+
|
|
414
|
+
if (gEmpty && rEmpty) return EMPTY_OBJECT;
|
|
415
|
+
if (gEmpty) return routeTranslations;
|
|
416
|
+
if (rEmpty) return globalTranslations;
|
|
417
|
+
|
|
418
|
+
const cacheKey = `${pagesDir}::${routeDir}::${locale}`;
|
|
419
|
+
const gCached = i18nCache.get(globalPath);
|
|
420
|
+
const rCached = i18nCache.get(routePath);
|
|
421
|
+
const gm = gCached?.mtime ?? 0;
|
|
422
|
+
const rm = rCached?.mtime ?? 0;
|
|
423
|
+
|
|
424
|
+
const mergedCached = mergedI18nCache.get(cacheKey);
|
|
425
|
+
if (mergedCached && mergedCached.gm === gm && mergedCached.rm === rm) {
|
|
426
|
+
return mergedCached.data;
|
|
427
|
+
}
|
|
428
|
+
|
|
393
429
|
// Merge: route-specific overrides global
|
|
394
|
-
|
|
430
|
+
const data = { ...globalTranslations, ...routeTranslations };
|
|
431
|
+
mergedI18nCache.set(cacheKey, { gm, rm, data });
|
|
432
|
+
return data;
|
|
395
433
|
}
|
|
396
434
|
|
|
397
435
|
/**
|
|
@@ -400,7 +438,7 @@ function loadI18n(pagesDir, routeDir, locale) {
|
|
|
400
438
|
* @returns {Function} Translation function t(key)
|
|
401
439
|
*/
|
|
402
440
|
function createTranslator(translations) {
|
|
403
|
-
return function t(key, params =
|
|
441
|
+
return function t(key, params = EMPTY_OBJECT) {
|
|
404
442
|
let value = translations[key];
|
|
405
443
|
|
|
406
444
|
if (value === undefined) {
|
|
@@ -422,10 +460,17 @@ function createTranslator(translations) {
|
|
|
422
460
|
}
|
|
423
461
|
|
|
424
462
|
// Replace params like {{name}} in the translation
|
|
425
|
-
if (typeof value === 'string' && Object.keys(params).length > 0) {
|
|
463
|
+
if (typeof value === 'string' && params && params !== EMPTY_OBJECT && Object.keys(params).length > 0) {
|
|
426
464
|
for (const [paramKey, paramValue] of Object.entries(params)) {
|
|
427
|
-
|
|
428
|
-
|
|
465
|
+
let regex = paramRegexCache.get(paramKey);
|
|
466
|
+
if (regex === undefined) {
|
|
467
|
+
const escaped = escapeRegExp(paramKey);
|
|
468
|
+
regex = new RegExp(`{{\\s*${escaped}\\s*}}`, 'g');
|
|
469
|
+
if (paramRegexCache.size < 500) {
|
|
470
|
+
paramRegexCache.set(paramKey, regex);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
value = value.replace(regex, paramValue);
|
|
429
474
|
}
|
|
430
475
|
}
|
|
431
476
|
|
|
@@ -585,9 +630,9 @@ function resolveNamedMiddleware(name, entry, fromTuple, tupleOptions, middleware
|
|
|
585
630
|
* @param {Object} middlewareRegistry - Named middleware registry (plain handlers or option factories)
|
|
586
631
|
* @returns {Array} Array of resolved middleware functions
|
|
587
632
|
*/
|
|
588
|
-
function resolveMiddlewares(middlewareConfig, middlewareRegistry =
|
|
589
|
-
if (!middlewareConfig || !Array.isArray(middlewareConfig)) {
|
|
590
|
-
return
|
|
633
|
+
function resolveMiddlewares(middlewareConfig, middlewareRegistry = EMPTY_OBJECT) {
|
|
634
|
+
if (!middlewareConfig || !Array.isArray(middlewareConfig) || middlewareConfig.length === 0) {
|
|
635
|
+
return EMPTY_ARRAY;
|
|
591
636
|
}
|
|
592
637
|
|
|
593
638
|
return middlewareConfig.map((mw, index) => {
|
|
@@ -640,7 +685,7 @@ function mountPages(app, options) {
|
|
|
640
685
|
? { alpine: !!clientRuntimeOpt.alpine, swup: !!clientRuntimeOpt.swup }
|
|
641
686
|
: { alpine: false, swup: false };
|
|
642
687
|
const isDev = process.env.NODE_ENV !== 'production';
|
|
643
|
-
const log = silent ?
|
|
688
|
+
const log = silent ? NOOP : console.log.bind(console);
|
|
644
689
|
|
|
645
690
|
// Get absolute path to pages directory
|
|
646
691
|
const absolutePagesDir = path.resolve(pagesDir);
|
|
@@ -783,7 +828,7 @@ function mountPages(app, options) {
|
|
|
783
828
|
|
|
784
829
|
const preResolvedMw = routeMiddleware
|
|
785
830
|
? resolveMiddlewares(routeMiddleware, middlewares)
|
|
786
|
-
:
|
|
831
|
+
: EMPTY_ARRAY;
|
|
787
832
|
|
|
788
833
|
if (typeof handlerFn !== 'function') {
|
|
789
834
|
console.warn(`API route ${route.file} does not export a function`);
|
|
@@ -867,7 +912,7 @@ function mountPages(app, options) {
|
|
|
867
912
|
const mountConfig = loadRouteConfig(route.configPath, isDev);
|
|
868
913
|
const preResolvedPageMw = mountConfig?.middleware
|
|
869
914
|
? resolveMiddlewares(mountConfig.middleware, middlewares)
|
|
870
|
-
:
|
|
915
|
+
: EMPTY_ARRAY;
|
|
871
916
|
|
|
872
917
|
app.get(route.routePath, async (req, res, next) => {
|
|
873
918
|
try {
|
|
@@ -880,11 +925,11 @@ function mountPages(app, options) {
|
|
|
880
925
|
|
|
881
926
|
// Load route config
|
|
882
927
|
const config = loadRouteConfig(route.configPath, isDev);
|
|
883
|
-
const routeHooks = config?.hooks ||
|
|
928
|
+
const routeHooks = config?.hooks || EMPTY_OBJECT;
|
|
884
929
|
|
|
885
930
|
// Create context with plugin helpers merged
|
|
886
931
|
const baseHelpers = createHelpers({ req, res, locale });
|
|
887
|
-
const pluginHelpers = pluginManager ? pluginManager.getHelpers() :
|
|
932
|
+
const pluginHelpers = pluginManager ? pluginManager.getHelpers() : EMPTY_OBJECT;
|
|
888
933
|
if (pluginManager) {
|
|
889
934
|
const contentApi = pluginManager.getPluginAPI('content');
|
|
890
935
|
if (contentApi?.createRequestHelpers) {
|
package/src/helpers.js
CHANGED
|
@@ -18,6 +18,9 @@ dayjs.extend(utc);
|
|
|
18
18
|
dayjs.extend(timezone);
|
|
19
19
|
dayjs.extend(customParseFormat);
|
|
20
20
|
|
|
21
|
+
// Cache for isPath regex patterns
|
|
22
|
+
const isPathRegexCache = new Map();
|
|
23
|
+
|
|
21
24
|
/**
|
|
22
25
|
* Asset Manager - handles asset paths, versioning, and manifest
|
|
23
26
|
*/
|
|
@@ -385,7 +388,13 @@ function createHelpers(ctx) {
|
|
|
385
388
|
const currentPath = req.path;
|
|
386
389
|
if (pattern === currentPath) return true;
|
|
387
390
|
if (pattern.includes('*')) {
|
|
388
|
-
|
|
391
|
+
let regex = isPathRegexCache.get(pattern);
|
|
392
|
+
if (regex === undefined) {
|
|
393
|
+
regex = new RegExp('^' + pattern.replace(/\*/g, '.*') + '$');
|
|
394
|
+
if (isPathRegexCache.size < 500) {
|
|
395
|
+
isPathRegexCache.set(pattern, regex);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
389
398
|
return regex.test(currentPath);
|
|
390
399
|
}
|
|
391
400
|
return false;
|