@decocms/blocks 7.86.2 → 7.86.4

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.86.2",
3
+ "version": "7.86.4",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24"
@@ -1,8 +1,10 @@
1
1
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { computeRevision } from "./blockSource";
2
3
  import { setDraftOverrideGetter } from "./draftSource";
3
4
  import {
4
5
  findPageByPath,
5
6
  getAllPages,
7
+ getRevision,
6
8
  loadBlocks,
7
9
  matchPath,
8
10
  setBlocks,
@@ -95,26 +97,17 @@ describe("matchPath", () => {
95
97
  });
96
98
 
97
99
  it("matches with an optional prefix before a literal segment", () => {
98
- expect(
99
- matchPath(
100
- "/{acme/}?campanhas/*",
101
- "/acme/campanhas/destaques-2023",
102
- ),
103
- ).toEqual({
100
+ expect(matchPath("/{acme/}?campanhas/*", "/acme/campanhas/destaques-2023")).toEqual({
104
101
  "0": "destaques-2023",
105
102
  });
106
- expect(
107
- matchPath("/{acme/}?campanhas/*", "/campanhas/destaques-2023"),
108
- ).toEqual({
103
+ expect(matchPath("/{acme/}?campanhas/*", "/campanhas/destaques-2023")).toEqual({
109
104
  "0": "destaques-2023",
110
105
  });
111
106
  });
112
107
 
113
108
  it("matches an optional suffix group present and absent", () => {
114
109
  expect(matchPath("/black-friday{/70-off}?", "/black-friday")).toEqual({});
115
- expect(
116
- matchPath("/black-friday{/70-off}?", "/black-friday/70-off"),
117
- ).toEqual({});
110
+ expect(matchPath("/black-friday{/70-off}?", "/black-friday/70-off")).toEqual({});
118
111
  });
119
112
  });
120
113
 
@@ -134,9 +127,7 @@ describe("matchPath", () => {
134
127
  // biome-ignore lint/performance/noDelete: restoring exact global state
135
128
  delete g.URLPattern;
136
129
  try {
137
- expect(() => matchPath("/foo/:slug", "/foo/bar")).toThrow(
138
- /URLPattern.*Node\.js >= 24/s,
139
- );
130
+ expect(() => matchPath("/foo/:slug", "/foo/bar")).toThrow(/URLPattern.*Node\.js >= 24/s);
140
131
  } finally {
141
132
  if (saved !== undefined) g.URLPattern = saved;
142
133
  }
@@ -432,9 +423,7 @@ describe("loadBlocks draft override — key percent-encoding", () => {
432
423
  }));
433
424
 
434
425
  // Exactly one page for "/" survives the merge — no encoded/raw duplicate.
435
- const pageBlocks = Object.keys(loadBlocks()).filter((k) =>
436
- k.startsWith("pages-"),
437
- );
426
+ const pageBlocks = Object.keys(loadBlocks()).filter((k) => k.startsWith("pages-"));
438
427
  expect(pageBlocks).toHaveLength(1);
439
428
 
440
429
  const match = findPageByPath("/");
@@ -476,9 +465,7 @@ describe("loadBlocks draft override — key percent-encoding", () => {
476
465
  }));
477
466
 
478
467
  expect(findPageByPath("/")).toBeNull();
479
- const pageBlocks = Object.keys(loadBlocks()).filter((k) =>
480
- k.startsWith("pages-"),
481
- );
468
+ const pageBlocks = Object.keys(loadBlocks()).filter((k) => k.startsWith("pages-"));
482
469
  expect(pageBlocks).toHaveLength(0);
483
470
  });
484
471
  });
@@ -534,10 +521,7 @@ describe("loadBlocks draft snapshot semantics", () => {
534
521
 
535
522
  // Merge (admin partial payloads): the base-only block survives.
536
523
  withBlocksOverride(draft, () => {
537
- expect(Object.keys(loadBlocks()).sort()).toEqual([
538
- "pages-home-1",
539
- "pages-other-2",
540
- ]);
524
+ expect(Object.keys(loadBlocks()).sort()).toEqual(["pages-home-1", "pages-other-2"]);
541
525
  });
542
526
  });
543
527
 
@@ -547,11 +531,27 @@ describe("loadBlocks draft snapshot semantics", () => {
547
531
  "pages-ambient-9": { name: "A", path: "/a", sections: [{}] },
548
532
  }));
549
533
 
550
- withDraftBlocks(
551
- { "pages-scoped-3": { name: "S", path: "/s", sections: [{}] } },
552
- () => {
553
- expect(Object.keys(loadBlocks())).toEqual(["pages-scoped-3"]);
554
- },
555
- );
534
+ withDraftBlocks({ "pages-scoped-3": { name: "S", path: "/s", sections: [{}] } }, () => {
535
+ expect(Object.keys(loadBlocks())).toEqual(["pages-scoped-3"]);
536
+ });
537
+ });
538
+ });
539
+
540
+ describe("setBlocks revision", () => {
541
+ it("uses a known revision without re-serializing the decofile", () => {
542
+ const stringify = vi.spyOn(JSON, "stringify");
543
+ setBlocks({ "pages/a.json": { name: "a" } }, "stored-rev");
544
+ expect(getRevision()).toBe("stored-rev");
545
+ expect(stringify).not.toHaveBeenCalled();
546
+ stringify.mockRestore();
547
+ });
548
+
549
+ it("computes the same revision as before when none is given", () => {
550
+ const blocks = { "pages/a.json": { name: "a" } };
551
+ setBlocks(blocks);
552
+ const computed = getRevision();
553
+ setBlocks(blocks, computed ?? undefined);
554
+ expect(getRevision()).toBe(computed);
555
+ expect(computed).toBe(computeRevision(blocks));
556
556
  });
557
557
  });
package/src/cms/loader.ts CHANGED
@@ -53,10 +53,7 @@ const blocksOverrideStorage: ALSLike<BlocksOverride> = ALS
53
53
  // Change listeners
54
54
  // ---------------------------------------------------------------------------
55
55
 
56
- type ChangeListener = (
57
- blocks: Record<string, unknown>,
58
- revision: string,
59
- ) => void;
56
+ type ChangeListener = (blocks: Record<string, unknown>, revision: string) => void;
60
57
  const changeListeners: ChangeListener[] = [];
61
58
 
62
59
  /** Register a callback invoked whenever setBlocks() changes the decofile. */
@@ -84,12 +81,16 @@ function computeRevision(blocks: Record<string, unknown>): string {
84
81
  * Set the blocks data. Called at startup with generated blocks,
85
82
  * and by the admin on hot-reload.
86
83
  * Notifies all onChange listeners and updates the revision.
84
+ *
85
+ * Pass `knownRevision` when the source already has it (the KV snapshot stores
86
+ * one, computed with the same `computeRevision`): hashing re-serializes the
87
+ * whole decofile, ~21 MB of garbage on a 10 MB decofile, on every isolate boot.
87
88
  */
88
- export function setBlocks(blocks: Record<string, unknown>) {
89
+ export function setBlocks(blocks: Record<string, unknown>, knownRevision?: string) {
89
90
  // A caller may hand back the same object after mutating it in place.
90
91
  pageIndexCache.delete(blocks);
91
92
  blockData = blocks;
92
- revision = computeRevision(blocks);
93
+ revision = knownRevision ?? computeRevision(blocks);
93
94
 
94
95
  // Persist to globalThis so other module instances see them
95
96
  G.__deco.blockData = blockData;
@@ -227,10 +228,7 @@ export function getRevision(): string | null {
227
228
  * for the duration of the render. Other concurrent requests are not
228
229
  * affected (AsyncLocalStorage is per-request scoped).
229
230
  */
230
- export function withBlocksOverride<T>(
231
- override: Record<string, unknown>,
232
- fn: () => T,
233
- ): T {
231
+ export function withBlocksOverride<T>(override: Record<string, unknown>, fn: () => T): T {
234
232
  return blocksOverrideStorage.run({ mode: "merge", blocks: override }, fn);
235
233
  }
236
234
 
@@ -241,10 +239,7 @@ export function withBlocksOverride<T>(
241
239
  * exactly like the page render, deletions included, or a lazy section could
242
240
  * render a block the page no longer has.
243
241
  */
244
- export function withDraftBlocks<T>(
245
- draft: Record<string, unknown>,
246
- fn: () => T,
247
- ): T {
242
+ export function withDraftBlocks<T>(draft: Record<string, unknown>, fn: () => T): T {
248
243
  return blocksOverrideStorage.run({ mode: "snapshot", blocks: draft }, fn);
249
244
  }
250
245
 
@@ -338,8 +333,8 @@ type PageIndexEntry = {
338
333
  * themselves, so every module instance drops the same entry on `setBlocks()`.
339
334
  * The compiled matchers live on the entries and go away with them.
340
335
  */
341
- const pageIndexCache: WeakMap<Record<string, unknown>, PageIndexEntry[]> =
342
- G.__deco.pageIndexCache ?? (G.__deco.pageIndexCache = new WeakMap());
336
+ const pageIndexCache: WeakMap<Record<string, unknown>, PageIndexEntry[]> = G.__deco
337
+ .pageIndexCache ?? (G.__deco.pageIndexCache = new WeakMap());
343
338
 
344
339
  function buildPageIndex(blocks: Record<string, unknown>): PageIndexEntry[] {
345
340
  const pages: Array<PageIndexEntry & { key2: [number, number, number] }> = [];
@@ -508,10 +503,7 @@ function assertURLPattern() {
508
503
  * `URLPattern` is native in browsers, workerd, Deno, and Node >= 24 (this
509
504
  * package's `engines` floor). Node 22 and older lack it.
510
505
  */
511
- export function matchPath(
512
- pattern: string,
513
- urlPath: string,
514
- ): Record<string, string> | null {
506
+ export function matchPath(pattern: string, urlPath: string): Record<string, string> | null {
515
507
  assertURLPattern();
516
508
  return execPattern(cachedPattern(pattern), urlPath);
517
509
  }
@@ -1,10 +1,5 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- decodeBase64,
4
- decodeBase64Url,
5
- encodeBase64,
6
- encodeBase64Url,
7
- } from "./encoding";
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import { decodeBase64, decodeBase64Url, encodeBase64, encodeBase64Url } from "./encoding";
8
3
 
9
4
  describe("encodeBase64 / decodeBase64", () => {
10
5
  it("round-trips ASCII strings", () => {
@@ -39,8 +34,31 @@ describe("encodeBase64 / decodeBase64", () => {
39
34
  const bytes = new Uint8Array(0x8000 + 7);
40
35
  for (let i = 0; i < bytes.length; i++) bytes[i] = i & 0xff;
41
36
  const b64 = encodeBase64(bytes);
37
+ expect(b64).toBe(Buffer.from(bytes).toString("base64"));
42
38
  expect(decodeBase64(b64)).toEqual(bytes);
43
39
  });
40
+
41
+ it("uses the runtime's native Uint8Array base64 when present (workerd)", () => {
42
+ const proto = Uint8Array.prototype as unknown as { toBase64?: () => string };
43
+ const ctor = Uint8Array as unknown as { fromBase64?: (b64: string) => Uint8Array };
44
+ const had = { to: proto.toBase64, from: ctor.fromBase64 };
45
+ const toBase64 = vi.fn(function (this: Uint8Array) {
46
+ return Buffer.from(this).toString("base64");
47
+ });
48
+ const fromBase64 = vi.fn((b64: string) => new Uint8Array(Buffer.from(b64, "base64")));
49
+ proto.toBase64 = toBase64;
50
+ ctor.fromBase64 = fromBase64;
51
+ try {
52
+ const bytes = new Uint8Array([104, 105, 255, 0]);
53
+ expect(encodeBase64(bytes)).toBe("aGn/AA==");
54
+ expect(decodeBase64("aGn/AA==")).toEqual(bytes);
55
+ expect(toBase64).toHaveBeenCalledOnce();
56
+ expect(fromBase64).toHaveBeenCalledOnce();
57
+ } finally {
58
+ proto.toBase64 = had.to;
59
+ ctor.fromBase64 = had.from;
60
+ }
61
+ });
44
62
  });
45
63
 
46
64
  describe("encodeBase64Url / decodeBase64Url", () => {
@@ -50,9 +68,7 @@ describe("encodeBase64Url / decodeBase64Url", () => {
50
68
  const standard = encodeBase64(bytes);
51
69
  const url = encodeBase64Url(bytes);
52
70
  // Every '+' becomes '-', '/' becomes '_', trailing '=' is stripped.
53
- expect(url).toBe(
54
- standard.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""),
55
- );
71
+ expect(url).toBe(standard.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""));
56
72
  expect(url).not.toContain("+");
57
73
  expect(url).not.toContain("/");
58
74
  expect(url).not.toContain("=");
@@ -14,19 +14,28 @@ function toBytes(data: ArrayBuffer | Uint8Array | string): Uint8Array {
14
14
  return data;
15
15
  }
16
16
 
17
+ type NativeBase64 = { toBase64?: () => string };
18
+ type NativeFromBase64 = { fromBase64?: (b64: string) => Uint8Array<ArrayBuffer> };
19
+
17
20
  export function encodeBase64(data: ArrayBuffer | Uint8Array | string): string {
18
21
  const bytes = toBytes(data);
19
- // Build the binary string in chunks to avoid blowing the call stack on
20
- // large inputs (`String.fromCharCode(...bytes)` spreads the entire array).
22
+ // workerd encodes natively, straight from the bytes, with the same output as btoa().
23
+ const native = (bytes as NativeBase64).toBase64;
24
+ if (native) return native.call(bytes);
25
+ // Chunked so a large input doesn't blow the call stack. `apply`, not a spread: spreading
26
+ // a Uint8Array goes through its iterator, one `{ value, done }` object per byte, ~24 MB
27
+ // of garbage for a 1 MB HTML body.
21
28
  let bin = "";
22
29
  const CHUNK = 0x8000;
23
30
  for (let i = 0; i < bytes.byteLength; i += CHUNK) {
24
- bin += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
31
+ bin += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK) as unknown as number[]);
25
32
  }
26
33
  return btoa(bin);
27
34
  }
28
35
 
29
36
  export function decodeBase64(b64: string): Uint8Array<ArrayBuffer> {
37
+ const native = (Uint8Array as unknown as NativeFromBase64).fromBase64;
38
+ if (native) return native(b64);
30
39
  const bin = atob(b64);
31
40
  const out = new Uint8Array(bin.length);
32
41
  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
@@ -1,5 +1,5 @@
1
1
  import type { CacheStorage } from "./cacheStorage";
2
- import { decodeBase64 } from "./encoding";
2
+ import { decodeBase64, encodeBase64 } from "./encoding";
3
3
 
4
4
  interface StoredResponse {
5
5
  status: number;
@@ -76,15 +76,11 @@ export function createResponseCache(storage: CacheStorage, scope: string) {
76
76
  bytes.set(chunk, offset);
77
77
  offset += chunk.byteLength;
78
78
  }
79
- let binary = "";
80
- for (let i = 0; i < bytes.length; i += 8192) {
81
- binary += String.fromCharCode(...bytes.subarray(i, i + 8192));
82
- }
83
79
  const value: StoredResponse = {
84
80
  status: response.status,
85
81
  statusText: response.statusText,
86
82
  headers: [...response.headers.entries()],
87
- body: btoa(binary),
83
+ body: encodeBase64(bytes),
88
84
  };
89
85
  try {
90
86
  await storage.set(keyFor(request), JSON.stringify(value), expiresAt);