@decocms/blocks 7.86.4 → 7.86.5

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.4",
3
+ "version": "7.86.5",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24"
@@ -169,6 +169,30 @@ it("retains non-JSON values locally without silently corrupting them in KV", asy
169
169
  });
170
170
  });
171
171
 
172
+ it("serializes a cached value once per write and not at all on a storage hit", async () => {
173
+ const storage = createKVCacheStorage(fakeKV());
174
+ const value = { items: [{ id: 1 }, { id: 2 }] };
175
+ const stringify = vi.spyOn(JSON, "stringify");
176
+ const ofValue = () =>
177
+ stringify.mock.calls.filter(([v]) => v === value || (v as { value?: unknown })?.value === value)
178
+ .length;
179
+ const writer = createCacheStore<typeof value>("once");
180
+ await run(storage, "site", async () => {
181
+ writer.set(writer.key("k"), value, Date.now() + 60_000);
182
+ await flush();
183
+ });
184
+ expect(ofValue()).toBe(1);
185
+ stringify.mockClear();
186
+ const reader = createCacheStore<typeof value>("once");
187
+ const hit = await run(storage, "site", () => reader.read(reader.key("k")));
188
+ expect(hit).toEqual(value);
189
+ // Sizing the memory tier reuses the raw text it just parsed.
190
+ expect(
191
+ stringify.mock.calls.filter(([v]) => (v as { items?: unknown })?.items !== undefined),
192
+ ).toHaveLength(0);
193
+ stringify.mockRestore();
194
+ });
195
+
172
196
  it("deduplicates a cold loader through slow storage and survives a memory wipe", async () => {
173
197
  const storage = createKVCacheStorage(fakeKV());
174
198
  const fn = vi.fn(async () => ({ product: 42 }));
@@ -118,7 +118,10 @@ export function createKVCacheStorage(
118
118
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return;
119
119
  const raw = JSON.stringify({ value, expiresAt });
120
120
  // Leave space below KV's 25 MiB value limit. Oversized cache entries are optional.
121
- if (new TextEncoder().encode(raw).byteLength > 25 * 1024 * 1024) return;
121
+ // UTF-8 takes at most 3 bytes per UTF-16 unit, so only a value that long needs the
122
+ // exact count: encoding every write copied each entry once more just to measure it.
123
+ const limit = 25 * 1024 * 1024;
124
+ if (raw.length * 3 > limit && new TextEncoder().encode(raw).byteLength > limit) return;
122
125
  await kv.put(await keyFor(key), raw, {
123
126
  expirationTtl: Math.max(60, Math.ceil((expiresAt - Date.now()) / 1000)),
124
127
  });
@@ -175,7 +178,9 @@ function serialize(value: unknown): string | undefined {
175
178
  throw new Error("Unsupported cached object");
176
179
  }
177
180
  seen.add(v);
178
- for (const item of Object.values(v)) check(item);
181
+ // Index and key loops: `Object.values` copied every array and object it walked.
182
+ if (Array.isArray(v)) for (let i = 0; i < v.length; i++) check(v[i]);
183
+ else for (const key in v) check((v as Record<string, unknown>)[key]);
179
184
  seen.delete(v);
180
185
  }
181
186
  check(value);
@@ -203,13 +208,14 @@ export function createCacheStore<T>(
203
208
  if (entry) bytes -= entry.bytes;
204
209
  local.delete(key);
205
210
  }
206
- function remember(key: string, value: T, expiresAt: number) {
211
+ /** `json`: the value's serialization when the caller already has it, so sizing doesn't stringify again. */
212
+ function remember(key: string, value: T, expiresAt: number, json?: string) {
207
213
  remove(key);
208
214
  let size: number;
209
215
  try {
210
216
  size = sizeOf
211
217
  ? sizeOf(value)
212
- : Math.max(512, (key.length + (JSON.stringify(value)?.length ?? 0)) * 2);
218
+ : Math.max(512, (key.length + ((json ?? JSON.stringify(value))?.length ?? 0)) * 2);
213
219
  } catch {
214
220
  size = 1024;
215
221
  }
@@ -252,7 +258,7 @@ export function createCacheStore<T>(
252
258
  if (raw === null) return undefined;
253
259
  const entry = JSON.parse(raw) as { value: T; expiresAt: number };
254
260
  if (!Number.isFinite(entry.expiresAt) || Date.now() >= entry.expiresAt) return undefined;
255
- remember(key, entry.value, entry.expiresAt);
261
+ remember(key, entry.value, entry.expiresAt, raw);
256
262
  return entry.value;
257
263
  } catch {
258
264
  return undefined;
@@ -265,15 +271,16 @@ export function createCacheStore<T>(
265
271
  expiresAt <= Date.now()
266
272
  )
267
273
  return;
268
- remember(key, value, expiresAt);
269
- const storage = getCacheStorageContext()?.storage;
270
- if (!persist || !storage || !Number.isFinite(expiresAt)) return;
274
+ const storage = persist ? getCacheStorageContext()?.storage : null;
275
+ let raw: string | undefined;
271
276
  try {
272
- const raw = serialize({ value, expiresAt });
273
- if (raw !== undefined) cacheBackground(storage.set(key, raw, expiresAt));
277
+ if (storage) raw = serialize({ value, expiresAt });
274
278
  } catch {
275
279
  /* Non-serializable results remain in the memory tier. */
276
280
  }
281
+ // The memory tier is sized from the same serialization the storage gets.
282
+ remember(key, value, expiresAt, raw);
283
+ if (storage && raw !== undefined) cacheBackground(storage.set(key, raw, expiresAt));
277
284
  },
278
285
  delete(key: string): void {
279
286
  remove(key);