webspresso 0.0.109 → 0.0.110

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.
@@ -609,6 +609,15 @@ async function resolvePendingSsrFragments(html, req) {
609
609
  return output;
610
610
  }
611
611
 
612
+ function trimTrailingSlashes(str) {
613
+ if (!str) return '';
614
+ let end = str.length;
615
+ while (end > 0 && str.charCodeAt(end - 1) === 47) {
616
+ end--;
617
+ }
618
+ return end === str.length ? str : str.slice(0, end);
619
+ }
620
+
612
621
  /**
613
622
  * Match a concrete request pathname (e.g. `/notes/42`) against discovered page route entries.
614
623
  * Extracts route `:params` when matched.
@@ -619,11 +628,11 @@ async function resolvePendingSsrFragments(html, req) {
619
628
  */
620
629
  function matchPageEntryByPath(pagePath, pageEntries) {
621
630
  if (!pagePath || !Array.isArray(pageEntries)) return null;
622
- const cleanPath = String(pagePath).split('?')[0].replace(/\/+$/, '') || '/';
631
+ const cleanPath = trimTrailingSlashes(String(pagePath).split('?')[0]) || '/';
623
632
 
624
633
  // 1. Exact static match
625
634
  for (const entry of pageEntries) {
626
- const routePattern = entry.routePath.replace(/\/+$/, '') || '/';
635
+ const routePattern = trimTrailingSlashes(entry.routePath) || '/';
627
636
  if (routePattern === cleanPath) {
628
637
  return { entry, params: {} };
629
638
  }
@@ -631,7 +640,7 @@ function matchPageEntryByPath(pagePath, pageEntries) {
631
640
 
632
641
  // 2. Dynamic `:param` match
633
642
  for (const entry of pageEntries) {
634
- const routePattern = entry.routePath.replace(/\/+$/, '') || '/';
643
+ const routePattern = trimTrailingSlashes(entry.routePath) || '/';
635
644
  if (!routePattern.includes(':')) continue;
636
645
  const paramNames = [];
637
646
  const regexSource =
@@ -0,0 +1,339 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Webspresso Client Storage & Persistence Layer (`core/client/storage.js`)
5
+ *
6
+ * Capabilities:
7
+ * - Unified, SSR-safe Storage Adapter for `localStorage`, `sessionStorage`, and in-memory fallback.
8
+ * - Graceful fallback to `MemoryStorage` when running in Node.js (SSR), sandboxed iframes,
9
+ * or when private browsing blocks web storage with SecurityError/DOMException.
10
+ * - Automatic JSON serialization and deserialization with fallback to raw strings.
11
+ * - Built-in namespace prefixing (default: `w:`) to prevent collision with other applications.
12
+ * - Safe `clear()` that only removes keys belonging to the current namespace prefix.
13
+ * - Quota error resilience: catches `QuotaExceededError` without throwing fatal runtime crashes.
14
+ * - Sub-namespace scoping via `storage.scoped(prefix)`.
15
+ */
16
+
17
+ /**
18
+ * Map-backed standard Storage implementation for Node.js SSR and private browsing fallbacks.
19
+ */
20
+ class MemoryStorage {
21
+ constructor() {
22
+ this._data = new Map();
23
+ }
24
+
25
+ get length() {
26
+ return this._data.size;
27
+ }
28
+
29
+ getItem(key) {
30
+ const k = String(key);
31
+ return this._data.has(k) ? this._data.get(k) : null;
32
+ }
33
+
34
+ setItem(key, value) {
35
+ this._data.set(String(key), String(value));
36
+ }
37
+
38
+ removeItem(key) {
39
+ this._data.delete(String(key));
40
+ }
41
+
42
+ clear() {
43
+ this._data.clear();
44
+ }
45
+
46
+ key(index) {
47
+ const idx = Number(index);
48
+ if (idx < 0 || idx >= this._data.size) return null;
49
+ let i = 0;
50
+ for (const k of this._data.keys()) {
51
+ if (i === idx) return k;
52
+ i++;
53
+ }
54
+ return null;
55
+ }
56
+ }
57
+
58
+ const GLOBAL_STORAGE_KEY = '__webspresso_memory_storage__';
59
+ if (!globalThis[GLOBAL_STORAGE_KEY]) {
60
+ globalThis[GLOBAL_STORAGE_KEY] = {
61
+ local: new MemoryStorage(),
62
+ session: new MemoryStorage(),
63
+ memory: new MemoryStorage(),
64
+ };
65
+ }
66
+ const sharedMemoryBackends = globalThis[GLOBAL_STORAGE_KEY];
67
+
68
+ /**
69
+ * Safely probe and acquire the native browser storage backend or fallback to MemoryStorage.
70
+ *
71
+ * @param {'local' | 'session' | 'memory'} type
72
+ * @returns {Storage | MemoryStorage}
73
+ */
74
+ function getNativeStorageBackend(type) {
75
+ if (type === 'memory' || typeof window === 'undefined') {
76
+ return sharedMemoryBackends[type] || sharedMemoryBackends.local;
77
+ }
78
+
79
+ try {
80
+ const storage = type === 'session' ? window.sessionStorage : window.localStorage;
81
+ if (!storage || typeof storage.getItem !== 'function' || typeof storage.setItem !== 'function') {
82
+ return sharedMemoryBackends[type] || sharedMemoryBackends.local;
83
+ }
84
+ // Verify write access (Safari private browsing or sandboxed iframes may throw here)
85
+ const probeKey = '__w_storage_probe__';
86
+ storage.setItem(probeKey, '1');
87
+ storage.removeItem(probeKey);
88
+ return storage;
89
+ } catch (_e) {
90
+ return sharedMemoryBackends[type] || sharedMemoryBackends.local;
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Strongly-typed, prefix-aware storage adapter.
96
+ */
97
+ class StorageAdapter {
98
+ /**
99
+ * @param {'local' | 'session' | 'memory'} type
100
+ * @param {object} [options]
101
+ * @param {string} [options.prefix='w:']
102
+ * @param {Storage | MemoryStorage} [options.backend]
103
+ */
104
+ constructor(type = 'local', options = {}) {
105
+ this.type = type;
106
+ this.prefix = options.prefix !== undefined ? String(options.prefix) : 'w:';
107
+ this._backend = options.backend || null;
108
+ }
109
+
110
+ /**
111
+ * Resolve active storage backend.
112
+ * @private
113
+ */
114
+ _getBackend() {
115
+ if (!this._backend) {
116
+ this._backend = getNativeStorageBackend(this.type);
117
+ }
118
+ return this._backend;
119
+ }
120
+
121
+ /**
122
+ * Build prefixed key.
123
+ * @private
124
+ */
125
+ _fullKey(key) {
126
+ return `${this.prefix}${key}`;
127
+ }
128
+
129
+ /**
130
+ * Retrieve and deserialize a value from storage.
131
+ *
132
+ * @param {string} key
133
+ * @param {any} [defaultValue=null]
134
+ * @returns {any}
135
+ */
136
+ get(key, defaultValue = null) {
137
+ if (!key) return defaultValue;
138
+ try {
139
+ const backend = this._getBackend();
140
+ const raw = backend.getItem(this._fullKey(key));
141
+ if (raw === null || raw === undefined) {
142
+ return defaultValue;
143
+ }
144
+ try {
145
+ return JSON.parse(raw);
146
+ } catch (_parseErr) {
147
+ // Return raw string if not valid JSON
148
+ return raw;
149
+ }
150
+ } catch (_err) {
151
+ return defaultValue;
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Serialize and store a value in storage.
157
+ *
158
+ * @param {string} key
159
+ * @param {any} value - If undefined, the key is removed
160
+ * @returns {boolean} True if successfully stored, false on failure (e.g. quota exceeded)
161
+ */
162
+ set(key, value) {
163
+ if (!key) return false;
164
+ if (value === undefined) {
165
+ return this.remove(key);
166
+ }
167
+ try {
168
+ const backend = this._getBackend();
169
+ const serialized = JSON.stringify(value);
170
+ backend.setItem(this._fullKey(key), serialized);
171
+ return true;
172
+ } catch (_err) {
173
+ // QuotaExceededError or security restrictions
174
+ return false;
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Remove a key from storage.
180
+ *
181
+ * @param {string} key
182
+ * @returns {boolean}
183
+ */
184
+ remove(key) {
185
+ if (!key) return false;
186
+ try {
187
+ const backend = this._getBackend();
188
+ backend.removeItem(this._fullKey(key));
189
+ return true;
190
+ } catch (_err) {
191
+ return false;
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Check whether a key exists in storage.
197
+ *
198
+ * @param {string} key
199
+ * @returns {boolean}
200
+ */
201
+ has(key) {
202
+ if (!key) return false;
203
+ try {
204
+ const backend = this._getBackend();
205
+ return backend.getItem(this._fullKey(key)) !== null;
206
+ } catch (_err) {
207
+ return false;
208
+ }
209
+ }
210
+
211
+ /**
212
+ * List all unprefixed keys stored under this adapter's namespace prefix.
213
+ *
214
+ * @returns {string[]}
215
+ */
216
+ keys() {
217
+ try {
218
+ const backend = this._getBackend();
219
+ const result = [];
220
+ const prefixLen = this.prefix.length;
221
+
222
+ if (backend instanceof MemoryStorage) {
223
+ for (const k of backend._data.keys()) {
224
+ if (!this.prefix || k.startsWith(this.prefix)) {
225
+ result.push(k.slice(prefixLen));
226
+ }
227
+ }
228
+ return result;
229
+ }
230
+
231
+ if (typeof backend.length === 'number') {
232
+ for (let i = 0; i < backend.length; i++) {
233
+ const k = backend.key(i);
234
+ if (k && (!this.prefix || k.startsWith(this.prefix))) {
235
+ result.push(k.slice(prefixLen));
236
+ }
237
+ }
238
+ }
239
+ return result;
240
+ } catch (_err) {
241
+ return [];
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Clear only keys belonging to this adapter's prefix. Never touches outside keys.
247
+ *
248
+ * @returns {boolean}
249
+ */
250
+ clear() {
251
+ try {
252
+ const backend = this._getBackend();
253
+ if (!this.prefix) {
254
+ backend.clear();
255
+ return true;
256
+ }
257
+ const matchedKeys = this.keys();
258
+ for (const k of matchedKeys) {
259
+ backend.removeItem(this._fullKey(k));
260
+ }
261
+ return true;
262
+ } catch (_err) {
263
+ return false;
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Create a sub-scoped storage adapter inheriting the same backend.
269
+ *
270
+ * @param {string} subPrefix
271
+ * @returns {StorageAdapter}
272
+ */
273
+ scoped(subPrefix) {
274
+ const clean = String(subPrefix || '').trim();
275
+ const nextPrefix = clean ? `${this.prefix}${clean}:` : this.prefix;
276
+ return new StorageAdapter(this.type, {
277
+ prefix: nextPrefix,
278
+ backend: this._getBackend(),
279
+ });
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Create a complete client storage bundle exposing `local`, `session`, `memory`, and `scoped()`.
285
+ *
286
+ * @param {object} [options]
287
+ * @param {string} [options.prefix='w:'] - Root key namespace prefix
288
+ * @param {Storage | MemoryStorage} [options.localBackend] - Custom backend for localStorage
289
+ * @param {Storage | MemoryStorage} [options.sessionBackend] - Custom backend for sessionStorage
290
+ * @param {MemoryStorage} [options.memoryBackend] - Custom backend for memory storage
291
+ * @returns {ClientStorage}
292
+ */
293
+ function createClientStorage(options = {}) {
294
+ const prefix = options.prefix !== undefined ? String(options.prefix) : 'w:';
295
+ const local = new StorageAdapter('local', {
296
+ prefix,
297
+ backend: options.localBackend || null,
298
+ });
299
+ const session = new StorageAdapter('session', {
300
+ prefix,
301
+ backend: options.sessionBackend || null,
302
+ });
303
+ const memory = new StorageAdapter('memory', {
304
+ prefix,
305
+ backend: options.memoryBackend || null,
306
+ });
307
+
308
+ return Object.freeze({
309
+ local,
310
+ session,
311
+ memory,
312
+ get prefix() {
313
+ return prefix;
314
+ },
315
+ scoped(subPrefix) {
316
+ const clean = String(subPrefix || '').trim();
317
+ const nextPrefix = clean ? `${prefix}${clean}:` : prefix;
318
+ return createClientStorage({
319
+ ...options,
320
+ prefix: nextPrefix,
321
+ localBackend: local._getBackend(),
322
+ sessionBackend: session._getBackend(),
323
+ memoryBackend: memory._getBackend(),
324
+ });
325
+ },
326
+ });
327
+ }
328
+
329
+ const defaultStorage = createClientStorage();
330
+
331
+ module.exports = {
332
+ MemoryStorage,
333
+ StorageAdapter,
334
+ getNativeStorageBackend,
335
+ createClientStorage,
336
+ defaultStorage,
337
+ sharedMemoryBackends,
338
+ };
339
+
@@ -132,6 +132,139 @@ const NOOP_DEBUGGER = Object.freeze({
132
132
  clear() {},
133
133
  });
134
134
 
135
+ /**
136
+ * Convert kebab-case or mixed string to camelCase (e.g. "todo-id" -> "todoId").
137
+ * @param {string} str
138
+ * @returns {string}
139
+ */
140
+ function toCamelCase(str) {
141
+ if (typeof str !== 'string') return '';
142
+ return str.replace(/-([a-z0-9])/gi, (_, char) => char.toUpperCase());
143
+ }
144
+
145
+ /**
146
+ * Convert camelCase to kebab-case (e.g. "todoId" -> "todo-id").
147
+ * @param {string} str
148
+ * @returns {string}
149
+ */
150
+ function toKebabCase(str) {
151
+ if (typeof str !== 'string') return '';
152
+ return str
153
+ .replace(/([A-Z])/g, '-$1')
154
+ .toLowerCase()
155
+ .replace(/^-+/, '');
156
+ }
157
+
158
+ /**
159
+ * Parse string representation of data-* attributes into typed primitives.
160
+ * Mirrors jQuery / standard data coercion without unintended leading-zero mutation.
161
+ * @param {unknown} val
162
+ * @returns {unknown}
163
+ */
164
+ function parseDataValue(val) {
165
+ if (typeof val !== 'string') return val;
166
+ if (val === 'true') return true;
167
+ if (val === 'false') return false;
168
+ if (val === 'null') return null;
169
+ if (val === 'undefined') return undefined;
170
+ if (/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(val)) {
171
+ const num = Number(val);
172
+ if (!Number.isNaN(num)) return num;
173
+ }
174
+ if ((val.startsWith('{') && val.endsWith('}')) || (val.startsWith('[') && val.endsWith(']'))) {
175
+ try {
176
+ return JSON.parse(val);
177
+ } catch (_e) {
178
+ return val;
179
+ }
180
+ }
181
+ return val;
182
+ }
183
+
184
+ /**
185
+ * Decorate an HTMLElement with a chainable `.data(key?, val?)` helper.
186
+ *
187
+ * Usage:
188
+ * - `el.data('priority')` -> reads dataset / data-priority (coerces numbers, booleans, JSON)
189
+ * - `el.data('priority', 'high')` -> sets data-priority="high" and returns `el`
190
+ * - `el.data({ priority: 'high', count: 1 })` -> sets multiple data attributes and returns `el`
191
+ * - `el.data()` -> returns object with all parsed data attributes
192
+ *
193
+ * @template {Element} T
194
+ * @param {T} el
195
+ * @returns {T}
196
+ */
197
+ function decorateElement(el) {
198
+ if (!el || typeof el !== 'object') return el;
199
+ if (typeof el.data === 'function') return el;
200
+
201
+ try {
202
+ Object.defineProperty(el, 'data', {
203
+ value: function data(key, val) {
204
+ if (arguments.length === 0) {
205
+ const result = {};
206
+ if (el.dataset) {
207
+ for (const [k, v] of Object.entries(el.dataset)) {
208
+ result[k] = parseDataValue(v);
209
+ }
210
+ }
211
+ return result;
212
+ }
213
+
214
+ if (typeof key === 'object' && key !== null) {
215
+ for (const [k, v] of Object.entries(key)) {
216
+ el.data(k, v);
217
+ }
218
+ return el;
219
+ }
220
+
221
+ const strKey = String(key);
222
+ const camelKey = toCamelCase(strKey);
223
+ const kebabKey = toKebabCase(strKey);
224
+
225
+ if (arguments.length >= 2) {
226
+ if (val === null || val === undefined) {
227
+ if (el.dataset) delete el.dataset[camelKey];
228
+ if (typeof el.removeAttribute === 'function') {
229
+ el.removeAttribute(`data-${kebabKey}`);
230
+ el.removeAttribute(strKey);
231
+ }
232
+ } else {
233
+ const strVal = typeof val === 'object' ? JSON.stringify(val) : String(val);
234
+ if (el.dataset) el.dataset[camelKey] = strVal;
235
+ if (typeof el.setAttribute === 'function') {
236
+ el.setAttribute(`data-${kebabKey}`, strVal);
237
+ }
238
+ }
239
+ return el;
240
+ }
241
+
242
+ let raw = null;
243
+ if (el.dataset && el.dataset[camelKey] !== undefined) {
244
+ raw = el.dataset[camelKey];
245
+ } else if (typeof el.getAttribute === 'function') {
246
+ raw = el.getAttribute(`data-${kebabKey}`);
247
+ if (raw === null || raw === undefined) {
248
+ raw = el.getAttribute(strKey);
249
+ }
250
+ }
251
+
252
+ if (raw === null || raw === undefined) {
253
+ return null;
254
+ }
255
+ return parseDataValue(raw);
256
+ },
257
+ configurable: true,
258
+ writable: true,
259
+ enumerable: false,
260
+ });
261
+ } catch (_e) {
262
+ // Ignore in case object is non-extensible
263
+ }
264
+
265
+ return el;
266
+ }
267
+
135
268
  module.exports = {
136
269
  isObject,
137
270
  isPlainObject,
@@ -140,5 +273,9 @@ module.exports = {
140
273
  getByPath,
141
274
  setByPath,
142
275
  NOOP_DEBUGGER,
276
+ toCamelCase,
277
+ toKebabCase,
278
+ parseDataValue,
279
+ decorateElement,
143
280
  };
144
281
 
package/core/index.js CHANGED
@@ -381,4 +381,8 @@ Object.defineProperties(module.exports, {
381
381
  sendApiResult: { get: () => require('./client').sendApiResult, enumerable: true, configurable: true },
382
382
  createDatastarAdapter: { get: () => require('./client').createDatastarAdapter, enumerable: true, configurable: true },
383
383
  createClientDebugger: { get: () => require('./client').createClientDebugger, enumerable: true, configurable: true },
384
+ defaultStorage: { get: () => require('./client').defaultStorage, enumerable: true, configurable: true },
385
+ createClientStorage: { get: () => require('./client').createClientStorage, enumerable: true, configurable: true },
386
+ watch: { get: () => require('./client').watch, enumerable: true, configurable: true },
387
+ mountDevtool: { get: () => require('./client').mountDevtool, enumerable: true, configurable: true },
384
388
  });