@decocms/blocks 7.71.5 → 7.71.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/blocks",
3
- "version": "7.71.5",
3
+ "version": "7.71.6",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24"
@@ -1,7 +1,8 @@
1
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
2
  import { setDraftOverrideGetter } from "./draftSource";
3
3
  import {
4
4
  findPageByPath,
5
+ getAllPages,
5
6
  loadBlocks,
6
7
  matchPath,
7
8
  setBlocks,
@@ -222,6 +223,112 @@ describe("findPageByPath specificity", () => {
222
223
  });
223
224
  });
224
225
 
226
+ describe("findPageByPath page index cache", () => {
227
+ afterEach(() => {
228
+ setBlocks({});
229
+ });
230
+
231
+ it("serves a change published by setBlocks()", () => {
232
+ setBlocks({ "pages-a": { name: "A", path: "/a", sections: [] } });
233
+ expect(findPageByPath("/a")?.blockKey).toBe("pages-a");
234
+
235
+ setBlocks({ "pages-b": { name: "B", path: "/b", sections: [] } });
236
+ expect(findPageByPath("/a")).toBeNull();
237
+ expect(findPageByPath("/b")?.blockKey).toBe("pages-b");
238
+ });
239
+
240
+ it("serves a change when setBlocks() gets the same object mutated in place", () => {
241
+ const blocks: Record<string, unknown> = {
242
+ "pages-a": { name: "A", path: "/a", sections: [] },
243
+ };
244
+ setBlocks(blocks);
245
+ expect(findPageByPath("/a")?.blockKey).toBe("pages-a");
246
+
247
+ blocks["pages-b"] = { name: "B", path: "/b", sections: [] };
248
+ setBlocks(blocks);
249
+ expect(findPageByPath("/b")?.blockKey).toBe("pages-b");
250
+ });
251
+
252
+ it("matches a page that only exists in the draft override", () => {
253
+ setBlocks({ "pages-a": { name: "A", path: "/a", sections: [] } });
254
+ const match = withBlocksOverride(
255
+ { "pages-draft": { name: "Draft", path: "/draft", sections: [] } },
256
+ () => findPageByPath("/draft"),
257
+ );
258
+ expect(match?.blockKey).toBe("pages-draft");
259
+ expect(findPageByPath("/draft")).toBeNull();
260
+ });
261
+
262
+ it("matches a literal path through its percent-encoded spelling", () => {
263
+ setBlocks({ "pages-promo": { name: "Promo", path: "/promoção", sections: [] } });
264
+ expect(findPageByPath("/promo%C3%A7%C3%A3o")?.blockKey).toBe("pages-promo");
265
+ expect(findPageByPath("/promoção")?.blockKey).toBe("pages-promo");
266
+ });
267
+
268
+ it("keeps literal matching case-sensitive and trailing-slash exact", () => {
269
+ setBlocks({ "pages-lego": { name: "Lego", path: "/lego", sections: [] } });
270
+ expect(findPageByPath("/lego")?.params).toEqual({});
271
+ expect(findPageByPath("/LEGO")).toBeNull();
272
+ expect(findPageByPath("/lego/")).toBeNull();
273
+ });
274
+
275
+ it("keeps the first of two pages with the same path", () => {
276
+ setBlocks({
277
+ "pages-first": { name: "First", path: "/same", sections: [] },
278
+ "pages-second": { name: "Second", path: "/same", sections: [] },
279
+ });
280
+ expect(findPageByPath("/same")?.blockKey).toBe("pages-first");
281
+ });
282
+
283
+ it("skips a malformed pattern without throwing", () => {
284
+ setBlocks({
285
+ "pages-bad": { name: "Bad", path: "/(unclosed", sections: [] },
286
+ "pages-ok": { name: "OK", path: "/ok", sections: [] },
287
+ });
288
+ expect(findPageByPath("/(unclosed")).toBeNull();
289
+ expect(findPageByPath("/ok")?.blockKey).toBe("pages-ok");
290
+ });
291
+
292
+ it("invalidates the index for every module instance sharing the blocks", async () => {
293
+ const blocks: Record<string, unknown> = {
294
+ "pages-a": { name: "A", path: "/a", sections: [] },
295
+ };
296
+ setBlocks(blocks);
297
+ vi.resetModules();
298
+ const other = await import("./loader");
299
+ expect(other.findPageByPath("/a")?.blockKey).toBe("pages-a");
300
+
301
+ blocks["pages-b"] = { name: "B", path: "/b", sections: [] };
302
+ setBlocks(blocks);
303
+ expect(other.findPageByPath("/b")?.blockKey).toBe("pages-b");
304
+ });
305
+
306
+ it("keeps matchPath correct past its compiled-pattern cache bound", () => {
307
+ for (let i = 0; i < 600; i++) {
308
+ expect(matchPath(`/p${i}/:slug`, `/p${i}/x`)).toEqual({ slug: "x" });
309
+ }
310
+ expect(matchPath("/p0/:slug", "/p0/y")).toEqual({ slug: "y" });
311
+ });
312
+
313
+ it("returns a fresh array from getAllPages()", () => {
314
+ setBlocks({ "pages-a": { name: "A", path: "/a", sections: [] } });
315
+ getAllPages().pop();
316
+ expect(getAllPages()).toHaveLength(1);
317
+ });
318
+
319
+ it("throws when the runtime lacks URLPattern, even for literal-only pages", () => {
320
+ setBlocks({ "pages-a": { name: "A", path: "/a", sections: [] } });
321
+ const g = globalThis as { URLPattern?: unknown };
322
+ const saved = g.URLPattern;
323
+ delete g.URLPattern;
324
+ try {
325
+ expect(() => findPageByPath("/a")).toThrow(/URLPattern.*Node\.js >= 24/s);
326
+ } finally {
327
+ if (saved !== undefined) g.URLPattern = saved;
328
+ }
329
+ });
330
+ });
331
+
225
332
  describe("getAllPages — page blocks without the `pages-` prefix", () => {
226
333
  afterEach(() => {
227
334
  setBlocks({});
package/src/cms/loader.ts CHANGED
@@ -86,6 +86,8 @@ function computeRevision(blocks: Record<string, unknown>): string {
86
86
  * Notifies all onChange listeners and updates the revision.
87
87
  */
88
88
  export function setBlocks(blocks: Record<string, unknown>) {
89
+ // A caller may hand back the same object after mutating it in place.
90
+ pageIndexCache.delete(blocks);
89
91
  blockData = blocks;
90
92
  revision = computeRevision(blocks);
91
93
 
@@ -312,13 +314,35 @@ function isPageBlock(key: string, block: unknown): boolean {
312
314
  );
313
315
  }
314
316
 
315
- export function getAllPages(): Array<{ key: string; page: DecoPage }> {
316
- const blocks = loadBlocks();
317
- const pages: Array<{
318
- key: string;
319
- page: DecoPage;
320
- key2: [number, number, number];
321
- }> = [];
317
+ type PageIndexEntry = {
318
+ key: string;
319
+ page: DecoPage;
320
+ path: string;
321
+ /** `path` has no URLPattern syntax, so it only matches its own spelling. */
322
+ literal: boolean;
323
+ /** Compiled on first use; `null` when the pattern is malformed. */
324
+ matcher?: CompiledPattern | null;
325
+ };
326
+
327
+ /**
328
+ * Page list per blocks object, ranked by path specificity.
329
+ *
330
+ * `findPageByPath` runs on every CMS resolve — twice per request on a site
331
+ * that retries a lowercase path, and once more per template it resolves — and
332
+ * a request that ends on no CMS page (a catalog PLP/PDP, a search, a 404) walks
333
+ * the whole list. Rebuilding and sorting the list and compiling a URLPattern
334
+ * per page on each call made that walk the hottest frame of an uncached render
335
+ * on a 1.2k-page decofile. Keyed by the blocks object: `setBlocks()` and every
336
+ * draft/override composition produce a new one, so a published change can
337
+ * never be served from a stale index. Kept on `globalThis`, like the blocks
338
+ * themselves, so every module instance drops the same entry on `setBlocks()`.
339
+ * The compiled matchers live on the entries and go away with them.
340
+ */
341
+ const pageIndexCache: WeakMap<Record<string, unknown>, PageIndexEntry[]> =
342
+ G.__deco.pageIndexCache ?? (G.__deco.pageIndexCache = new WeakMap());
343
+
344
+ function buildPageIndex(blocks: Record<string, unknown>): PageIndexEntry[] {
345
+ const pages: Array<PageIndexEntry & { key2: [number, number, number] }> = [];
322
346
 
323
347
  for (const [key, block] of Object.entries(blocks)) {
324
348
  if (!isPageBlock(key, block)) continue;
@@ -326,7 +350,13 @@ export function getAllPages(): Array<{ key: string; page: DecoPage }> {
326
350
  if (!page.sections) continue;
327
351
  if (!page.path) continue;
328
352
 
329
- pages.push({ key, page, key2: pathSpecificityKey(page.path) });
353
+ pages.push({
354
+ key,
355
+ page,
356
+ path: page.path,
357
+ literal: isPlainPath(page.path),
358
+ key2: pathSpecificityKey(page.path),
359
+ });
330
360
  }
331
361
 
332
362
  return pages
@@ -336,7 +366,21 @@ export function getAllPages(): Array<{ key: string; page: DecoPage }> {
336
366
  }
337
367
  return 0;
338
368
  })
339
- .map(({ key, page }) => ({ key, page }));
369
+ .map(({ key, page, path, literal }) => ({ key, page, path, literal }));
370
+ }
371
+
372
+ function getPageIndex(): PageIndexEntry[] {
373
+ const blocks = loadBlocks();
374
+ let index = pageIndexCache.get(blocks);
375
+ if (!index) {
376
+ index = buildPageIndex(blocks);
377
+ pageIndexCache.set(blocks, index);
378
+ }
379
+ return index;
380
+ }
381
+
382
+ export function getAllPages(): Array<{ key: string; page: DecoPage }> {
383
+ return getPageIndex().map(({ key, page }) => ({ key, page }));
340
384
  }
341
385
 
342
386
  // Module-scoped (NOT `declare global`) ambient declaration for the
@@ -366,6 +410,84 @@ declare const URLPattern: {
366
410
  };
367
411
  };
368
412
 
413
+ type CompiledPattern = {
414
+ exec(input: { pathname: string }): MatchPatternResult | null;
415
+ };
416
+
417
+ function compilePattern(pattern: string): CompiledPattern | null {
418
+ try {
419
+ return new URLPattern({ pathname: pattern });
420
+ } catch {
421
+ return null;
422
+ }
423
+ }
424
+
425
+ /**
426
+ * Compiled patterns for direct `matchPath()` callers, bounded: unlike the page
427
+ * index, its patterns can come from anywhere. Oldest entry evicted first.
428
+ */
429
+ const MATCH_PATH_CACHE_MAX = 256;
430
+ const matchPathCache = new Map<string, CompiledPattern | null>();
431
+
432
+ function cachedPattern(pattern: string): CompiledPattern | null {
433
+ const hit = matchPathCache.get(pattern);
434
+ if (hit !== undefined) return hit;
435
+ const compiled = compilePattern(pattern);
436
+ if (matchPathCache.size >= MATCH_PATH_CACHE_MAX) {
437
+ matchPathCache.delete(matchPathCache.keys().next().value as string);
438
+ }
439
+ matchPathCache.set(pattern, compiled);
440
+ return compiled;
441
+ }
442
+
443
+ function execPattern(
444
+ compiled: CompiledPattern | null,
445
+ urlPath: string,
446
+ ): Record<string, string> | null {
447
+ if (!compiled) return null;
448
+ let result: MatchPatternResult | null;
449
+ try {
450
+ result = compiled.exec({ pathname: urlPath });
451
+ } catch {
452
+ return null;
453
+ }
454
+ if (!result) return null;
455
+
456
+ const groups = result.pathname.groups as Record<string, string | undefined>;
457
+ const out: Record<string, string> = {};
458
+ for (const [k, v] of Object.entries(groups)) {
459
+ if (v !== undefined) out[k] = v;
460
+ }
461
+ return out;
462
+ }
463
+
464
+ /**
465
+ * Characters that are literal both in URLPattern syntax and in URL path
466
+ * canonicalization. A pattern made only of them matches exactly its own
467
+ * spelling, and an input made only of them is already canonical — so for that
468
+ * pair a string comparison gives the same answer as `URLPattern.exec`. Anything
469
+ * else (`:param`, groups, `*`, `%`-escapes, non-ASCII, dot segments) takes the
470
+ * URLPattern path.
471
+ */
472
+ const PLAIN_PATH = /^[A-Za-z0-9\-._~/]*$/;
473
+ const DOT_SEGMENT = /(^|\/)\.{1,2}(\/|$)/;
474
+
475
+ function isPlainPath(path: string): boolean {
476
+ return PLAIN_PATH.test(path) && !DOT_SEGMENT.test(path);
477
+ }
478
+
479
+ function assertURLPattern() {
480
+ if (typeof URLPattern === "undefined") {
481
+ throw new Error(
482
+ "@decocms/blocks: this runtime has no URLPattern Web API, so CMS page " +
483
+ "paths cannot be matched. URLPattern is native in browsers, " +
484
+ "Cloudflare workerd, Deno, and Node.js >= 24 — you are most likely " +
485
+ "running Node <= 22. Upgrade the runtime to Node 24+ (see this " +
486
+ 'package\'s "engines" field).',
487
+ );
488
+ }
489
+ }
490
+
369
491
  /**
370
492
  * Match a CMS page path pattern against a URL path.
371
493
  *
@@ -390,29 +512,8 @@ export function matchPath(
390
512
  pattern: string,
391
513
  urlPath: string,
392
514
  ): Record<string, string> | null {
393
- if (typeof URLPattern === "undefined") {
394
- throw new Error(
395
- "@decocms/blocks: this runtime has no URLPattern Web API, so CMS page " +
396
- "paths cannot be matched. URLPattern is native in browsers, " +
397
- "Cloudflare workerd, Deno, and Node.js >= 24 — you are most likely " +
398
- "running Node <= 22. Upgrade the runtime to Node 24+ (see this " +
399
- 'package\'s "engines" field).',
400
- );
401
- }
402
- let result: MatchPatternResult | null;
403
- try {
404
- result = new URLPattern({ pathname: pattern }).exec({ pathname: urlPath });
405
- } catch {
406
- return null;
407
- }
408
- if (!result) return null;
409
-
410
- const groups = result.pathname.groups as Record<string, string | undefined>;
411
- const out: Record<string, string> = {};
412
- for (const [k, v] of Object.entries(groups)) {
413
- if (v !== undefined) out[k] = v;
414
- }
415
- return out;
515
+ assertURLPattern();
516
+ return execPattern(cachedPattern(pattern), urlPath);
416
517
  }
417
518
 
418
519
  /**
@@ -443,11 +544,18 @@ export function getSiteSeo(): {
443
544
  export function findPageByPath(
444
545
  targetPath: string,
445
546
  ): { page: DecoPage; params: Record<string, string>; blockKey: string } | null {
446
- const allPages = getAllPages();
447
-
448
- for (const { key, page } of allPages) {
449
- if (!page.path) continue;
450
- const params = matchPath(page.path, targetPath);
547
+ // Same loud failure as matchPath, even when every page is literal.
548
+ assertURLPattern();
549
+ const plainTarget = isPlainPath(targetPath);
550
+
551
+ for (const entry of getPageIndex()) {
552
+ const { key, page, path, literal } = entry;
553
+ if (literal && plainTarget) {
554
+ if (path === targetPath) return { page, params: {}, blockKey: key };
555
+ continue;
556
+ }
557
+ if (entry.matcher === undefined) entry.matcher = compilePattern(path);
558
+ const params = execPattern(entry.matcher, targetPath);
451
559
  if (params !== null) return { page, params, blockKey: key };
452
560
  }
453
561