@decocms/blocks 8.10.0 → 8.12.0

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.
Files changed (210) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js.map +1 -1
  4. package/dist/protocol/conformance/blockMetaVectors.json +80 -0
  5. package/dist/protocol/index.d.ts +5 -2
  6. package/dist/protocol/index.d.ts.map +1 -1
  7. package/dist/protocol/index.js +5 -2
  8. package/dist/protocol/index.js.map +1 -1
  9. package/dist/v8/blockMeta.d.ts +33 -4
  10. package/dist/v8/blockMeta.d.ts.map +1 -1
  11. package/dist/v8/blockMeta.js +70 -13
  12. package/dist/v8/blockMeta.js.map +1 -1
  13. package/dist/v8/cli/index.d.ts +1 -0
  14. package/dist/v8/cli/index.d.ts.map +1 -1
  15. package/dist/v8/cli/index.js +1 -0
  16. package/dist/v8/cli/index.js.map +1 -1
  17. package/dist/v8/cli/run.d.ts +2 -0
  18. package/dist/v8/cli/run.d.ts.map +1 -1
  19. package/dist/v8/cli/run.js +30 -1
  20. package/dist/v8/cli/run.js.map +1 -1
  21. package/dist/v8/cli/skills.d.ts +25 -0
  22. package/dist/v8/cli/skills.d.ts.map +1 -0
  23. package/dist/v8/cli/skills.js +70 -0
  24. package/dist/v8/cli/skills.js.map +1 -0
  25. package/dist/v8/client.d.ts +6 -4
  26. package/dist/v8/client.d.ts.map +1 -1
  27. package/dist/v8/client.js +26 -70
  28. package/dist/v8/client.js.map +1 -1
  29. package/dist/v8/cms.d.ts.map +1 -1
  30. package/dist/v8/cms.js +1 -2
  31. package/dist/v8/cms.js.map +1 -1
  32. package/dist/v8/contentIndex.d.ts +18 -7
  33. package/dist/v8/contentIndex.d.ts.map +1 -1
  34. package/dist/v8/contentIndex.js +46 -17
  35. package/dist/v8/contentIndex.js.map +1 -1
  36. package/dist/v8/draftChanges.d.ts.map +1 -1
  37. package/dist/v8/draftChanges.js +4 -1
  38. package/dist/v8/draftChanges.js.map +1 -1
  39. package/dist/v8/index.d.ts +1 -1
  40. package/dist/v8/index.d.ts.map +1 -1
  41. package/dist/v8/remoteLoader.d.ts +4 -2
  42. package/dist/v8/remoteLoader.d.ts.map +1 -1
  43. package/dist/v8/remoteLoader.js +13 -3
  44. package/dist/v8/remoteLoader.js.map +1 -1
  45. package/dist/v8/types.d.ts +47 -7
  46. package/dist/v8/types.d.ts.map +1 -1
  47. package/package.json +3 -2
  48. package/skills/deco-apps/SKILL.md +82 -0
  49. package/skills/deco-apps/references/algolia.md +51 -0
  50. package/skills/deco-apps/references/commerce-types.md +132 -0
  51. package/skills/deco-apps/references/instrumented-fetch.md +144 -0
  52. package/skills/deco-apps/references/magento.md +55 -0
  53. package/skills/deco-apps/references/messaging.md +76 -0
  54. package/skills/deco-apps/references/shopify.md +69 -0
  55. package/skills/deco-apps/references/vendored-loaders.md +135 -0
  56. package/skills/deco-apps/references/vtex-cookies-auth.md +146 -0
  57. package/skills/deco-apps/references/vtex.md +150 -0
  58. package/skills/deco-apps/references/wake.md +75 -0
  59. package/skills/deco-cms-schema/SKILL.md +80 -0
  60. package/skills/deco-cms-schema/references/annotations.md +147 -0
  61. package/skills/deco-cms-schema/references/content-hygiene.md +91 -0
  62. package/skills/deco-cms-schema/references/formats-and-widgets.md +112 -0
  63. package/skills/deco-cms-schema/references/shapes-that-break-the-form.md +165 -0
  64. package/skills/deco-cms-schema/references/types-to-fields.md +112 -0
  65. package/skills/deco-go-live/SKILL.md +127 -0
  66. package/skills/deco-go-live/references/content-releases.md +90 -0
  67. package/skills/deco-go-live/references/process.md +106 -0
  68. package/skills/deco-go-live/references/proxy-headers-checkout.md +139 -0
  69. package/skills/deco-go-live/references/qa-checklist-template.md +150 -0
  70. package/skills/deco-go-live/references/qa-inventory.md +120 -0
  71. package/skills/deco-go-live/references/react-spa.md +183 -0
  72. package/skills/deco-go-live/references/seo-analytics.md +114 -0
  73. package/skills/deco-go-live/references/traffic-ramp.md +87 -0
  74. package/skills/deco-go-live/references/worker-runtime.md +93 -0
  75. package/skills/deco-go-live/scripts/preflight.sh +221 -0
  76. package/skills/deco-images-media/SKILL.md +64 -0
  77. package/skills/deco-images-media/references/asset-upload.md +191 -0
  78. package/skills/deco-images-media/references/components-per-binding.md +167 -0
  79. package/skills/deco-images-media/references/providers-and-cdn.md +145 -0
  80. package/skills/deco-images-media/references/quality-and-lcp.md +93 -0
  81. package/skills/deco-images-media/references/troubleshooting.md +147 -0
  82. package/skills/deco-images-media/references/video.md +122 -0
  83. package/skills/deco-make-editable/SKILL.md +94 -0
  84. package/skills/deco-make-editable/references/a11y-and-e2e.md +104 -0
  85. package/skills/deco-make-editable/references/content-shapes.md +203 -0
  86. package/skills/deco-make-editable/references/from-figma.md +110 -0
  87. package/skills/deco-make-editable/references/i18n-fields.md +112 -0
  88. package/skills/deco-make-editable/references/inventory.md +79 -0
  89. package/skills/deco-make-editable/references/pixel-parity.md +175 -0
  90. package/skills/deco-make-editable/references/seeding-content.md +119 -0
  91. package/skills/deco-nextjs-site/SKILL.md +74 -0
  92. package/skills/deco-nextjs-site/references/caching.md +116 -0
  93. package/skills/deco-nextjs-site/references/metadata-seo.md +100 -0
  94. package/skills/deco-nextjs-site/references/proxy-and-drafts.md +177 -0
  95. package/skills/deco-nextjs-site/references/rendering.md +172 -0
  96. package/skills/deco-nextjs-site/references/setup.md +190 -0
  97. package/skills/deco-nextjs-site/references/studio-bridge.md +130 -0
  98. package/skills/deco-site-authoring/SKILL.md +75 -0
  99. package/skills/deco-site-authoring/references/lazy-blocks.md +155 -0
  100. package/skills/deco-site-authoring/references/loaders.md +192 -0
  101. package/skills/deco-site-authoring/references/pages.md +158 -0
  102. package/skills/deco-site-authoring/references/review-before-publish.md +95 -0
  103. package/skills/deco-site-authoring/references/sections.md +158 -0
  104. package/skills/deco-site-authoring/references/seo.md +116 -0
  105. package/skills/deco-site-workflow/SKILL.md +101 -0
  106. package/skills/deco-site-workflow/references/check.md +116 -0
  107. package/skills/deco-site-workflow/references/cli-reference.md +106 -0
  108. package/skills/deco-site-workflow/references/content-layout.md +93 -0
  109. package/skills/deco-site-workflow/references/content-sync.md +146 -0
  110. package/skills/deco-site-workflow/references/delivery.md +51 -0
  111. package/skills/deco-site-workflow/references/deploy.md +87 -0
  112. package/skills/deco-site-workflow/references/schema.md +173 -0
  113. package/skills/deco-site-workflow/references/serve-and-studio.md +138 -0
  114. package/skills/deco-storefront-caching/SKILL.md +67 -0
  115. package/skills/deco-storefront-caching/references/cache-keys.md +129 -0
  116. package/skills/deco-storefront-caching/references/case-study.md +82 -0
  117. package/skills/deco-storefront-caching/references/egress-traps.md +153 -0
  118. package/skills/deco-storefront-caching/references/nextjs.md +60 -0
  119. package/skills/deco-storefront-caching/references/perf-guardrails-e2e.md +123 -0
  120. package/skills/deco-storefront-caching/references/verification.md +136 -0
  121. package/skills/deco-storefront-caching/references/worker-page-cache.md +160 -0
  122. package/skills/deco-storefront-caching/scripts/html-anatomy.mjs +97 -0
  123. package/skills/deco-storefront-performance/SKILL.md +81 -0
  124. package/skills/deco-storefront-performance/references/cls-third-party.md +90 -0
  125. package/skills/deco-storefront-performance/references/hydration.md +116 -0
  126. package/skills/deco-storefront-performance/references/loaders-n-plus-1.md +107 -0
  127. package/skills/deco-storefront-performance/references/navigation-ux.md +130 -0
  128. package/skills/deco-storefront-performance/references/payload-trim.md +163 -0
  129. package/skills/deco-storefront-performance/references/render-location.md +152 -0
  130. package/skills/deco-storefront-performance/references/request-dedupe.md +147 -0
  131. package/skills/deco-storefront-performance/references/trace-reading.md +79 -0
  132. package/skills/deco-storefront-performance/references/worker-memory.md +176 -0
  133. package/skills/deco-tanstack-site/SKILL.md +68 -0
  134. package/skills/deco-tanstack-site/references/document-and-security.md +155 -0
  135. package/skills/deco-tanstack-site/references/router-and-navigation.md +137 -0
  136. package/skills/deco-tanstack-site/references/routes-and-pages.md +183 -0
  137. package/skills/deco-tanstack-site/references/server-functions.md +123 -0
  138. package/skills/deco-tanstack-site/references/setup.md +153 -0
  139. package/skills/deco-tanstack-site/references/worker-entry.md +152 -0
  140. package/skills/deco-v7-to-v8-migration/SKILL.md +123 -0
  141. package/skills/deco-v7-to-v8-migration/references/caching-and-privacy.md +10 -0
  142. package/skills/deco-v7-to-v8-migration/references/content.md +25 -0
  143. package/skills/deco-v7-to-v8-migration/references/editor-forms.md +27 -0
  144. package/skills/deco-v7-to-v8-migration/references/faststore.md +40 -0
  145. package/skills/deco-v7-to-v8-migration/references/framework-code.md +53 -0
  146. package/skills/deco-v7-to-v8-migration/references/hosted-releases.md +16 -0
  147. package/skills/deco-v7-to-v8-migration/references/import-map.md +81 -0
  148. package/skills/deco-v7-to-v8-migration/references/legacy-names.md +33 -0
  149. package/skills/deco-v7-to-v8-migration/references/manual-steps.md +10 -0
  150. package/skills/deco-v7-to-v8-migration/references/native-apps.md +43 -0
  151. package/skills/deco-v7-to-v8-migration/references/nextjs.md +19 -0
  152. package/skills/deco-v7-to-v8-migration/references/parity.md +66 -0
  153. package/skills/deco-v7-to-v8-migration/references/rendering.md +13 -0
  154. package/skills/deco-v7-to-v8-migration/references/running-the-script.md +29 -0
  155. package/skills/deco-v7-to-v8-migration/references/script-steps.md +13 -0
  156. package/skills/deco-v7-to-v8-migration/references/server-functions.md +15 -0
  157. package/skills/deco-v7-to-v8-migration/references/sibling-port.md +11 -0
  158. package/skills/deco-v7-to-v8-migration/references/site-code.md +15 -0
  159. package/skills/deco-v7-to-v8-migration/references/telemetry.md +10 -0
  160. package/skills/deco-v7-to-v8-migration/references/verify.md +23 -0
  161. package/skills/deco-v7-to-v8-migration/scripts/apps.ts +297 -0
  162. package/skills/deco-v7-to-v8-migration/scripts/asyncRendering.ts +73 -0
  163. package/skills/deco-v7-to-v8-migration/scripts/blockMap.ts +584 -0
  164. package/skills/deco-v7-to-v8-migration/scripts/checkContentReads.ts +32 -0
  165. package/skills/deco-v7-to-v8-migration/scripts/ciSchemaCheck.ts +145 -0
  166. package/skills/deco-v7-to-v8-migration/scripts/compat.ts +357 -0
  167. package/skills/deco-v7-to-v8-migration/scripts/content.ts +121 -0
  168. package/skills/deco-v7-to-v8-migration/scripts/contentReads.ts +157 -0
  169. package/skills/deco-v7-to-v8-migration/scripts/experiments.ts +81 -0
  170. package/skills/deco-v7-to-v8-migration/scripts/framework.ts +61 -0
  171. package/skills/deco-v7-to-v8-migration/scripts/imageCopy.ts +276 -0
  172. package/skills/deco-v7-to-v8-migration/scripts/imageModule.ts +285 -0
  173. package/skills/deco-v7-to-v8-migration/scripts/imports.ts +942 -0
  174. package/skills/deco-v7-to-v8-migration/scripts/invoke.ts +624 -0
  175. package/skills/deco-v7-to-v8-migration/scripts/legacyNames.ts +45 -0
  176. package/skills/deco-v7-to-v8-migration/scripts/main.ts +59 -0
  177. package/skills/deco-v7-to-v8-migration/scripts/matchers.ts +41 -0
  178. package/skills/deco-v7-to-v8-migration/scripts/migrate.ts +180 -0
  179. package/skills/deco-v7-to-v8-migration/scripts/redirects.ts +455 -0
  180. package/skills/deco-v7-to-v8-migration/scripts/report.ts +50 -0
  181. package/skills/deco-v7-to-v8-migration/scripts/scaffold.ts +1119 -0
  182. package/skills/deco-v7-to-v8-migration/scripts/secrets.ts +35 -0
  183. package/skills/deco-v7-to-v8-migration/scripts/sectionLoaders.ts +216 -0
  184. package/skills/deco-v7-to-v8-migration/scripts/siteSettings.ts +261 -0
  185. package/skills/deco-v7-to-v8-migration/scripts/stubs.ts +388 -0
  186. package/skills/deco-v7-to-v8-migration/scripts/tsconfig.json +7 -0
  187. package/skills/deco-v7-to-v8-migration/scripts/vendor.ts +249 -0
  188. package/skills/deco-v7-to-v8-migration/scripts/vtexInvoke.ts +240 -0
  189. package/skills/deco-v7-to-v8-migration/scripts/walk.ts +30 -0
  190. package/skills/deco-variants/SKILL.md +57 -0
  191. package/skills/deco-variants/references/caching-variants.md +63 -0
  192. package/skills/deco-variants/references/custom-matchers.md +83 -0
  193. package/skills/deco-variants/references/draft-preview.md +59 -0
  194. package/skills/deco-variants/references/experiments-and-campaigns.md +104 -0
  195. package/skills/deco-variants/references/multivariate.md +85 -0
  196. package/skills/deco-variants/references/v7-matchers.md +71 -0
  197. package/src/index.ts +1 -1
  198. package/src/protocol/conformance/blockMetaVectors.json +80 -0
  199. package/src/protocol/index.ts +8 -1
  200. package/src/v8/blockMeta.ts +75 -11
  201. package/src/v8/cli/index.ts +1 -0
  202. package/src/v8/cli/run.ts +35 -1
  203. package/src/v8/cli/skills.ts +91 -0
  204. package/src/v8/client.ts +32 -77
  205. package/src/v8/cms.ts +1 -2
  206. package/src/v8/contentIndex.ts +49 -19
  207. package/src/v8/draftChanges.ts +5 -1
  208. package/src/v8/index.ts +1 -1
  209. package/src/v8/remoteLoader.ts +13 -3
  210. package/src/v8/types.ts +48 -7
@@ -0,0 +1,147 @@
1
+ # Duplicate upstream calls in one page
2
+
3
+ Load when: the same upstream operation runs several times for one page; two sections
4
+ fetch the same product; you need to count calls before and after a change.
5
+
6
+ On a v7 storefront, removing duplicates cut a product page from 40+ VTEX calls to about 8.
7
+ v8 already removes some duplicates for you. Know which ones before you write code.
8
+
9
+ ## What the client dedupes for you
10
+
11
+ A client (`cms.client(...)`, or `contentClient(cms, request)` on TanStack) runs each
12
+ block function **once per distinct input**. The memo key is the function plus its inputs
13
+ in canonical form (key order does not matter). Every other occurrence in the same client
14
+ gets the same promise and the same result object. So a product loader named by the PDP
15
+ section and by the SEO block, with equal props, runs once.
16
+
17
+ It stops working when:
18
+
19
+ | Case | Why | Fix |
20
+ |---|---|---|
21
+ | Inputs differ by one prop (`count: 12` vs `count: 24`, an extra facet) | Different key | Make them equal, or have one block take the larger result and slice |
22
+ | Code calls a client or a helper directly instead of naming a block in content | The memo only sees blocks the resolver runs | Make the shared data a block, or memoize per request (below) |
23
+ | Two clients for one request (one in the page loader, one in another loader or server function) | The memo belongs to one client | Create one client per request and pass it down |
24
+ | Two requests (hover prefetch then click, the page then a server function) | Nothing is shared between requests | An upstream cache: `deco-storefront-caching` |
25
+ | An input holds a value with no canonical form (a function, a class instance) | No key, so no memo | Keep block inputs plain JSON |
26
+
27
+ Results are shared, so they are read-only. Copy before you change one: an in-place edit
28
+ changes every other place that got the same object.
29
+
30
+ ## Make equal blocks equal: save the loader once
31
+
32
+ When several sections call the same loader with the same props, save that loader as one
33
+ named block and reference it from each section, instead of repeating the props inline:
34
+
35
+ ```jsonc
36
+ // the saved block "Shelf - Best sellers"
37
+ { "__resolveType": "product-list", "collection": "334", "count": 12 }
38
+
39
+ // in each section that needs it
40
+ "products": { "__resolveType": "Shelf - Best sellers" }
41
+ ```
42
+
43
+ A reference resolves to `{ ...saved, ...overrides }`. With no overrides, every reference
44
+ reaches the loader with identical inputs, so the client runs it once. An override in one
45
+ place (a different `count`) makes a second call there, which is what you want.
46
+
47
+ This also stops the copies drifting apart when someone edits one of them in Studio.
48
+
49
+ ## Memoize code that is not a block, per request
50
+
51
+ A helper called from several block functions (`getProductBySlug` used by the PDP section
52
+ and the breadcrumb) does not go through the memo. Key a memo on the current client, which
53
+ is one per request:
54
+
55
+ ```ts
56
+ // src/perRequest.ts
57
+ import { currentClient, type Client } from "@decocms/blocks";
58
+
59
+ const memos = new WeakMap<Client, Map<string, Promise<unknown>>>();
60
+
61
+ /** Runs `load` once per request for `key`. Call it from inside a block function. */
62
+ export function oncePerRequest<T>(key: string, load: () => Promise<T>): Promise<T> {
63
+ const client = currentClient();
64
+ let memo = memos.get(client);
65
+ if (!memo) memos.set(client, (memo = new Map()));
66
+ let pending = memo.get(key) as Promise<T> | undefined;
67
+ if (!pending) {
68
+ pending = load();
69
+ memo.set(key, pending);
70
+ }
71
+ return pending;
72
+ }
73
+ ```
74
+
75
+ `currentClient()` returns the client that is running the block function. It works before
76
+ the function's first `await` everywhere, and across `await` where the runtime has
77
+ `AsyncLocalStorage` (Workers with `nodejs_compat`). Outside a block function it throws.
78
+ The `WeakMap` lets the memo go with the client at the end of the request. Do not use a
79
+ module-level `Map` keyed by URL instead: it is shared by every request in the isolate,
80
+ never expires, and mixes shoppers.
81
+
82
+ Do not memoize shopper-scoped calls (cart, session, anything sent with the shopper's
83
+ cookie) under a key that leaves the cookie out.
84
+
85
+ ## Count the calls
86
+
87
+ Do this before and after every change. Three ways, from quickest to most complete.
88
+
89
+ **Dev: log every upstream call.** The thin clients take a `fetch` option. Pass a wrapper:
90
+
91
+ ```ts
92
+ // src/clients/vtex.ts
93
+ import { createVtexClient } from "@decocms/apps-vtex";
94
+
95
+ const logged: typeof fetch = async (input, init) => {
96
+ const t0 = performance.now();
97
+ const response = await fetch(input, init);
98
+ const url = new URL(input instanceof Request ? input.url : String(input));
99
+ console.log(`[upstream] ${init?.method ?? "GET"} ${url.pathname} ${response.status} ${Math.round(performance.now() - t0)}ms`);
100
+ return response;
101
+ };
102
+
103
+ export const vtex = createVtexClient({ account: "mystore", fetch: import.meta.env.DEV ? logged : undefined });
104
+ ```
105
+
106
+ The option is documented as the fetch underneath, for tests. It sits below the client's
107
+ retry, so a retried call logs one line per attempt. Load one page and sort the lines:
108
+ `sort | uniq -c | sort -rn`. One line per operation is
109
+ the goal. Several lines with the same path is a duplicate; one line per product is an N+1
110
+ ([`loaders-n-plus-1.md`](./loaders-n-plus-1.md)). Never log query strings or cookies to a
111
+ shared log.
112
+
113
+ **Production: the client metric.** Every `@decocms/apps-*` client measures each request
114
+ once as `http.client.request.duration`, labelled `provider`, `operation` (for VTEX, a
115
+ stable name such as `intelligent-search.product_search` or `catalog.crossselling.similars`),
116
+ `status_class`, `cached` and `retries`. The worker records `http.server.request.duration`
117
+ with `http.route`. Over the same window, calls of one operation divided by page requests
118
+ of one route is the calls-per-page ratio. It is an estimate when several routes use the
119
+ operation. Both metrics need a telemetry destination on `createCMS` (a `token`, or a
120
+ `telemetry.endpoint`).
121
+
122
+ **Browser: a HAR.** Upstream calls made on the server never appear in the browser. A HAR
123
+ shows the other half: `/_serverFn/` requests (one per client-side navigation or prefetch)
124
+ and calls client components make straight to the commerce API (cart, simulation).
125
+
126
+ ```python
127
+ import json, collections, sys
128
+ entries = json.load(open(sys.argv[1]))["log"]["entries"]
129
+ count = collections.Counter(
130
+ e["request"]["url"].split("?")[0] for e in entries
131
+ if "/_serverFn/" in e["request"]["url"] or "/api/" in e["request"]["url"]
132
+ )
133
+ for url, n in count.most_common(20):
134
+ print(f"{n:4}x {url}")
135
+ ```
136
+
137
+ Record the HAR with a script (Playwright's `recordHar`) rather than by hand, so the before
138
+ and after runs do the same clicks. Do not wait on `networkidle`; wait for a selector.
139
+
140
+ ## Typical duplicates on a VTEX store
141
+
142
+ | Symptom | Usual cause | Fix |
143
+ |---|---|---|
144
+ | Same product search 2-4 times on a PDP | PDP section, related products and breadcrumb each resolve the product | One loader block, referenced by each (above), or `oncePerRequest` |
145
+ | Same cross-selling call twice | Two shelves for the same product and type | Same block, same inputs |
146
+ | Simulation once per card | Per-item call | Batch into one `items` array ([`loaders-n-plus-1.md`](./loaders-n-plus-1.md)) |
147
+ | `/_serverFn/` twice for one click | Hover prefetch with different search params than the click | [`navigation-ux.md`](./navigation-ux.md) |
@@ -0,0 +1,79 @@
1
+ # Reading a Chrome Performance trace, and measuring without fooling yourself
2
+
3
+ Load when: you need to know which element shifted, why the screen went blank for a moment,
4
+ or where a slow navigation spends its time; or your local numbers disagree with production.
5
+
6
+ A trace records which element moved, by how much, and what ran just before. It answers
7
+ questions the console and Lighthouse only hint at.
8
+
9
+ ## Record one
10
+
11
+ 1. DevTools, **Performance** panel.
12
+ 2. Turn on **Screenshots** (to see flashes) and **Web Vitals** (to see layout shifts).
13
+ 3. Set CPU and network throttling to match what you are debugging (mobile: 4x CPU, a
14
+ slow 4G profile).
15
+ 4. Record, then reproduce: a hard reload for load problems, a click for navigation
16
+ problems. Wait until the page settles (3 to 5 s), then stop.
17
+
18
+ Save it (the export button, a `.json` file) so someone else can load it, or open it in
19
+ Perfetto. Record the same steps before and after a fix.
20
+
21
+ ## Layout shifts (CLS)
22
+
23
+ 1. In the **Layout shifts** (or Experience) track, each shift is a marker. Click one.
24
+ 2. The summary shows its **score**, the **cumulative score**, and the **elements** that
25
+ moved. Click an element to jump to it in the Elements panel.
26
+ 3. Look just to the left of the shift on the **Network** and **Main** tracks: a script
27
+ finished, a stylesheet arrived, a font swapped, an image decoded. That is the cause.
28
+
29
+ Fixes are in [`cls-third-party.md`](./cls-third-party.md).
30
+
31
+ ## A flash or a blank frame
32
+
33
+ 1. In the screenshot strip at the top, find the white or half-painted frame. Note its time.
34
+ 2. On the **Main** track at that time, look for React work (`performConcurrentWorkOnRoot`,
35
+ hydration) and for a Suspense fallback commit.
36
+ 3. Check the console for a hydration error at the same moment.
37
+
38
+ A fallback during hydration usually means a component loaded with `React.lazy` was not
39
+ ready, or a block promise was still pending. See [`hydration.md`](./hydration.md#3-flashes-and-blank-frames).
40
+
41
+ ## A slow navigation
42
+
43
+ 1. Record while clicking a card or a menu link.
44
+ 2. On the **Network** track, find the `/_serverFn/` request. Its duration is the server's
45
+ share: routing, the page's blocks and the upstream.
46
+ 3. After it ends, look on **Main** for long tasks: rendering the new page, effects, a large
47
+ list. That is the browser's share.
48
+
49
+ If the server share dominates, go to [`render-location.md`](./render-location.md) and
50
+ count upstream calls ([`request-dedupe.md`](./request-dedupe.md#count-the-calls)). If two
51
+ `/_serverFn/` requests appear for one click, see [`navigation-ux.md`](./navigation-ux.md).
52
+
53
+ ## Measurement traps
54
+
55
+ These produced false conclusions on real storefronts.
56
+
57
+ - **A local preview without compression is for deltas, not absolutes.** One local FCP of
58
+ 11.7 s was a dev server sending 573 KB of HTML instead of 62 KB, and 364 KB of CSS
59
+ instead of 57 KB. Compare local against local.
60
+ - **A local build of `main` is not the deployed build.** A stale generated file made a
61
+ local chunk 1,215 kB against the deployed 908 kB: 307 kB of difference that did not exist.
62
+ Run the repo's codegen (`deco schema`, and `deco content` if the site bundles its
63
+ content) before the control build,
64
+ and check that the local asset hashes match the deployed ones.
65
+ - **Warm the cache for the right segment.** When the page cache keys by device, the first
66
+ hit with a mismatched User-Agent measures a cold render for the wrong segment. That
67
+ produced two fake "TTFB regressions" on one site. Warm up with the same UA you measure with.
68
+ - **One run is noise.** Take the median of five runs per side. Lighthouse varies more than
69
+ most fixes move it.
70
+ - **A hydration change needs a control.** Count the nodes that survive hydration and the
71
+ console errors on representative pages, on the base branch and on yours. Without the
72
+ control, 99.7% surviving tells you nothing.
73
+ - **Assert what must be there, not only what you removed.** After a change to the `<head>`
74
+ or the client bundle, check that the served HTML still loads the client entry script.
75
+ One change removed it with zero errors and zero warnings: the page rendered and never
76
+ hydrated.
77
+ - **Escaping is not waste.** Removing `encodeURIComponent` from JSON in an HTML attribute
78
+ to "save bytes" cost 8% more: React escapes `"` as `&quot;` (6 bytes) against `%22`
79
+ (3 bytes), and JSON is mostly quotes.
@@ -0,0 +1,176 @@
1
+ # Worker memory: measure per deploy, keep big data out of the isolate
2
+
3
+ Load when: the Worker logs "exceeded memory limit" (128 MB per isolate); memory P90 grew
4
+ after a deploy; a proxied sitemap, feed or export is large.
5
+
6
+ An isolate pays for everything reachable from module scope, for its whole life, in every
7
+ isolate. That is **resident** memory. A single request that holds a large body in JS is a
8
+ **peak**. They have different fixes, so find out which one you have first.
9
+
10
+ ## 1. What v8 keeps in an isolate
11
+
12
+ | Holder | Size | Notes |
13
+ |---|---|---|
14
+ | Content, with `createCMS({ site })` | The release index (`latest.json`, at most 16 MiB) and the previous one; block bodies in an LRU bounded at 32 MiB of JSON text; up to three old revisions' indexes when Studio previews them | Not in the bundle: fetched from the delivery CDN at runtime. Parsed objects take more heap than their JSON text |
15
+ | Content without `site` (`content` from `.deco/blocks.gen`) | The whole content module | Bundled, so resident in every isolate |
16
+ | Your module scope | Anything you import or build at top level | Large JSON or CSV imports, generated tables, unbounded `Map` caches |
17
+ | One request | Whatever it buffers | `await response.text()` on a proxied sitemap is the classic peak |
18
+
19
+ On v7, the bundled decofile was the largest resident item. A v8 site with `site` set does
20
+ not have it. When memory is high on v8, look at your own module scope and your proxies.
21
+
22
+ ## 2. Measure: Cloudflare GraphQL Analytics, per version
23
+
24
+ The dashboard rounds and hides the percentile you need. Query the same data.
25
+
26
+ - Endpoint: `https://api.cloudflare.com/client/v4/graphql`, with an API token that can
27
+ read account analytics.
28
+ - Dataset: `workersInvocationsAdaptive`. Quantiles `memoryUsageBytesP50…P999` (bytes),
29
+ `cpuTimeP50…P999` and `wallTimeP50…` (microseconds); sums `requests`, `errors`,
30
+ `subrequests`; dimensions `scriptName`, `scriptVersion`, `datetimeHour`,
31
+ `datetimeFiveMinutes`, `status`.
32
+
33
+ ```graphql
34
+ query($a: String!, $n: String!, $s: Time!, $e: Time!) {
35
+ viewer { accounts(filter: { accountTag: $a }) {
36
+ workersInvocationsAdaptive(limit: 2000, orderBy: [datetimeHour_ASC],
37
+ filter: { datetime_geq: $s, datetime_leq: $e, scriptName: $n }) {
38
+ dimensions { datetimeHour scriptVersion }
39
+ sum { requests }
40
+ quantiles { memoryUsageBytesP50 memoryUsageBytesP90 memoryUsageBytesP99 cpuTimeP50 cpuTimeP99 wallTimeP50 }
41
+ }
42
+ } }
43
+ }
44
+ ```
45
+
46
+ Group by `scriptVersion` to attribute memory to a deployed version directly. Narrow to
47
+ `datetimeFiveMinutes` once you know the hour. The versions list
48
+ (`GET /accounts/{account}/workers/scripts/{name}/versions`) has the deploy time under
49
+ `metadata.created_on`, not at the top level. A version's detail lists its bindings, which
50
+ answers "is that variable really set in production?".
51
+
52
+ ### Compare two windows honestly
53
+
54
+ - **Report P90.** It is what sits against the limit. P50 flatters; P999 is noisy.
55
+ - **Read memory, CPU and wall time together.** High wall with low CPU is waiting on I/O.
56
+ High CPU with low wall is computing. A story that fits two of them often fails the third.
57
+ - **Exclude the rollout** (5 to 10 minutes after the deploy, when two versions mix).
58
+ - **Compare windows of similar traffic** (check `sum { requests }`), take the median across
59
+ 5-minute buckets, and state how many buckets you used.
60
+
61
+ ### Prove causation
62
+
63
+ A drop right after your deploy may be someone else's deploy. Any one of these upgrades a
64
+ correlation to a cause:
65
+
66
+ 1. **A reversal.** Revert or switch off, and the metric moves back by the same amount.
67
+ 2. **An independent magnitude match.** A local measurement (parse the same data with
68
+ `node --expose-gc` and compare heap) predicts the same order of change.
69
+ 3. **A binding diff.** When no commit explains a regression, compare the bindings of the
70
+ last good version with the first bad one. On one store the only difference was one
71
+ added variable, which switched on a code path that had sat inert for weeks.
72
+
73
+ Without one of these, call the attribution tentative.
74
+
75
+ ## 3. Keep large tables out of the isolate
76
+
77
+ Any dataset bundled or built at module scope (redirect lists, geo tables, fixtures, a
78
+ product feed) is resident in every isolate. Measured on a v7 storefront: moving ~18k
79
+ redirect rows out of the bundle cut memory P90 by about 31 MB (−19%).
80
+
81
+ Move the long tail to Workers KV and look it up per request by key:
82
+
83
+ ```ts
84
+ // src/worker-entry.ts — normalize() and withDeadline() are your own helpers
85
+ export default createDecoWorker<Env>({
86
+ serverEntry, cms, dev: import.meta.env.DEV,
87
+ routes: async (request, env) => {
88
+ if (request.method !== "GET") return null;
89
+ const url = new URL(request.url);
90
+ if (url.pathname.startsWith("/assets/") || url.pathname.startsWith("/_serverFn/")) return null;
91
+ const key = `redir:${normalize(url.pathname)}`; // the same normalisation as the upload script
92
+ const hit = await withDeadline(env.REDIRECTS.get(key), 50); // fail open
93
+ if (!hit) return null;
94
+ const [status, to] = [Number(hit.slice(0, 3)), hit.slice(4)]; // value: "301:/new-path"
95
+ return new Response(null, { status, headers: { Location: url.search ? `${to}${url.search}` : to } });
96
+ },
97
+ });
98
+ ```
99
+
100
+ - Store a small string (`"301:/new-path"`), not JSON: one read, no parse.
101
+ - Upload with the exact normalisation the lookup uses. A mismatch is a silent 100% miss.
102
+ Wire the upload into the deploy script so KV is never behind the code.
103
+ - Point reads only. Never `list()` on a request path.
104
+ - `routes` runs for every request that gets past the CMS redirects, assets and server
105
+ functions included. Return `null` early for paths that are never redirected, so they
106
+ pay no KV read.
107
+ - Fail open: race the read against a short deadline and treat a timeout as "no redirect".
108
+ - Keep the editor-managed redirects in the `Redirects` block. They are few, and Studio
109
+ edits them. The CMS redirects run before `routes`, so they win.
110
+ - A table of a few dozen entries is not worth a KV read per request. Leave it in code.
111
+
112
+ A large `Redirects` block costs CPU on every request as well as memory. Numbers in
113
+ [`render-location.md`](./render-location.md#4-a-large-redirects-block-is-paid-on-every-request).
114
+
115
+ Also check for module-level caches that never evict (`const cache = new Map()` filled per
116
+ request). They grow until the isolate dies. Bound them, or use an upstream cache
117
+ (`deco-storefront-caching`).
118
+
119
+ ## 4. Stream large proxied bodies
120
+
121
+ KV fixes resident memory. A peak is one request materialising a big body: `await
122
+ response.text()` on a proxied sitemap, feed or CSV can push a lean isolate over the limit.
123
+ If you only rewrite a passthrough response, stream it:
124
+
125
+ ```ts
126
+ function rewriteStream(body: ReadableStream<Uint8Array>, replacements: [string, string][]) {
127
+ const to = new Map(replacements);
128
+ const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
129
+ const pattern = new RegExp(replacements.map(([from]) => escape(from)).join("|"), "g");
130
+ const keep = Math.max(...replacements.map(([from]) => from.length)) - 1;
131
+ const decoder = new TextDecoder();
132
+ const encoder = new TextEncoder();
133
+ let tail = "";
134
+ return body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
135
+ transform(chunk, out) {
136
+ const text = tail + decoder.decode(chunk, { stream: true });
137
+ const safe = text.length - keep; // a match starting here or later may be cut off
138
+ let done = "";
139
+ let last = 0;
140
+ for (const m of text.matchAll(pattern)) {
141
+ if (m.index >= safe) break;
142
+ done += text.slice(last, m.index) + to.get(m[0]);
143
+ last = m.index + m[0].length;
144
+ }
145
+ const cut = Math.max(last, safe);
146
+ done += text.slice(last, cut);
147
+ tail = text.slice(cut);
148
+ if (done) out.enqueue(encoder.encode(done));
149
+ },
150
+ flush(out) {
151
+ const rest = (tail + decoder.decode()).replace(pattern, (m) => to.get(m) ?? m);
152
+ if (rest) out.enqueue(encoder.encode(rest));
153
+ },
154
+ }));
155
+ }
156
+
157
+ // in routes: return new Response(rewriteStream(upstream.body!, [[ORIGIN, url.origin]]), { headers });
158
+ ```
159
+
160
+ The usual mistakes: no `flush` (drops the end of the body); holding back a fixed tail and
161
+ replacing only the part before it, which misses every match that straddles the cut (the
162
+ version above never emits text where a match could still start); and `decode(chunk)`
163
+ without `{ stream: true }` (breaks multi-byte characters split across chunks). Test with
164
+ chunk sizes from 1 byte up. Drop `content-length` from the copied headers, since the
165
+ length changes.
166
+
167
+ Find candidates: `grep -rnE "await (res|response|upstream)\.(text|arrayBuffer|json)\(\)" src/`
168
+ on proxy paths.
169
+
170
+ ## Checklist
171
+
172
+ - [ ] P90 memory per `scriptVersion`, before and after, with the rollout excluded
173
+ - [ ] No large JSON, CSV or generated table imported at module scope
174
+ - [ ] No unbounded module-level `Map`
175
+ - [ ] Proxied large bodies streamed, never buffered
176
+ - [ ] The win proved with a reversal or an independent measurement
@@ -0,0 +1,68 @@
1
+ ---
2
+ name: deco-tanstack-site
3
+ description: "Wiring a TanStack Start site to @decocms/tanstack 8 on Cloudflare Workers: createCMS and the block map (.deco/index.ts), the catch-all route with matchRoute, the page server function and its search params (loaderDeps, decoStringifySearch), createDecoWorker and the worker entry (routes, csp, preload, pageCache hook), createDecoRouter and decoServerFnFetch, DecoDocument (lang, head, Studio bridge) and DecoPreview, the security headers and Studio's CSP, and server functions in place of v7's /deco/invoke (top-level createServerFn().handler(), markPrivate, Set-Cookie). Load it when scaffolding a v8 TanStack site, wiring routes, the router or the worker, or debugging a page that renders, routes, redirects, previews or reloads wrong. Not for v7 sites (@decocms/blocks 7.x: the 7.x branch) or Next.js (deco-nextjs-site)."
4
+ ---
5
+
6
+ # Deco TanStack Start site (v8)
7
+
8
+ A v8 TanStack site is TanStack Start with four pieces from `@decocms/tanstack` around it: the
9
+ worker (`/worker`), the router (`/router`), the server-function fetch (`/start`) and the root
10
+ document (`/react`). Content comes from `@decocms/blocks`: `createCMS` over the site's block map,
11
+ and `matchRoute` to find the page for a URL. Everything else (routes, server functions, the page
12
+ cache, commerce code) is the site's own code.
13
+
14
+ Load this skill when you build or debug that wiring. `examples/tanstack-worker-smoke` in this repo
15
+ is a complete app; its files are the shapes shown here. The package README
16
+ (`packages/tanstack/README.md`) is the full contract of the worker.
17
+
18
+ ## When to load what
19
+
20
+ | Reference | Load it when |
21
+ |---|---|
22
+ | [`references/setup.md`](./references/setup.md) | Starting a site, or checking its files: packages, `vite.config.ts`, `wrangler.jsonc`, `.deco/index.ts`, `src/cms.ts`, scripts |
23
+ | [`references/routes-and-pages.md`](./references/routes-and-pages.md) | The catch-all route, `openPage`, redirects and 404s, rendering blocks, the head, search params and filters that don't reach the loader |
24
+ | [`references/worker-entry.md`](./references/worker-entry.md) | `src/worker-entry.ts`: what `createDecoWorker` always does, its options, the `routes` escape hatch, drafts and the headers it hands the app |
25
+ | [`references/server-functions.md`](./references/server-functions.md) | Replacing `/deco/invoke`, a server function whose code ships to the browser, cookies lost on the way to the browser, per-visitor responses |
26
+ | [`references/router-and-navigation.md`](./references/router-and-navigation.md) | `createDecoRouter` options, `Link` and preload, a navigation that fetches twice or not at all, variant switching on a product page |
27
+ | [`references/document-and-security.md`](./references/document-and-security.md) | `<html lang>`, the head, `DecoDocument` vs your own document, Studio framing, CSP and security headers |
28
+
29
+ ## The files of a site
30
+
31
+ | File | What it holds | Import from |
32
+ |---|---|---|
33
+ | `.deco/index.ts` | The block map: one function per block type | `@decocms/blocks` (`Blocks`) |
34
+ | `src/cms.ts` | `createCMS(...)` and the per-request client | `@decocms/blocks`, `@decocms/tanstack/server` |
35
+ | `src/open-page.server.ts` | `openPage(href, request)`: route, redirect, resolve | `@decocms/blocks` (`matchRoute`) |
36
+ | `src/page.functions.ts` | `loadPage`, the page's server function | `@tanstack/react-start` |
37
+ | `src/routes/$.tsx` | The catch-all route that calls `loadPage` | `@tanstack/react-router` |
38
+ | `src/routes/__root.tsx` | `DecoDocument` as the root component | `@decocms/tanstack/react` |
39
+ | `src/router.tsx` | `getRouter()` with `createDecoRouter` | `@decocms/tanstack/router` |
40
+ | `src/start.ts` | `createStart` with `decoServerFnFetch` | `@decocms/tanstack/start` |
41
+ | `src/worker-entry.ts` | `createDecoWorker(...)`, `wrangler.jsonc` `main` | `@decocms/tanstack/worker` |
42
+
43
+ ## Rules that hold everywhere
44
+
45
+ - **Never import `@decocms/tanstack/server` or `/worker` from a component.** They are server-only.
46
+ `/react`, `/router`, `/start` and the root export are safe in the browser.
47
+ - **The worker decides the draft, the visitor and the tests once per request.** Read them with
48
+ `contentClient(cms, request)`. Don't add a second draft check.
49
+ - **The page server function reads the page's URL, never the request's.** On a client-side
50
+ navigation the request is the `/_serverFn/…` call.
51
+ - **Each `createServerFn(...).handler(...)` is a top-level `const`.** Inside a function, TanStack's
52
+ compiler skips it and the handler ships to the browser.
53
+ - **Build query strings with `decoStringifySearch`**, not `new URLSearchParams(search)`, which turns
54
+ a repeated key (`filter.size=M&filter.size=L`) into one value (`M,L`).
55
+ - **Responsive layout is CSS** (`md:hidden`, `<picture>` with `<source media>`), not a JS device
56
+ branch: a branch must render the same on server and client, and the example page cache keys on
57
+ device, so a branch splits the cache.
58
+
59
+ ## Other skills
60
+
61
+ - `deco-site-workflow`: the `deco` CLI (`schema`, `check`, `pull`, `push --draft`, `publish`) and
62
+ where content lives.
63
+ - `deco-site-authoring`: writing sections, pages and loaders.
64
+ - `deco-storefront-caching`: the site's `pageCache` and the CDN.
65
+ - `deco-storefront-performance`: slow loaders, payload size, hydration.
66
+ - `deco-images-media`: `Image`, `Picture` and `ImageUrlProvider`.
67
+ - `deco-apps`: the `@decocms/apps-*` clients (VTEX cart cookies included).
68
+ - `deco-v7-to-v8-migration`: moving a v7 site here; its script writes the files above.
@@ -0,0 +1,155 @@
1
+ # The document, Studio and security headers
2
+
3
+ ## `src/routes/__root.tsx`
4
+
5
+ ```tsx
6
+ import { DecoDocument } from "@decocms/tanstack/react";
7
+ import { createRootRoute } from "@tanstack/react-router";
8
+
9
+ export const Route = createRootRoute({
10
+ head: () => ({
11
+ meta: [
12
+ { charSet: "utf-8" },
13
+ { name: "viewport", content: "width=device-width, initial-scale=1" },
14
+ { title: "My Store" },
15
+ ],
16
+ }),
17
+ component: () => <DecoDocument site="my-store" lang="pt-BR" />,
18
+ });
19
+ ```
20
+
21
+ `DecoDocument` is the whole `<html>`: `<HeadContent />` in the head, the page in `<main>`,
22
+ TanStack's `<Scripts />` at the end of the body, and the Deco pieces below. Mount it as the root
23
+ route's `component`.
24
+
25
+ | Prop | Default | What it sets |
26
+ |---|---|---|
27
+ | `site` | (required) | The site's name in Deco; the "." shortcut opens the page under it in Studio. |
28
+ | `lang` | `"en"` | `<html lang>`. |
29
+ | `bodyClassName` | `"bg-base-200 text-base-content"` | `<body class>`. |
30
+ | `account` | `""` | The commerce account in `window.__RUNTIME__`, which analytics scripts read. |
31
+ | `readyDelay` | `500` | ms after hydration before `deco:ready` fires. |
32
+ | `outlet` | `"main"` | The element around the page. `"div"` when the page renders its own `<main>`. |
33
+ | `editShortcut` | on | The "." shortcut that opens the page in Studio. `false` turns it off. |
34
+ | `nonce` | none | The CSP nonce for its inline scripts. |
35
+ | `studioOrigins` | see below | The Studio origins the page trusts. |
36
+ | `children` | none | Rendered after the page (toasts, drawers, analytics). |
37
+
38
+ **Set `lang`.** It defaults to `"en"`, so a Portuguese or Spanish store renders
39
+ `<html lang="en">` until you pass the right BCP 47 tag (`pt-BR`, `es-AR`). Accessibility checkers
40
+ and SEO audits flag the mismatch. Check it in the page source. (On Fresh this was `ctx.lang` in
41
+ `fresh.config.ts`; that file doesn't exist on v8.)
42
+
43
+ `<html>` always carries `data-theme="light"` (DaisyUI reads its colors from it).
44
+
45
+ What else it mounts:
46
+
47
+ - The `DECO.events` bus and a `data-event` observer that dispatches the events elements declare,
48
+ on view or click. Analytics go through it.
49
+ - `deco:ready`: `window.__deco_ready = true` and a `deco:ready` event on `document`, `readyDelay` ms
50
+ after hydration. Work that must follow hydration waits for it.
51
+ - `NavigationProgress` and `StableOutlet` ([`router-and-navigation.md`](./router-and-navigation.md)).
52
+ - An inline script that publishes the request's draft and CDN segment token to `window`.
53
+ - `StudioBridge`, `StudioChannel` and `DraftBadge` from `@decocms/blocks/preview` (below).
54
+
55
+ ## The head
56
+
57
+ The root route's `head()` holds what every page shares; each page route's `head()` adds its own
58
+ title and meta from its loader data ([`routes-and-pages.md`](./routes-and-pages.md)). Both end up in
59
+ `<HeadContent />`. Don't write `<title>` or `<meta>` tags into the document by hand.
60
+
61
+ ## Your own document
62
+
63
+ A layout `DecoDocument` can't express (a skip link before `<main>`, a different body structure)
64
+ keeps its own document, like any TanStack Start app, and renders `DecoPreview` once in its
65
+ `<body>`:
66
+
67
+ ```tsx
68
+ import { DecoPreview } from "@decocms/tanstack/react";
69
+
70
+ <body>
71
+ <a href="#content" className="sr-only focus:not-sr-only">Skip to content</a>
72
+ <main id="content">{children}</main>
73
+ <DecoPreview site="my-store" />
74
+ <Scripts />
75
+ </body>
76
+ ```
77
+
78
+ `DecoPreview` takes `site`, `editShortcut`, `nonce` and `studioOrigins`. It renders the draft
79
+ script, `StudioBridge`, `StudioChannel` and `DraftBadge`. `StudioBridge` alone leaves draft pages
80
+ without the badge. You then own `<HeadContent />`, `<Scripts />`, `lang`, the events bus and the
81
+ progress bar.
82
+
83
+ ## Studio inside the page
84
+
85
+ - **`StudioBridge`**: in Studio's frame it talks to Studio. Outside it, "." opens the current page
86
+ in Studio's editor: the page whose route returns `pathTemplate` (and optionally `pageId`) in its
87
+ loader data, else Studio picks it from the URL.
88
+ - **`StudioChannel`**: on every page, production included, about 0.7 kB gzipped. When a trusted
89
+ Studio origin frames the page, it loads Studio's editor modules from that origin. Otherwise it
90
+ does nothing. The bridge runs no script Studio sends.
91
+ - **`DraftBadge`**: shown on a draft page outside Studio's frame. A draft link that can't be read
92
+ anymore shows a notice and the release.
93
+
94
+ **Studio's origins** are, in order: the `studioOrigins` prop, else the `DECO_STUDIO_ORIGIN`
95
+ environment variable (comma-separated, read on the server; a local Studio such as
96
+ `http://localhost:3000`), else Studio's production and staging origins (`DEFAULT_STUDIO_ORIGINS`
97
+ from `@decocms/tanstack`). Each entry must be an exact `http(s)` origin; anything else is dropped.
98
+ The worker puts the same list into the CSP. If you set `studioOrigins` on `DecoDocument`, set the
99
+ same list on `createDecoWorker`; `DECO_STUDIO_ORIGIN` sets both.
100
+
101
+ When Studio asks the page to scroll to a section, `StudioBridge` looks for the element whose
102
+ `data-manifest-key` equals the id Studio sends, else the element with that `id`. How to render
103
+ sections: `deco-site-authoring`.
104
+
105
+ ## Security headers
106
+
107
+ The worker adds these to every HTML response that doesn't set them already:
108
+
109
+ | Header | Value |
110
+ |---|---|
111
+ | `X-Content-Type-Options` | `nosniff` |
112
+ | `Referrer-Policy` | `strict-origin-when-cross-origin` |
113
+ | `Permissions-Policy` | `camera=(), microphone=(), geolocation=()` |
114
+ | `X-XSS-Protection` | `1; mode=block` |
115
+ | `Strict-Transport-Security` | `max-age=63072000; includeSubDomains; preload` |
116
+ | `Cross-Origin-Opener-Policy` | `same-origin-allow-popups` |
117
+ | `Content-Security-Policy` | The site's `csp.enforce`, with Studio's additions |
118
+
119
+ There is no `X-Frame-Options`: `frame-ancestors` replaces it and, unlike `SAMEORIGIN`, can allow
120
+ Studio. A response that sets one of these headers keeps its own value.
121
+
122
+ ## CSP
123
+
124
+ ```ts
125
+ createDecoWorker({
126
+ serverEntry, cms,
127
+ csp: {
128
+ enforce: ["default-src 'self'", "img-src 'self' https: data:"],
129
+ reportOnly: "script-src 'self' https://analytics.example",
130
+ frameAncestors: ["https://editor.example.com"],
131
+ },
132
+ });
133
+ ```
134
+
135
+ `enforce` and `reportOnly` take a string (`"a; b"`) or a list of directives. What the worker adds:
136
+
137
+ - **`frame-ancestors`**, when the enforced policy has none: `STUDIO_FRAME_ANCESTORS` (`'self'`
138
+ and Studio's hosts), Studio's origins, `frameAncestors`, and loopback (`http://localhost:*`,
139
+ `http://127.0.0.1:*`) in `dev`. A `frame-ancestors` the site writes is kept as is: then Studio
140
+ frames the site only if that list names it.
141
+ - **Studio's origins in `script-src`** (and `script-src-elem`), so the Studio channel can import
142
+ Studio's modules. A policy that restricts scripts only through `default-src` gets a `script-src`
143
+ with `default-src`'s sources plus Studio's. A directive that is `'none'` stays as is.
144
+ - `reportOnly` goes out as `Content-Security-Policy-Report-Only`, with Studio's origins in its
145
+ `script-src` and no added `frame-ancestors`.
146
+
147
+ With no `csp` at all, the policy is just the `frame-ancestors` directive.
148
+
149
+ A policy the site sends some other way (a `routes` response, another proxy) goes through
150
+ `withStudioCsp(directives, options?)` from `@decocms/tanstack`, which makes the same additions and
151
+ returns the directive list.
152
+
153
+ **A nonce.** If the policy requires a nonce for scripts, pass the same nonce to
154
+ `DecoDocument` (`nonce`) and to `createDecoRouter` (`nonce`), so Deco's inline scripts and
155
+ TanStack's scripts carry it.