@decocms/blocks 8.1.0-next.0 → 8.1.0-next.2

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 (490) hide show
  1. package/bin/deco.js +5 -12
  2. package/dist/index.d.ts +2 -0
  3. package/dist/index.d.ts.map +1 -0
  4. package/dist/index.js +4 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/protocol/assets.d.ts +46 -0
  7. package/dist/protocol/assets.d.ts.map +1 -0
  8. package/dist/protocol/assets.js +105 -0
  9. package/dist/protocol/assets.js.map +1 -0
  10. package/dist/protocol/canonical.d.ts +8 -0
  11. package/dist/protocol/canonical.d.ts.map +1 -0
  12. package/dist/protocol/canonical.js +8 -0
  13. package/dist/protocol/canonical.js.map +1 -0
  14. package/dist/protocol/ciphertext.d.ts +7 -0
  15. package/dist/protocol/ciphertext.d.ts.map +1 -0
  16. package/dist/protocol/ciphertext.js +7 -0
  17. package/dist/protocol/ciphertext.js.map +1 -0
  18. package/dist/protocol/client.d.ts +54 -0
  19. package/dist/protocol/client.d.ts.map +1 -0
  20. package/dist/protocol/client.js +104 -0
  21. package/dist/protocol/client.js.map +1 -0
  22. package/dist/protocol/conformance/cases/assets.d.ts +3 -0
  23. package/dist/protocol/conformance/cases/assets.d.ts.map +1 -0
  24. package/dist/protocol/conformance/cases/assets.js +71 -0
  25. package/dist/protocol/conformance/cases/assets.js.map +1 -0
  26. package/dist/protocol/conformance/cases/guards.d.ts +3 -0
  27. package/dist/protocol/conformance/cases/guards.d.ts.map +1 -0
  28. package/dist/protocol/conformance/cases/guards.js +265 -0
  29. package/dist/protocol/conformance/cases/guards.js.map +1 -0
  30. package/dist/protocol/conformance/cases/reads.d.ts +3 -0
  31. package/dist/protocol/conformance/cases/reads.d.ts.map +1 -0
  32. package/dist/protocol/conformance/cases/reads.js +140 -0
  33. package/dist/protocol/conformance/cases/reads.js.map +1 -0
  34. package/dist/protocol/conformance/cases/types.d.ts +9 -0
  35. package/dist/protocol/conformance/cases/types.d.ts.map +1 -0
  36. package/dist/protocol/conformance/cases/types.js +2 -0
  37. package/dist/protocol/conformance/cases/types.js.map +1 -0
  38. package/dist/protocol/conformance/cases/wire.d.ts +3 -0
  39. package/dist/protocol/conformance/cases/wire.d.ts.map +1 -0
  40. package/dist/protocol/conformance/cases/wire.js +130 -0
  41. package/dist/protocol/conformance/cases/wire.js.map +1 -0
  42. package/dist/protocol/conformance/cases/writes.d.ts +3 -0
  43. package/dist/protocol/conformance/cases/writes.d.ts.map +1 -0
  44. package/dist/protocol/conformance/cases/writes.js +278 -0
  45. package/dist/protocol/conformance/cases/writes.js.map +1 -0
  46. package/dist/protocol/conformance/contentHashFixtures.d.ts +22 -0
  47. package/dist/protocol/conformance/contentHashFixtures.d.ts.map +1 -0
  48. package/dist/protocol/conformance/contentHashFixtures.js +64 -0
  49. package/dist/protocol/conformance/contentHashFixtures.js.map +1 -0
  50. package/dist/protocol/conformance/context.d.ts +100 -0
  51. package/dist/protocol/conformance/context.d.ts.map +1 -0
  52. package/dist/protocol/conformance/context.js +155 -0
  53. package/dist/protocol/conformance/context.js.map +1 -0
  54. package/dist/protocol/conformance/index.d.ts +32 -0
  55. package/dist/protocol/conformance/index.d.ts.map +1 -0
  56. package/dist/protocol/conformance/index.js +90 -0
  57. package/dist/protocol/conformance/index.js.map +1 -0
  58. package/dist/protocol/errors.d.ts +85 -0
  59. package/dist/protocol/errors.d.ts.map +1 -0
  60. package/dist/protocol/errors.js +62 -0
  61. package/dist/protocol/errors.js.map +1 -0
  62. package/dist/protocol/index.d.ts +25 -0
  63. package/dist/protocol/index.d.ts.map +1 -0
  64. package/dist/protocol/index.js +25 -0
  65. package/dist/protocol/index.js.map +1 -0
  66. package/dist/protocol/keys.d.ts +101 -0
  67. package/dist/protocol/keys.d.ts.map +1 -0
  68. package/dist/protocol/keys.js +223 -0
  69. package/dist/protocol/keys.js.map +1 -0
  70. package/dist/protocol/params.d.ts +10 -0
  71. package/dist/protocol/params.d.ts.map +1 -0
  72. package/dist/protocol/params.js +54 -0
  73. package/dist/protocol/params.js.map +1 -0
  74. package/dist/protocol/secrets.d.ts +22 -0
  75. package/dist/protocol/secrets.d.ts.map +1 -0
  76. package/dist/protocol/secrets.js +200 -0
  77. package/dist/protocol/secrets.js.map +1 -0
  78. package/dist/protocol/server/assets.d.ts +20 -0
  79. package/dist/protocol/server/assets.d.ts.map +1 -0
  80. package/dist/protocol/server/assets.js +77 -0
  81. package/dist/protocol/server/assets.js.map +1 -0
  82. package/dist/protocol/server/auth.d.ts +31 -0
  83. package/dist/protocol/server/auth.d.ts.map +1 -0
  84. package/dist/protocol/server/auth.js +32 -0
  85. package/dist/protocol/server/auth.js.map +1 -0
  86. package/dist/protocol/server/bodyCache.d.ts +28 -0
  87. package/dist/protocol/server/bodyCache.d.ts.map +1 -0
  88. package/dist/protocol/server/bodyCache.js +75 -0
  89. package/dist/protocol/server/bodyCache.js.map +1 -0
  90. package/dist/protocol/server/content.d.ts +44 -0
  91. package/dist/protocol/server/content.d.ts.map +1 -0
  92. package/dist/protocol/server/content.js +132 -0
  93. package/dist/protocol/server/content.js.map +1 -0
  94. package/dist/protocol/server/core.d.ts +63 -0
  95. package/dist/protocol/server/core.d.ts.map +1 -0
  96. package/dist/protocol/server/core.js +77 -0
  97. package/dist/protocol/server/core.js.map +1 -0
  98. package/dist/protocol/server/handler.d.ts +5 -0
  99. package/dist/protocol/server/handler.d.ts.map +1 -0
  100. package/dist/protocol/server/handler.js +70 -0
  101. package/dist/protocol/server/handler.js.map +1 -0
  102. package/dist/protocol/server/http.d.ts +24 -0
  103. package/dist/protocol/server/http.d.ts.map +1 -0
  104. package/dist/protocol/server/http.js +133 -0
  105. package/dist/protocol/server/http.js.map +1 -0
  106. package/dist/protocol/server/index.d.ts +11 -0
  107. package/dist/protocol/server/index.d.ts.map +1 -0
  108. package/dist/protocol/server/index.js +9 -0
  109. package/dist/protocol/server/index.js.map +1 -0
  110. package/dist/protocol/server/methods/apply.d.ts +4 -0
  111. package/dist/protocol/server/methods/apply.d.ts.map +1 -0
  112. package/dist/protocol/server/methods/apply.js +275 -0
  113. package/dist/protocol/server/methods/apply.js.map +1 -0
  114. package/dist/protocol/server/methods/read.d.ts +14 -0
  115. package/dist/protocol/server/methods/read.d.ts.map +1 -0
  116. package/dist/protocol/server/methods/read.js +132 -0
  117. package/dist/protocol/server/methods/read.js.map +1 -0
  118. package/dist/protocol/server/rpc.d.ts +7 -0
  119. package/dist/protocol/server/rpc.d.ts.map +1 -0
  120. package/dist/protocol/server/rpc.js +115 -0
  121. package/dist/protocol/server/rpc.js.map +1 -0
  122. package/dist/protocol/storage/fs/hash.d.ts +8 -0
  123. package/dist/protocol/storage/fs/hash.d.ts.map +1 -0
  124. package/dist/protocol/storage/fs/hash.js +20 -0
  125. package/dist/protocol/storage/fs/hash.js.map +1 -0
  126. package/dist/protocol/storage/fs/index.d.ts +30 -0
  127. package/dist/protocol/storage/fs/index.d.ts.map +1 -0
  128. package/dist/protocol/storage/fs/index.js +301 -0
  129. package/dist/protocol/storage/fs/index.js.map +1 -0
  130. package/dist/protocol/storage/fs/lock.d.ts +8 -0
  131. package/dist/protocol/storage/fs/lock.d.ts.map +1 -0
  132. package/dist/protocol/storage/fs/lock.js +61 -0
  133. package/dist/protocol/storage/fs/lock.js.map +1 -0
  134. package/dist/protocol/storage/fs/transaction.d.ts +19 -0
  135. package/dist/protocol/storage/fs/transaction.d.ts.map +1 -0
  136. package/dist/protocol/storage/fs/transaction.js +174 -0
  137. package/dist/protocol/storage/fs/transaction.js.map +1 -0
  138. package/dist/protocol/storage/fs/unsupported.d.ts +10 -0
  139. package/dist/protocol/storage/fs/unsupported.d.ts.map +1 -0
  140. package/dist/protocol/storage/fs/unsupported.js +4 -0
  141. package/dist/protocol/storage/fs/unsupported.js.map +1 -0
  142. package/dist/protocol/storage/memory.d.ts +40 -0
  143. package/dist/protocol/storage/memory.d.ts.map +1 -0
  144. package/dist/protocol/storage/memory.js +179 -0
  145. package/dist/protocol/storage/memory.js.map +1 -0
  146. package/dist/protocol/storage.d.ts +178 -0
  147. package/dist/protocol/storage.d.ts.map +1 -0
  148. package/dist/protocol/storage.js +29 -0
  149. package/dist/protocol/storage.js.map +1 -0
  150. package/dist/protocol/types.d.ts +194 -0
  151. package/dist/protocol/types.d.ts.map +1 -0
  152. package/dist/protocol/types.js +31 -0
  153. package/dist/protocol/types.js.map +1 -0
  154. package/dist/v8/analytics.d.ts +31 -0
  155. package/dist/v8/analytics.d.ts.map +1 -0
  156. package/dist/v8/analytics.js +46 -0
  157. package/dist/v8/analytics.js.map +1 -0
  158. package/dist/v8/background.d.ts +26 -0
  159. package/dist/v8/background.d.ts.map +1 -0
  160. package/dist/v8/background.js +95 -0
  161. package/dist/v8/background.js.map +1 -0
  162. package/dist/v8/builtins/data.d.ts +15 -0
  163. package/dist/v8/builtins/data.d.ts.map +1 -0
  164. package/dist/v8/builtins/data.js +18 -0
  165. package/dist/v8/builtins/data.js.map +1 -0
  166. package/dist/v8/builtins/index.d.ts +9 -0
  167. package/dist/v8/builtins/index.d.ts.map +1 -0
  168. package/dist/v8/builtins/index.js +24 -0
  169. package/dist/v8/builtins/index.js.map +1 -0
  170. package/dist/v8/builtins/lazy.d.ts +17 -0
  171. package/dist/v8/builtins/lazy.d.ts.map +1 -0
  172. package/dist/v8/builtins/lazy.js +13 -0
  173. package/dist/v8/builtins/lazy.js.map +1 -0
  174. package/dist/v8/builtins/legacy.d.ts +41 -0
  175. package/dist/v8/builtins/legacy.d.ts.map +1 -0
  176. package/dist/v8/builtins/legacy.js +62 -0
  177. package/dist/v8/builtins/legacy.js.map +1 -0
  178. package/dist/v8/builtins/matchers.d.ts +19 -0
  179. package/dist/v8/builtins/matchers.d.ts.map +1 -0
  180. package/dist/v8/builtins/matchers.js +24 -0
  181. package/dist/v8/builtins/matchers.js.map +1 -0
  182. package/dist/v8/builtins/multivariate.d.ts +15 -0
  183. package/dist/v8/builtins/multivariate.d.ts.map +1 -0
  184. package/dist/v8/builtins/multivariate.js +18 -0
  185. package/dist/v8/builtins/multivariate.js.map +1 -0
  186. package/dist/v8/builtins/secret.d.ts +7 -0
  187. package/dist/v8/builtins/secret.d.ts.map +1 -0
  188. package/dist/v8/builtins/secret.js +68 -0
  189. package/dist/v8/builtins/secret.js.map +1 -0
  190. package/dist/v8/canonical.d.ts +42 -0
  191. package/dist/v8/canonical.d.ts.map +1 -0
  192. package/dist/v8/canonical.js +111 -0
  193. package/dist/v8/canonical.js.map +1 -0
  194. package/dist/v8/ciphertext.d.ts +58 -0
  195. package/dist/v8/ciphertext.d.ts.map +1 -0
  196. package/dist/v8/ciphertext.js +134 -0
  197. package/dist/v8/ciphertext.js.map +1 -0
  198. package/dist/v8/cli/builtins.d.ts +11 -0
  199. package/dist/v8/cli/builtins.d.ts.map +1 -0
  200. package/dist/v8/cli/builtins.js +18 -0
  201. package/dist/v8/cli/builtins.js.map +1 -0
  202. package/dist/v8/cli/check/index.d.ts +41 -0
  203. package/dist/v8/cli/check/index.d.ts.map +1 -0
  204. package/dist/v8/cli/check/index.js +713 -0
  205. package/dist/v8/cli/check/index.js.map +1 -0
  206. package/dist/v8/cli/check/messages.d.ts +24 -0
  207. package/dist/v8/cli/check/messages.d.ts.map +1 -0
  208. package/dist/v8/cli/check/messages.js +150 -0
  209. package/dist/v8/cli/check/messages.js.map +1 -0
  210. package/dist/v8/cli/content.d.ts +60 -0
  211. package/dist/v8/cli/content.d.ts.map +1 -0
  212. package/dist/v8/cli/content.js +231 -0
  213. package/dist/v8/cli/content.js.map +1 -0
  214. package/dist/v8/cli/index.d.ts +18 -0
  215. package/dist/v8/cli/index.d.ts.map +1 -0
  216. package/dist/v8/cli/index.js +18 -0
  217. package/dist/v8/cli/index.js.map +1 -0
  218. package/dist/v8/cli/log.d.ts +9 -0
  219. package/dist/v8/cli/log.d.ts.map +1 -0
  220. package/dist/v8/cli/log.js +11 -0
  221. package/dist/v8/cli/log.js.map +1 -0
  222. package/dist/v8/cli/main.d.ts +2 -0
  223. package/dist/v8/cli/main.d.ts.map +1 -0
  224. package/dist/v8/cli/main.js +9 -0
  225. package/dist/v8/cli/main.js.map +1 -0
  226. package/dist/v8/cli/root.d.ts +28 -0
  227. package/dist/v8/cli/root.d.ts.map +1 -0
  228. package/dist/v8/cli/root.js +64 -0
  229. package/dist/v8/cli/root.js.map +1 -0
  230. package/dist/v8/cli/run.d.ts +13 -0
  231. package/dist/v8/cli/run.d.ts.map +1 -0
  232. package/dist/v8/cli/run.js +210 -0
  233. package/dist/v8/cli/run.js.map +1 -0
  234. package/dist/v8/cli/schema/builtinSchemas.d.ts +22 -0
  235. package/dist/v8/cli/schema/builtinSchemas.d.ts.map +1 -0
  236. package/dist/v8/cli/schema/builtinSchemas.js +213 -0
  237. package/dist/v8/cli/schema/builtinSchemas.js.map +1 -0
  238. package/dist/v8/cli/schema/generate.d.ts +50 -0
  239. package/dist/v8/cli/schema/generate.d.ts.map +1 -0
  240. package/dist/v8/cli/schema/generate.js +415 -0
  241. package/dist/v8/cli/schema/generate.js.map +1 -0
  242. package/dist/v8/cli/schema/index.d.ts +21 -0
  243. package/dist/v8/cli/schema/index.d.ts.map +1 -0
  244. package/dist/v8/cli/schema/index.js +51 -0
  245. package/dist/v8/cli/schema/index.js.map +1 -0
  246. package/dist/v8/cli/schema/tsProgram.d.ts +120 -0
  247. package/dist/v8/cli/schema/tsProgram.d.ts.map +1 -0
  248. package/dist/v8/cli/schema/tsProgram.js +418 -0
  249. package/dist/v8/cli/schema/tsProgram.js.map +1 -0
  250. package/dist/v8/cli/schema/typeToSchema.d.ts +81 -0
  251. package/dist/v8/cli/schema/typeToSchema.d.ts.map +1 -0
  252. package/dist/v8/cli/schema/typeToSchema.js +683 -0
  253. package/dist/v8/cli/schema/typeToSchema.js.map +1 -0
  254. package/dist/v8/cli/serve/server.d.ts +31 -0
  255. package/dist/v8/cli/serve/server.d.ts.map +1 -0
  256. package/dist/v8/cli/serve/server.js +247 -0
  257. package/dist/v8/cli/serve/server.js.map +1 -0
  258. package/dist/v8/cli/watch.d.ts +20 -0
  259. package/dist/v8/cli/watch.d.ts.map +1 -0
  260. package/dist/v8/cli/watch.js +79 -0
  261. package/dist/v8/cli/watch.js.map +1 -0
  262. package/dist/v8/client.d.ts +20 -0
  263. package/dist/v8/client.d.ts.map +1 -0
  264. package/dist/v8/client.js +115 -0
  265. package/dist/v8/client.js.map +1 -0
  266. package/dist/v8/cms.d.ts +9 -0
  267. package/dist/v8/cms.d.ts.map +1 -0
  268. package/dist/v8/cms.js +206 -0
  269. package/dist/v8/cms.js.map +1 -0
  270. package/dist/v8/content.d.ts +35 -0
  271. package/dist/v8/content.d.ts.map +1 -0
  272. package/dist/v8/content.js +183 -0
  273. package/dist/v8/content.js.map +1 -0
  274. package/dist/v8/draft.d.ts +44 -0
  275. package/dist/v8/draft.d.ts.map +1 -0
  276. package/dist/v8/draft.js +133 -0
  277. package/dist/v8/draft.js.map +1 -0
  278. package/dist/v8/errors.d.ts +21 -0
  279. package/dist/v8/errors.d.ts.map +1 -0
  280. package/dist/v8/errors.js +39 -0
  281. package/dist/v8/errors.js.map +1 -0
  282. package/dist/v8/fetch.d.ts +26 -0
  283. package/dist/v8/fetch.d.ts.map +1 -0
  284. package/dist/v8/fetch.js +98 -0
  285. package/dist/v8/fetch.js.map +1 -0
  286. package/dist/v8/identity.d.ts +19 -0
  287. package/dist/v8/identity.d.ts.map +1 -0
  288. package/dist/v8/identity.js +54 -0
  289. package/dist/v8/identity.js.map +1 -0
  290. package/dist/v8/index.d.ts +11 -0
  291. package/dist/v8/index.d.ts.map +1 -0
  292. package/dist/v8/index.js +10 -0
  293. package/dist/v8/index.js.map +1 -0
  294. package/dist/v8/json.d.ts +19 -0
  295. package/dist/v8/json.d.ts.map +1 -0
  296. package/dist/v8/json.js +65 -0
  297. package/dist/v8/json.js.map +1 -0
  298. package/dist/v8/matchRoute.d.ts +30 -0
  299. package/dist/v8/matchRoute.d.ts.map +1 -0
  300. package/dist/v8/matchRoute.js +175 -0
  301. package/dist/v8/matchRoute.js.map +1 -0
  302. package/dist/v8/remoteLoader.d.ts +16 -0
  303. package/dist/v8/remoteLoader.d.ts.map +1 -0
  304. package/dist/v8/remoteLoader.js +243 -0
  305. package/dist/v8/remoteLoader.js.map +1 -0
  306. package/dist/v8/resolver.d.ts +34 -0
  307. package/dist/v8/resolver.d.ts.map +1 -0
  308. package/dist/v8/resolver.js +219 -0
  309. package/dist/v8/resolver.js.map +1 -0
  310. package/dist/v8/secrets.d.ts +9 -0
  311. package/dist/v8/secrets.d.ts.map +1 -0
  312. package/dist/v8/secrets.js +14 -0
  313. package/dist/v8/secrets.js.map +1 -0
  314. package/dist/v8/telemetry.d.ts +61 -0
  315. package/dist/v8/telemetry.d.ts.map +1 -0
  316. package/dist/v8/telemetry.js +460 -0
  317. package/dist/v8/telemetry.js.map +1 -0
  318. package/dist/v8/types.d.ts +214 -0
  319. package/dist/v8/types.d.ts.map +1 -0
  320. package/dist/v8/types.js +2 -0
  321. package/dist/v8/types.js.map +1 -0
  322. package/package.json +65 -105
  323. package/src/index.ts +3 -13
  324. package/src/protocol/canonical.ts +1 -1
  325. package/src/protocol/ciphertext.ts +1 -1
  326. package/src/protocol/client.ts +2 -2
  327. package/src/protocol/conformance/cases/assets.ts +3 -3
  328. package/src/protocol/conformance/cases/guards.ts +4 -4
  329. package/src/protocol/conformance/cases/reads.ts +4 -4
  330. package/src/protocol/conformance/cases/types.ts +1 -1
  331. package/src/protocol/conformance/cases/wire.ts +4 -4
  332. package/src/protocol/conformance/cases/writes.ts +4 -4
  333. package/src/protocol/conformance/context.ts +4 -4
  334. package/src/protocol/conformance/index.ts +10 -10
  335. package/src/protocol/index.ts +6 -6
  336. package/src/protocol/params.ts +2 -2
  337. package/src/protocol/secrets.ts +3 -3
  338. package/src/protocol/server/assets.ts +6 -6
  339. package/src/protocol/server/auth.ts +1 -1
  340. package/src/protocol/server/content.ts +5 -5
  341. package/src/protocol/server/core.ts +12 -6
  342. package/src/protocol/server/handler.ts +6 -6
  343. package/src/protocol/server/http.ts +1 -1
  344. package/src/protocol/server/index.ts +3 -3
  345. package/src/protocol/server/methods/apply.ts +9 -9
  346. package/src/protocol/server/methods/read.ts +5 -5
  347. package/src/protocol/server/rpc.ts +6 -6
  348. package/src/protocol/storage/fs/index.ts +7 -7
  349. package/src/protocol/storage/fs/lock.ts +1 -1
  350. package/src/protocol/storage/fs/unsupported.ts +2 -2
  351. package/src/protocol/storage/memory.ts +5 -5
  352. package/src/protocol/storage.ts +1 -1
  353. package/src/v8/analytics.ts +2 -2
  354. package/src/v8/background.ts +3 -3
  355. package/src/v8/builtins/data.ts +1 -1
  356. package/src/v8/builtins/index.ts +6 -6
  357. package/src/v8/builtins/lazy.ts +1 -1
  358. package/src/v8/builtins/legacy.ts +2 -2
  359. package/src/v8/builtins/multivariate.ts +1 -1
  360. package/src/v8/builtins/secret.ts +2 -2
  361. package/src/v8/cli/builtins.ts +2 -2
  362. package/src/v8/cli/check/index.ts +11 -11
  363. package/src/v8/cli/content.ts +6 -6
  364. package/src/v8/cli/index.ts +8 -8
  365. package/src/v8/cli/main.ts +1 -1
  366. package/src/v8/cli/run.ts +7 -7
  367. package/src/v8/cli/schema/builtinSchemas.ts +1 -1
  368. package/src/v8/cli/schema/generate.ts +6 -6
  369. package/src/v8/cli/schema/index.ts +4 -4
  370. package/src/v8/cli/schema/tsProgram.ts +1 -1
  371. package/src/v8/cli/schema/typeToSchema.ts +24 -2
  372. package/src/v8/cli/serve/server.ts +9 -9
  373. package/src/v8/client.ts +5 -5
  374. package/src/v8/cms.ts +9 -9
  375. package/src/v8/content.ts +4 -4
  376. package/src/v8/draft.ts +1 -1
  377. package/src/v8/errors.ts +1 -1
  378. package/src/v8/fetch.ts +9 -28
  379. package/src/v8/identity.ts +1 -1
  380. package/src/v8/index.ts +5 -5
  381. package/src/v8/matchRoute.ts +1 -1
  382. package/src/v8/remoteLoader.ts +7 -7
  383. package/src/v8/resolver.ts +6 -6
  384. package/src/v8/secrets.ts +1 -1
  385. package/src/v8/telemetry.ts +6 -6
  386. package/src/cms/applySectionConventions.ts +0 -148
  387. package/src/cms/blockSource.ts +0 -228
  388. package/src/cms/client.ts +0 -85
  389. package/src/cms/deferredTrigger.ts +0 -58
  390. package/src/cms/draftSource.ts +0 -476
  391. package/src/cms/index.ts +0 -180
  392. package/src/cms/loadDecofileDirectory.ts +0 -89
  393. package/src/cms/loader.ts +0 -563
  394. package/src/cms/registry.ts +0 -264
  395. package/src/cms/renderJson.ts +0 -179
  396. package/src/cms/resolve.ts +0 -2583
  397. package/src/cms/schema.ts +0 -1219
  398. package/src/cms/sectionLoaderContext.ts +0 -113
  399. package/src/cms/sectionLoaders.ts +0 -686
  400. package/src/cms/sectionMixins.ts +0 -153
  401. package/src/flags/audience.ts +0 -56
  402. package/src/flags/everyone.ts +0 -29
  403. package/src/flags/flag.ts +0 -15
  404. package/src/flags/multivariate/image.ts +0 -11
  405. package/src/flags/multivariate/message.ts +0 -11
  406. package/src/flags/multivariate/page.ts +0 -16
  407. package/src/flags/multivariate/section.ts +0 -16
  408. package/src/flags/multivariate.ts +0 -1
  409. package/src/flags/types.ts +0 -59
  410. package/src/flags/utils/multivariate.ts +0 -20
  411. package/src/hooks/Image.tsx +0 -314
  412. package/src/hooks/JsonLd.tsx +0 -353
  413. package/src/hooks/LazySection.tsx +0 -121
  414. package/src/hooks/LiveControls.tsx +0 -144
  415. package/src/hooks/Picture.tsx +0 -127
  416. package/src/hooks/RenderSection.tsx +0 -91
  417. package/src/hooks/SectionErrorFallback.tsx +0 -97
  418. package/src/hooks/Stats.tsx +0 -134
  419. package/src/hooks/index.ts +0 -35
  420. package/src/hooks/useLoadMore.ts +0 -100
  421. package/src/matchers/builtins.ts +0 -459
  422. package/src/matchers/countryNames.ts +0 -104
  423. package/src/matchers/override.ts +0 -136
  424. package/src/matchers/posthog.ts +0 -154
  425. package/src/middleware/decoState.ts +0 -55
  426. package/src/middleware/healthMetrics.ts +0 -133
  427. package/src/middleware/hydrationContext.ts +0 -79
  428. package/src/middleware/index.ts +0 -88
  429. package/src/middleware/liveness.ts +0 -21
  430. package/src/middleware/observability.ts +0 -800
  431. package/src/middleware/validateSection.ts +0 -100
  432. package/src/preview/DraftPreviewBadge.tsx +0 -306
  433. package/src/preview/decoMark.ts +0 -11
  434. package/src/preview/index.ts +0 -8
  435. package/src/sdk/abTesting.ts +0 -556
  436. package/src/sdk/analytics.ts +0 -147
  437. package/src/sdk/cacheHeaders.ts +0 -633
  438. package/src/sdk/cacheStorage.ts +0 -287
  439. package/src/sdk/cachedLoader.ts +0 -556
  440. package/src/sdk/clx.ts +0 -5
  441. package/src/sdk/cn.ts +0 -28
  442. package/src/sdk/composite.ts +0 -114
  443. package/src/sdk/cookie.ts +0 -129
  444. package/src/sdk/crypto.ts +0 -199
  445. package/src/sdk/csp.ts +0 -59
  446. package/src/sdk/deepOmit.ts +0 -52
  447. package/src/sdk/detectDevice.ts +0 -45
  448. package/src/sdk/djb2.ts +0 -20
  449. package/src/sdk/encoding.ts +0 -44
  450. package/src/sdk/env.ts +0 -54
  451. package/src/sdk/experiments.ts +0 -314
  452. package/src/sdk/fetchCache.ts +0 -269
  453. package/src/sdk/fetchTimeout.ts +0 -58
  454. package/src/sdk/flags.ts +0 -138
  455. package/src/sdk/http.ts +0 -124
  456. package/src/sdk/index.ts +0 -97
  457. package/src/sdk/inflightTimeout.ts +0 -53
  458. package/src/sdk/instrumentedFetch.ts +0 -362
  459. package/src/sdk/invoke.ts +0 -298
  460. package/src/sdk/logger.ts +0 -304
  461. package/src/sdk/mergeCacheControl.ts +0 -150
  462. package/src/sdk/nonce.ts +0 -46
  463. package/src/sdk/normalizeUrls.ts +0 -91
  464. package/src/sdk/observability.ts +0 -116
  465. package/src/sdk/otel.ts +0 -1118
  466. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  467. package/src/sdk/otelAdapters.ts +0 -144
  468. package/src/sdk/otelHttpLog.ts +0 -419
  469. package/src/sdk/otelHttpMeter.ts +0 -532
  470. package/src/sdk/otelHttpTracer.ts +0 -543
  471. package/src/sdk/redirects.ts +0 -336
  472. package/src/sdk/requestContext.ts +0 -281
  473. package/src/sdk/requestContextStorage.browser.ts +0 -43
  474. package/src/sdk/requestContextStorage.ts +0 -35
  475. package/src/sdk/responseCache.ts +0 -82
  476. package/src/sdk/retry.ts +0 -45
  477. package/src/sdk/serverTimings.ts +0 -68
  478. package/src/sdk/signal.ts +0 -42
  479. package/src/sdk/sitemap.ts +0 -160
  480. package/src/sdk/urlRedaction.ts +0 -82
  481. package/src/sdk/urlUtils.ts +0 -183
  482. package/src/sdk/useDevice.ts +0 -89
  483. package/src/sdk/useDeviceContext.tsx +0 -108
  484. package/src/sdk/useId.ts +0 -7
  485. package/src/sdk/useScript.ts +0 -210
  486. package/src/sdk/useSuggestions.ts +0 -188
  487. package/src/sdk/wrapCaughtErrors.ts +0 -107
  488. package/src/setup.ts +0 -120
  489. package/src/types/index.ts +0 -53
  490. package/src/types/widgets.ts +0 -14
@@ -1,2583 +0,0 @@
1
- import { getMatchersOverride, getRuleOverrideId, hasMatchersOverride } from "../matchers/override";
2
- import { getMeter, MetricNames, withTracing } from "../middleware/observability";
3
- import { createCacheStore } from "../sdk/cacheStorage";
4
- import { detectDevice } from "../sdk/detectDevice";
5
- import { djb2Hex } from "../sdk/djb2";
6
- import { stickyDecide } from "../sdk/experiments";
7
- import { parseSegmentCookie, SEGMENT_COOKIE, type StoredFlag, trafficToPct } from "../sdk/flags";
8
- import { withInflightTimeout } from "../sdk/inflightTimeout";
9
- import { normalizeUrlsInObject } from "../sdk/normalizeUrls";
10
- import { stripTrackingParams } from "../sdk/urlUtils";
11
- import { DEFAULT_DEFERRED_TRIGGER, type DeferredTrigger } from "./deferredTrigger";
12
- import { findPageByPath, loadBlocks } from "./loader";
13
- import { getOnBeforeResolveProps, getSection, registerOnBeforeResolveProps } from "./registry";
14
- import {
15
- type ActionConfig,
16
- inferLoaderTags,
17
- type LoaderConfig,
18
- registerActionSchemas,
19
- registerLoaderSchemas,
20
- } from "./schema";
21
- import { isLayoutSection, markSectionDegraded, runSingleSectionLoader } from "./sectionLoaders";
22
-
23
- // globalThis-backed: share state across Vite server function split modules
24
- const G = globalThis as any;
25
- if (!G.__deco) G.__deco = {};
26
- if (!G.__deco.commerceLoaders) G.__deco.commerceLoaders = {};
27
- if (!G.__deco.customMatchers) G.__deco.customMatchers = {};
28
- if (!G.__deco.eagerSectionKeys) G.__deco.eagerSectionKeys = new Set<string>();
29
-
30
- // ---------------------------------------------------------------------------
31
- // onBeforeResolveProps helper — eagerly loads the section module if needed
32
- // ---------------------------------------------------------------------------
33
-
34
- async function applyOnBeforeResolveProps(
35
- sectionType: string,
36
- props: Record<string, unknown>,
37
- ): Promise<Record<string, unknown>> {
38
- let fn = getOnBeforeResolveProps(sectionType);
39
- if (!fn) {
40
- const loader = getSection(sectionType);
41
- if (loader) {
42
- try {
43
- const mod = await loader();
44
- if (mod?.onBeforeResolveProps) {
45
- registerOnBeforeResolveProps(sectionType, mod.onBeforeResolveProps);
46
- fn = mod.onBeforeResolveProps;
47
- }
48
- } catch {}
49
- }
50
- }
51
- return fn ? fn(props) : props;
52
- }
53
-
54
- // ---------------------------------------------------------------------------
55
- // Well-known resolve types — extracted as constants so they're searchable
56
- // and overridable. Consumers migrating from deco-cx/deco may have blocks
57
- // with these __resolveType strings in their CMS JSON.
58
- // ---------------------------------------------------------------------------
59
-
60
- /** @internal */
61
- export const WELL_KNOWN_TYPES = {
62
- LAZY: "website/sections/Rendering/Lazy.tsx",
63
- DEFERRED: "website/sections/Rendering/Deferred.tsx",
64
- REQUEST_TO_PARAM: "website/functions/requestToParam.ts",
65
- COMMERCE_EXT_DETAILS: "commerce/loaders/product/extensions/detailsPage.ts",
66
- COMMERCE_EXT_LISTING: "commerce/loaders/product/extensions/listingPage.ts",
67
- MULTIVARIATE: "website/flags/multivariate.ts",
68
- MULTIVARIATE_SECTION: "website/flags/multivariate/section.ts",
69
- PAGE: "website/pages/Page.tsx",
70
- } as const;
71
-
72
- export type ResolvedSection = {
73
- component: string;
74
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
75
- props: Record<string, any>;
76
- key: string;
77
- /** Original position in the raw section list (used by mergeSections). */
78
- index?: number;
79
- };
80
-
81
- // ---------------------------------------------------------------------------
82
- // Deferred section — a placeholder for sections loaded on scroll
83
- // ---------------------------------------------------------------------------
84
-
85
- export interface DeferredSection {
86
- component: string;
87
- key: string;
88
- /** Position in the original page section list. */
89
- index: number;
90
- /**
91
- * Short hash of rawProps for client-side cache busting.
92
- * Keeps the serialized payload small — full rawProps are resolved
93
- * server-side from the deferred props cache or page re-resolution.
94
- */
95
- propsHash: string;
96
- /**
97
- * CMS-resolved props without section-loader enrichment.
98
- * @deprecated Stripped before serialization to reduce HTML payload.
99
- * Only present server-side in the rawProps cache.
100
- */
101
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
102
- rawProps?: Record<string, any>;
103
- }
104
-
105
- // ---------------------------------------------------------------------------
106
- // Async rendering configuration
107
- // ---------------------------------------------------------------------------
108
-
109
- export interface AsyncRenderingConfig {
110
- /**
111
- * When true, sections wrapped in `website/sections/Rendering/Lazy.tsx`
112
- * in the CMS are deferred and loaded on scroll. This respects the
113
- * editor's per-section choices made in the admin.
114
- * @default true
115
- */
116
- respectCmsLazy: boolean;
117
- /**
118
- * When a deferred (⚡) section fetches its real markup on the client.
119
- *
120
- * `"intersection"` (default) waits for the skeleton to come within 300px of
121
- * the viewport. `"load"` fetches as soon as the wrapper mounts — the
122
- * behaviour Deco on Fresh gets from `DispatchAsyncRender`'s
123
- * `partialTriggerMode: "load"`, where the page ships a light skeleton and
124
- * then materializes every deferred section right after hydration.
125
- *
126
- * Sites migrating from Fresh generally want `"load"`: under `"intersection"`
127
- * alone, everything below the fold does not exist until the user scrolls, so
128
- * the document stays short and below-the-fold analytics impressions are lost.
129
- * The cost is a request burst — every deferred section POSTs in the same
130
- * commit, on load and on each SPA navigation.
131
- *
132
- * Read on the CLIENT, so it must be set from a module the browser bundle also
133
- * loads (normally `setup.ts`, imported from `router.tsx`). Setting it from
134
- * server-only code leaves the client on `"intersection"` with no warning.
135
- * Only `@decocms/tanstack` reads it; a no-op in `@decocms/nextjs`.
136
- *
137
- * Optional on purpose. `setAsyncRenderingConfig()` always fills it, so the
138
- * stored config never actually lacks it — but this interface is exported from
139
- * `@decocms/blocks/cms`, and a required field would break the typecheck of
140
- * anyone outside the package who builds an `AsyncRenderingConfig` literal.
141
- * The only sanctioned reader, `getDeferredTrigger()`, already defaults.
142
- * @default "intersection"
143
- */
144
- deferredTrigger?: DeferredTrigger;
145
- /**
146
- * Fold threshold: sections at or above this flat index are DEFERRED
147
- * (rendered as a skeleton and loaded on scroll), so their resolved props are
148
- * not serialized into the SSR hydration payload. Sections below it stay
149
- * eager. This is an explicit, position-based opt-in that applies ONLY to
150
- * sections the editor did NOT mark async (⚡) in the admin — it never
151
- * overrides a CMS Lazy/Deferred wrapper.
152
- *
153
- * Defaults to {@link DEFAULT_FOLD_THRESHOLD} (`Infinity`), which disables
154
- * position-based deferral entirely so the admin ⚡ toggle is the sole source
155
- * of truth. Set a finite value per-site to also defer unmarked sections by
156
- * position.
157
- * @default {@link DEFAULT_FOLD_THRESHOLD}
158
- */
159
- foldThreshold: number;
160
- /** Section component keys that must always be rendered eagerly. */
161
- alwaysEager: Set<string>;
162
- /**
163
- * Site-wide bot-aware page SEO shortcut. When true, the page-level `seo`
164
- * block's commerce-loader-backed props (e.g. `jsonLD: { __resolveType: "PLP
165
- * Loader" }`) are SKIPPED for human (non-bot) requests — so SSR doesn't run
166
- * the heavy upstream fetch and the product payload never reaches the human
167
- * HTML. Bots still get the full SEO (JSON-LD) for indexing.
168
- *
169
- * This is a blanket, developer-set shortcut. The PRIMARY, client-facing lever
170
- * is the per-section `ignoreStructuredData` toggle in the admin (on the PLP/PDP
171
- * SEO section): it drives the exact same fetch-skip + bot-aware JSON-LD, but
172
- * per section and without a code change. This flag simply turns the behavior
173
- * on for every commerce-backed SEO block at once.
174
- *
175
- * OFF by default: the optimization removes the commerce data a human `<title>`
176
- * may derive from, so a blanket opt-in is only safe once the site provides a
177
- * lightweight title fallback (e.g. a cheap category-metadata loader). Sites
178
- * that just bump the framework keep the previous behavior (full SEO for
179
- * everyone) and are not regressed. Opt in with
180
- * `setAsyncRenderingConfig({ botAwareSeo: true })`, or leave it off and let
181
- * editors flip `ignoreStructuredData` per section.
182
- * @default false
183
- */
184
- botAwareSeo: boolean;
185
- }
186
-
187
- /**
188
- * Default fold threshold. `Infinity` disables position-based deferral entirely:
189
- * sections are deferred if and only if the editor marked them async (⚡) in the
190
- * admin (wrapped in CMS `Lazy.tsx`/`Deferred.tsx`). The admin is the source of
191
- * truth; a section's position on the page never drives the SSR-vs-deferred
192
- * decision by default.
193
- *
194
- * Sites that want to additionally defer unmarked sections by position can opt
195
- * in explicitly via `setAsyncRenderingConfig({ foldThreshold: N })` — keeping
196
- * the first N sections eager (above-the-fold LCP/SEO) and deferring the rest to
197
- * trim the SSR hydration payload. Even then, the threshold only affects
198
- * sections NOT marked ⚡; it never overrides the editor's choice.
199
- */
200
- export const DEFAULT_FOLD_THRESHOLD = Infinity;
201
-
202
- // Always read from globalThis so split-module copies see updates
203
- function getAsyncConfig(): AsyncRenderingConfig | null {
204
- return G.__deco.asyncConfig ?? null;
205
- }
206
-
207
- /**
208
- * Enable async section rendering.
209
- *
210
- * The admin is the source of truth: any section the editor marked async ⚡
211
- * (wrapped in `website/sections/Rendering/Lazy.tsx` or `Deferred.tsx`) is
212
- * deferred and loaded on scroll; every other section is rendered eagerly (SSR),
213
- * regardless of its position. `foldThreshold` defaults to
214
- * {@link DEFAULT_FOLD_THRESHOLD} (`Infinity`), so position-based deferral is
215
- * OFF by default. Pass a finite `foldThreshold: N` to additionally defer
216
- * UNMARKED sections from index N onward (an opt-in optimization that never
217
- * overrides the editor's ⚡ choice).
218
- *
219
- * When not called, all sections are resolved eagerly (backward compatible).
220
- */
221
- export function setAsyncRenderingConfig(config?: {
222
- foldThreshold?: number;
223
- alwaysEager?: string[];
224
- respectCmsLazy?: boolean;
225
- deferredTrigger?: DeferredTrigger;
226
- botAwareSeo?: boolean;
227
- }): void {
228
- const existing = getAsyncConfig();
229
- const merged = new Set([...(existing?.alwaysEager ?? []), ...(config?.alwaysEager ?? [])]);
230
- G.__deco.asyncConfig = {
231
- respectCmsLazy: config?.respectCmsLazy ?? existing?.respectCmsLazy ?? true,
232
- deferredTrigger:
233
- config?.deferredTrigger ?? existing?.deferredTrigger ?? DEFAULT_DEFERRED_TRIGGER,
234
- foldThreshold: config?.foldThreshold ?? existing?.foldThreshold ?? DEFAULT_FOLD_THRESHOLD,
235
- alwaysEager: merged,
236
- botAwareSeo: config?.botAwareSeo ?? existing?.botAwareSeo ?? false,
237
- };
238
- }
239
-
240
- /** Read-only access to the current config (null when disabled). */
241
- export function getAsyncRenderingConfig(): AsyncRenderingConfig | null {
242
- return getAsyncConfig();
243
- }
244
-
245
- // ---------------------------------------------------------------------------
246
- // Permanent eager section registry — survives setAsyncRenderingConfig() calls
247
- // ---------------------------------------------------------------------------
248
-
249
- /**
250
- * Register sections that declared `export const eager = true`.
251
- * This is a permanent registry that cannot be overwritten by
252
- * subsequent calls to `setAsyncRenderingConfig()`.
253
- */
254
- export function registerEagerSections(keys: string[]): void {
255
- const set: Set<string> = G.__deco.eagerSectionKeys;
256
- for (const k of keys) set.add(k);
257
- }
258
-
259
- function isEagerSection(key: string): boolean {
260
- return (G.__deco.eagerSectionKeys as Set<string>).has(key);
261
- }
262
-
263
- // ---------------------------------------------------------------------------
264
- // Permanent neverDefer section registry
265
- // ---------------------------------------------------------------------------
266
-
267
- /**
268
- * Register sections that declared `export const neverDefer = true`.
269
- * These sections are NEVER deferred regardless of fold threshold —
270
- * use for interactive components that need their props on the client
271
- * during hydration (search filters, configurators, etc.).
272
- */
273
- export function registerNeverDeferSections(keys: string[]): void {
274
- const set: Set<string> = (G.__deco.neverDeferSectionKeys ??= new Set());
275
- for (const k of keys) set.add(k);
276
- }
277
-
278
- function isNeverDeferSection(key: string): boolean {
279
- return (G.__deco.neverDeferSectionKeys as Set<string> | undefined)?.has(key) ?? false;
280
- }
281
-
282
- // ---------------------------------------------------------------------------
283
- // Permanent alwaysDefer section registry
284
- // ---------------------------------------------------------------------------
285
-
286
- /**
287
- * Register sections that declared `export const deferred = true`.
288
- * These sections are ALWAYS deferred (rendered client-side on scroll),
289
- * independent of the global `respectCmsLazy` config — the per-section opt-in
290
- * for async-rendering a single heavy section (e.g. a PLP grid) without
291
- * turning on deferral site-wide. Bots stay eager via the `isBotReq`
292
- * short-circuit in {@link shouldDeferSection}.
293
- */
294
- export function registerAlwaysDeferSections(keys: string[]): void {
295
- G.__deco.alwaysDeferSectionKeys ??= new Set();
296
- const set: Set<string> = G.__deco.alwaysDeferSectionKeys;
297
- for (const k of keys) set.add(k);
298
- }
299
-
300
- function isAlwaysDeferSection(key: string): boolean {
301
- return (G.__deco.alwaysDeferSectionKeys as Set<string> | undefined)?.has(key) ?? false;
302
- }
303
-
304
- // ---------------------------------------------------------------------------
305
- // Deferred rawProps cache — keeps rawProps server-side to trim HTML payload
306
- // ---------------------------------------------------------------------------
307
-
308
- const DEFERRED_PROPS_TTL = 120_000; // 2 minutes
309
- const deferredRawPropsCache = createCacheStore<{ rawProps: Record<string, unknown>; ts: number }>(
310
- "deferred-props",
311
- 500,
312
- );
313
-
314
- function deferredPropsCacheKey(pagePath: string, component: string, index: number): string {
315
- return deferredRawPropsCache.key(`${pagePath}::${component}::${index}`);
316
- }
317
-
318
- export function cacheDeferredRawProps(
319
- pagePath: string,
320
- component: string,
321
- index: number,
322
- rawProps: Record<string, unknown>,
323
- ): void {
324
- const key = deferredPropsCacheKey(pagePath, component, index);
325
- deferredRawPropsCache.set(key, { rawProps, ts: Date.now() }, Date.now() + DEFERRED_PROPS_TTL);
326
- }
327
-
328
- /** Async form used when a deferred request may run in a different isolate. */
329
- export async function readDeferredRawProps(
330
- pagePath: string,
331
- component: string,
332
- index: number,
333
- ): Promise<Record<string, unknown> | null> {
334
- const entry = await deferredRawPropsCache.read(deferredPropsCacheKey(pagePath, component, index));
335
- return entry?.rawProps ?? null;
336
- }
337
-
338
- export function getDeferredRawProps(
339
- pagePath: string,
340
- component: string,
341
- index: number,
342
- ): Record<string, unknown> | null {
343
- const key = deferredPropsCacheKey(pagePath, component, index);
344
- const entry = deferredRawPropsCache.get(key);
345
- if (!entry || Date.now() - entry.ts > DEFERRED_PROPS_TTL) return null;
346
- return entry.rawProps;
347
- }
348
-
349
- // ---------------------------------------------------------------------------
350
- // Bot detection — bots always receive fully eager pages for SEO
351
- // ---------------------------------------------------------------------------
352
-
353
- /**
354
- * User-Agent substrings that classify a request as a bot.
355
- *
356
- * Exported as data, not just baked into the regex, because the CDN cache rules
357
- * have to bypass exactly the same requests this list makes eager — see
358
- * `@decocms/blocks-cli/scripts/cdn-rules.ts`. Two hand-maintained copies would
359
- * drift, and the failure mode is a crawler's eager HTML (~10x larger) being
360
- * served to humans from the CDN, or the deferred one being served to Google.
361
- */
362
- export const BOT_UA_SUBSTRINGS = [
363
- "bot",
364
- "crawl",
365
- "spider",
366
- "slurp",
367
- "facebookexternalhit",
368
- "mediapartners",
369
- "google",
370
- "bing",
371
- "yandex",
372
- "baidu",
373
- "duckduck",
374
- "teoma",
375
- "ia_archiver",
376
- "semrush",
377
- "ahrefs",
378
- "lighthouse",
379
- ] as const;
380
-
381
- const botPatterns: RegExp[] = [new RegExp(BOT_UA_SUBSTRINGS.join("|"), "i")];
382
-
383
- /**
384
- * Add a custom bot detection regex.
385
- * Requests matching any bot pattern receive fully eager pages for SEO.
386
- */
387
- export function registerBotPattern(pattern: RegExp): void {
388
- botPatterns.push(pattern);
389
- }
390
-
391
- export function isBot(userAgent?: string): boolean {
392
- if (!userAgent) return false;
393
- return botPatterns.some((re) => re.test(userAgent));
394
- }
395
-
396
- /**
397
- * Explicit override to force the eager (full SSR / crawler) render from a normal
398
- * browser — for QA and SEO auditing without spoofing the User-Agent. Triggered
399
- * by `?__deco_ssr=1` (alias `?__bot=1`) on the request URL.
400
- *
401
- * The flag lives in the query string, so it is part of the edge cache key: the
402
- * forced-eager response gets its own cache bucket and never contaminates the
403
- * human page. Cookies are intentionally NOT honored here — they are not in the
404
- * cache key and would risk serving a stale human entry.
405
- */
406
- function hasForceEagerParam(ctx?: MatcherContext): boolean {
407
- const url = ctx?.url;
408
- if (!url) return false;
409
- try {
410
- const sp = new URL(url, "https://localhost").searchParams;
411
- return sp.get("__deco_ssr") === "1" || sp.get("__bot") === "1";
412
- } catch {
413
- return false;
414
- }
415
- }
416
-
417
- /**
418
- * True for a programmatic, non-navigation request to a page URL — an AJAX
419
- * `fetch()`/XHR (e.g. the PLP "Ver mais"/load-more pagination), an embed, or a
420
- * server-to-server fetch. These consumers read the static SSR HTML and never
421
- * run the client-side deferred-section resolution (IntersectionObserver +
422
- * `loadDeferredSection` serverFn), so any `⚡` deferred section is invisible to
423
- * them — they only ever see its skeleton. Rendering eagerly puts the real
424
- * content in the HTML they actually parse.
425
- *
426
- * Detected via `Sec-Fetch-Dest: empty`, which a `fetch()`/XHR sends and which a
427
- * top-level browser navigation (`document`) and subresource loads
428
- * (`image`/`script`/`style`/`font`) do not — navigations stay deferred because
429
- * they CAN hydrate and resolve deferred sections. SPA navigations (TanStack
430
- * `<Link>` → `/_serverFn`) also send `empty` but set `isClientNavigation`, and
431
- * are excluded here on both counts: page-SEO commerce loaders stay off for
432
- * humans (decocms/blocks#286), and their sections stay deferred, because a
433
- * client nav renders through `DecoPageRenderer` and therefore CAN resolve a
434
- * deferred section on scroll — unlike a real AJAX consumer.
435
- *
436
- * Like {@link hasForceEagerParam}, this must stay in lock-step with the edge
437
- * cache key: `workerEntry` keys `Sec-Fetch-Dest: empty` page requests into a
438
- * separate `__fetch=1` bucket, so the eager response never poisons the
439
- * navigation (deferred) entry, and vice-versa.
440
- */
441
- function isProgrammaticFetch(ctx?: MatcherContext): boolean {
442
- if (ctx?.isClientNavigation) return false;
443
- const dest = ctx?.request?.headers.get("sec-fetch-dest") ?? ctx?.headers?.["sec-fetch-dest"];
444
- return dest === "empty";
445
- }
446
-
447
- /**
448
- * True when the request should receive the full eager (crawler) render: real
449
- * search-engine bots (by User-Agent), an explicit `?__deco_ssr=1` override, or
450
- * a programmatic non-navigation fetch (see {@link isProgrammaticFetch}). Used
451
- * to gate both section deferral and page-SEO commerce resolution.
452
- */
453
- export function isEagerRequest(ctx?: MatcherContext): boolean {
454
- return isBot(ctx?.userAgent) || hasForceEagerParam(ctx) || isProgrammaticFetch(ctx);
455
- }
456
-
457
- /**
458
- * A loader registered against a `__resolveType` key. The runtime invokes it
459
- * through two paths:
460
- *
461
- * 1. CMS resolution (`commerceLoader(resolvedProps)`) — 1-arg call.
462
- * 2. `/deco/invoke/...` endpoint — `(props, request)` 2-arg call.
463
- *
464
- * Loaders that need the `Request` (cookies, geo, headers) declare the second
465
- * parameter; pure loaders ignore it. This shape lets a single registry serve
466
- * both invocation paths without `as any` casts at every wrapper.
467
- */
468
- export type CommerceLoader = (props: any, request?: Request) => Promise<any>;
469
-
470
- /**
471
- * Context passed through the resolution pipeline.
472
- * Includes HTTP request info for matcher evaluation and per-request memoization.
473
- */
474
- export interface MatcherContext {
475
- userAgent?: string;
476
- url?: string;
477
- path?: string;
478
- cookies?: Record<string, string>;
479
- headers?: Record<string, string>;
480
- request?: Request;
481
- /**
482
- * Sticky A/B flags recorded during resolution. The resolver appends a
483
- * {@link StoredFlag} the first time it evaluates each sticky matcher (see
484
- * `evaluateVariantRule`), reusing the decision for the rest of the request
485
- * so every resolve pass picks the same variant. Read it after resolution to
486
- * persist the `deco_flags` cookie and split the edge cache per cohort.
487
- * Pass an array in to opt into recording; leave undefined to disable.
488
- */
489
- flags?: StoredFlag[];
490
- /**
491
- * Client-side (SPA) navigation via TanStack `<Link>`. Set by the route
492
- * loaders, where the incoming request URL is the `/_serverFn/...` endpoint
493
- * rather than the page being navigated to.
494
- *
495
- * Consumed by `derivePageUrl` (rebuilding the real page URL, #280) and by
496
- * {@link isProgrammaticFetch} (a SPA nav sends `Sec-Fetch-Dest: empty` but is
497
- * NOT an AJAX consumer). It deliberately does NOT affect section deferral —
498
- * a TanStack route loader is blocking, so eager-resolving below-fold sections
499
- * on client nav stalls the whole transition. See `resolveDecoPageImpl`.
500
- */
501
- isClientNavigation?: boolean;
502
- }
503
-
504
- /**
505
- * Internal resolution context with memoization and error tracking.
506
- * Created once per resolveDecoPage / resolveValue call tree.
507
- */
508
- interface ResolveContext {
509
- routeParams?: Record<string, string>;
510
- matcherCtx: MatcherContext;
511
- memo: Map<string, unknown>;
512
- depth: number;
513
- }
514
-
515
- // ---------------------------------------------------------------------------
516
- // Configuration
517
- // ---------------------------------------------------------------------------
518
-
519
- const SKIP_RESOLVE_TYPES = new Set([
520
- "Deco",
521
- "htmx/sections/htmx.tsx",
522
- "website/sections/Analytics/Analytics.tsx",
523
- "algolia/sections/Analytics/Algolia.tsx",
524
- "shopify/loaders/proxy.ts",
525
- "vtex/loaders/proxy.ts",
526
- "website/loaders/pages.ts",
527
- "website/loaders/redirects.ts",
528
- "website/loaders/fonts/googleFonts.ts",
529
- "commerce/sections/Seo/SeoPDP.tsx",
530
- "commerce/sections/Seo/SeoPDPV2.tsx",
531
- "commerce/sections/Seo/SeoPLP.tsx",
532
- "commerce/sections/Seo/SeoPLPV2.tsx",
533
- "website/sections/Seo/Seo.tsx",
534
- "website/sections/Seo/SeoV2.tsx",
535
- "deco-sites/std/sections/SEO.tsx",
536
- ]);
537
-
538
- /** Add a __resolveType that should be skipped during resolution. */
539
- export function addSkipResolveType(resolveType: string) {
540
- SKIP_RESOLVE_TYPES.add(resolveType);
541
- }
542
-
543
- const MAX_RESOLVE_DEPTH = 20;
544
-
545
- // ---------------------------------------------------------------------------
546
- // Commerce loaders
547
- // ---------------------------------------------------------------------------
548
-
549
- const commerceLoaders: Record<string, CommerceLoader> = G.__deco.commerceLoaders;
550
-
551
- export function registerCommerceLoader(key: string, loader: CommerceLoader) {
552
- commerceLoaders[key] = loader;
553
- }
554
-
555
- export function registerCommerceLoaders(loaders: Record<string, CommerceLoader>) {
556
- Object.assign(commerceLoaders, loaders);
557
-
558
- // Auto-register loader + action schemas for the admin manifest.
559
- // Separate actions (keys containing "/actions/") from loaders.
560
- // These are stub registrations (isStub) — a real schema for the same key
561
- // (registered via registerAppSchemas from an app's schemas.gen.ts) always
562
- // wins, no matter which side registers first.
563
- const loaderConfigs: LoaderConfig[] = [];
564
- const actionConfigs: ActionConfig[] = [];
565
-
566
- for (const key of Object.keys(loaders)) {
567
- const namespace = key.startsWith("vtex/") ? "vtex" : "site";
568
- const schema = { type: "object" as const, additionalProperties: true };
569
-
570
- if (key.includes("/actions/")) {
571
- actionConfigs.push({ key, title: key, namespace, propsSchema: schema, isStub: true });
572
- } else {
573
- loaderConfigs.push({
574
- key,
575
- title: key,
576
- namespace,
577
- propsSchema: schema,
578
- tags: inferLoaderTags(key),
579
- isStub: true,
580
- });
581
- }
582
- }
583
-
584
- registerLoaderSchemas(loaderConfigs);
585
- registerActionSchemas(actionConfigs);
586
- }
587
-
588
- /** Delete a single commerce loader by key. No-op if key is absent. */
589
- export function unregisterCommerceLoader(key: string): void {
590
- delete commerceLoaders[key];
591
- }
592
-
593
- /** Clear all commerce loaders. Use with care — wipes site-registered entries too. */
594
- export function clearCommerceLoaders(): void {
595
- for (const key of Object.keys(commerceLoaders)) delete commerceLoaders[key];
596
- }
597
-
598
- /**
599
- * Look up a commerce loader tolerant of a legacy `.ts`/`.tsx` resolveType
600
- * suffix. Fresh/Deno decofiles reference app loaders with the file extension
601
- * (`shopify/loaders/ProductDetailsPage.ts`), but the split-package app
602
- * manifests register them WITHOUT it (`shopify/loaders/ProductDetailsPage`).
603
- * Exact key wins (so an explicitly-registered `.ts` alias — e.g. a site's
604
- * wrapped loader — still takes precedence); otherwise fall back to the
605
- * extension-stripped key so existing content keeps resolving after a migration.
606
- */
607
- export function getCommerceLoader(resolveType: string): CommerceLoader | undefined {
608
- return commerceLoaders[resolveType] ?? commerceLoaders[resolveType.replace(/\.tsx?$/, "")];
609
- }
610
-
611
- // ---------------------------------------------------------------------------
612
- // Custom matchers
613
- // ---------------------------------------------------------------------------
614
-
615
- const customMatchers: Record<
616
- string,
617
- (rule: Record<string, unknown>, ctx: MatcherContext) => boolean
618
- > = G.__deco.customMatchers;
619
-
620
- export function registerMatcher(
621
- key: string,
622
- fn: (rule: Record<string, unknown>, ctx: MatcherContext) => boolean,
623
- ) {
624
- customMatchers[key] = fn;
625
- }
626
-
627
- // ---------------------------------------------------------------------------
628
- // Built-in matchers — registered through the same API as custom matchers
629
- // ---------------------------------------------------------------------------
630
-
631
- if (!G.__deco._builtinMatchersRegistered) {
632
- G.__deco._builtinMatchersRegistered = true;
633
-
634
- const builtinMatchers: Record<
635
- string,
636
- (rule: Record<string, unknown>, ctx: MatcherContext) => boolean
637
- > = {
638
- "website/matchers/always.ts": () => true,
639
- "$live/matchers/MatchAlways.ts": () => true,
640
- "website/matchers/never.ts": () => false,
641
- "website/matchers/device.ts": (rule, ctx) => {
642
- const ua = (ctx.userAgent || "").toLowerCase();
643
- const isTablet = /ipad|android(?!.*mobile)|tablet/i.test(ua);
644
- const isMobile =
645
- !isTablet && /mobile|android|iphone|ipod|webos|blackberry|opera mini|iemobile/i.test(ua);
646
- const isDesktop = !isMobile && !isTablet;
647
- // If no flags are set, match everything (permissive default)
648
- if (!rule.mobile && !rule.tablet && !rule.desktop) return true;
649
- return (
650
- !!(rule.mobile && isMobile) || !!(rule.tablet && isTablet) || !!(rule.desktop && isDesktop)
651
- );
652
- },
653
- "website/matchers/random.ts": (rule) => {
654
- const traffic = typeof rule.traffic === "number" ? rule.traffic : 0.5;
655
- return Math.random() < traffic;
656
- },
657
- "website/matchers/date.ts": (rule) => {
658
- const now = Date.now();
659
- const start = typeof rule.start === "string" ? new Date(rule.start).getTime() : 0;
660
- const end = typeof rule.end === "string" ? new Date(rule.end).getTime() : Infinity;
661
- return now >= start && now <= end;
662
- },
663
- };
664
-
665
- for (const [key, fn] of Object.entries(builtinMatchers)) {
666
- // Only register if not already overridden by consumer
667
- if (!customMatchers[key]) {
668
- customMatchers[key] = fn;
669
- }
670
- }
671
- }
672
-
673
- // ---------------------------------------------------------------------------
674
- // Error handling
675
- // ---------------------------------------------------------------------------
676
-
677
- export type ResolveErrorHandler = (error: unknown, resolveType: string, context: string) => void;
678
-
679
- let onResolveError: ResolveErrorHandler = (error, resolveType, context) => {
680
- console.error(`[CMS] ${context} "${resolveType}" failed:`, error);
681
- };
682
-
683
- /** Configure a custom error handler for resolution failures. */
684
- export function setResolveErrorHandler(handler: ResolveErrorHandler) {
685
- onResolveError = handler;
686
- }
687
-
688
- // ---------------------------------------------------------------------------
689
- // Dangling reference handling
690
- // ---------------------------------------------------------------------------
691
-
692
- export type DanglingReferenceHandler = (resolveType: string) => unknown;
693
-
694
- let onDanglingReference: DanglingReferenceHandler = (resolveType) => {
695
- console.warn(`[CMS] Unhandled resolver: ${resolveType}`);
696
- return null;
697
- };
698
-
699
- /** Configure how unresolvable __resolveType references are handled. */
700
- export function setDanglingReferenceHandler(handler: DanglingReferenceHandler) {
701
- onDanglingReference = handler;
702
- }
703
-
704
- // ---------------------------------------------------------------------------
705
- // Init hook
706
- // ---------------------------------------------------------------------------
707
-
708
- export function onBeforeResolve(callback: () => void) {
709
- G.__deco.initCallback = callback;
710
- }
711
-
712
- function ensureInitialized() {
713
- if (!G.__deco.initialized && G.__deco.initCallback) {
714
- G.__deco.initCallback();
715
- G.__deco.initialized = true;
716
- }
717
- }
718
-
719
- // ---------------------------------------------------------------------------
720
- // Matcher evaluation
721
- // ---------------------------------------------------------------------------
722
-
723
- export function evaluateMatcher(
724
- rule: Record<string, unknown> | undefined,
725
- ctx: MatcherContext,
726
- ): boolean {
727
- if (!rule) return true;
728
-
729
- const resolveType = rule.__resolveType as string | undefined;
730
- if (!resolveType) return true;
731
-
732
- const blocks = loadBlocks();
733
-
734
- // x-deco-matchers-override — Deno resolveChain semantics: a saved matcher
735
- // block is keyed by its name; an inline rule by `<blockId>@<prop.path>`
736
- // (e.g. `pages-home-abc123@sections.2.variants.0.rule`). Checked before
737
- // the saved-block recursion below, which swaps __resolveType for the
738
- // underlying matcher type and merges into a fresh object, losing both the
739
- // block name and the rule's identity in the blocks map.
740
- if (hasMatchersOverride(ctx)) {
741
- const overrides = getMatchersOverride(ctx);
742
- const forced =
743
- (blocks[resolveType] ? overrides[resolveType] : undefined) ??
744
- overrides[getRuleOverrideId(blocks, rule) ?? ""];
745
- if (forced !== undefined) return forced;
746
- }
747
-
748
- if (blocks[resolveType]) {
749
- const resolvedRule = blocks[resolveType] as Record<string, unknown>;
750
- return evaluateMatcher(
751
- { ...resolvedRule, ...rule, __resolveType: resolvedRule.__resolveType as string },
752
- ctx,
753
- );
754
- }
755
-
756
- const matcher = customMatchers[resolveType];
757
- if (matcher) {
758
- try {
759
- return matcher(rule, ctx);
760
- } catch {
761
- return false;
762
- }
763
- }
764
-
765
- console.warn(`[CMS] Unknown matcher: ${resolveType}, defaulting to false`);
766
- return false;
767
- }
768
-
769
- // ---------------------------------------------------------------------------
770
- // Sticky matchers (A/B)
771
- // ---------------------------------------------------------------------------
772
-
773
- /**
774
- * Matcher types whose decision must stick per user instead of re-rolling every
775
- * request. Mirrors the `sticky = "session"` export on the corresponding
776
- * matchers in @decocms/apps (blocks re-implements matchers inline, so it
777
- * declares the set here rather than importing those exports).
778
- */
779
- const STICKY_MATCHER_TYPES = new Set(["website/matchers/random.ts"]);
780
-
781
- interface StickyMeta {
782
- /** Cohort identity — the named matcher block (e.g. "TestHero"). */
783
- name: string;
784
- /** Traffic share for the `true` branch. */
785
- traffic: number;
786
- /** `round(traffic * 100)` — the re-roll fingerprint. */
787
- pct: number;
788
- }
789
-
790
- /**
791
- * If `rule` points at a sticky matcher, return its cohort identity + traffic;
792
- * otherwise `null` (evaluate normally). A rule is either a named matcher block
793
- * (`{__resolveType: "TestHero"}`, dereferenced here to read its `traffic`) or
794
- * an inline matcher; the block name is the stable cohort key when present.
795
- */
796
- function stickyMatcherMeta(rule: Record<string, unknown> | undefined): StickyMeta | null {
797
- const rt = rule?.__resolveType as string | undefined;
798
- if (!rt) return null;
799
-
800
- const blocks = loadBlocks();
801
- const name = rt;
802
- let resolved = rule as Record<string, unknown>;
803
- if (blocks[rt]) {
804
- resolved = blocks[rt] as Record<string, unknown>;
805
- }
806
-
807
- const type = resolved.__resolveType as string | undefined;
808
- if (!type || !STICKY_MATCHER_TYPES.has(type)) return null;
809
-
810
- const traffic = typeof resolved.traffic === "number" ? resolved.traffic : 0.5;
811
- return { name, traffic, pct: trafficToPct(traffic) };
812
- }
813
-
814
- /**
815
- * Evaluate a variant's rule, applying sticky persistence for A/B matchers.
816
- *
817
- * For a sticky matcher: reuse the decision already recorded this request; else
818
- * honor the `deco_segment` cookie when its fingerprint still matches the current
819
- * `traffic`; else roll fresh. Every decision is recorded on `ctx.flags` (when
820
- * present) so the caller can persist the cookie and split the cache. Non-sticky
821
- * rules fall through to the plain matcher.
822
- */
823
- function evaluateVariantRule(
824
- rule: Record<string, unknown> | undefined,
825
- ctx: MatcherContext,
826
- ): boolean {
827
- const meta = stickyMatcherMeta(rule);
828
- // Admin preview forces variants via x-deco-matchers-override; defer to
829
- // evaluateMatcher so a forced decision wins. Sticky persistence is a
830
- // production concern (previews aren't cached), so skipping it here is fine.
831
- if (!meta || hasMatchersOverride(ctx)) return evaluateMatcher(rule, ctx);
832
-
833
- // Shared with sdk/experiments.ts' N-way resolution — same reuse / stay-sticky
834
- // / re-roll precedence, so the two assignment paths cannot drift. This path
835
- // keeps its own `trafficToPct` fingerprint: swapping it for the experiment
836
- // weight hash would re-roll every live visitor on the next deploy.
837
- return stickyDecide<boolean>({
838
- name: meta.name,
839
- fingerprint: meta.pct,
840
- recorded: ctx.flags,
841
- stored: parseSegmentCookie(ctx.cookies?.[SEGMENT_COOKIE]),
842
- roll: () => Math.random() < meta.traffic,
843
- // A matcher decision is always boolean; a string here means an experiment
844
- // took the same cookie slot. Re-roll rather than coerce a variant id.
845
- accepts: (v) => typeof v === "boolean",
846
- }).value;
847
- }
848
-
849
- // ---------------------------------------------------------------------------
850
- // Select (partial field picking)
851
- // ---------------------------------------------------------------------------
852
-
853
- function applySelect(value: unknown, select?: string[]): unknown {
854
- if (!select || !select.length || !value || typeof value !== "object") return value;
855
- if (Array.isArray(value)) return value.map((item) => applySelect(item, select));
856
-
857
- const result: Record<string, unknown> = {};
858
- for (const key of select) {
859
- if (key in (value as Record<string, unknown>)) {
860
- result[key] = (value as Record<string, unknown>)[key];
861
- }
862
- }
863
- return result;
864
- }
865
-
866
- // ---------------------------------------------------------------------------
867
- // Core resolution
868
- // ---------------------------------------------------------------------------
869
-
870
- async function resolveProps(
871
- obj: Record<string, unknown>,
872
- rctx: ResolveContext,
873
- ): Promise<Record<string, unknown>> {
874
- const entries = Object.entries(obj);
875
- const resolvedEntries = await Promise.all(
876
- entries.map(async ([k, v]) => [k, await internalResolve(v, rctx)] as const),
877
- );
878
- return Object.fromEntries(resolvedEntries);
879
- }
880
-
881
- async function internalResolve(value: unknown, rctx: ResolveContext): Promise<unknown> {
882
- if (!value || typeof value !== "object") return value;
883
- if (Array.isArray(value)) {
884
- const resolved = await Promise.all(value.map((item) => internalResolve(item, rctx)));
885
- // Drop items that resolved to "not present" (`undefined`) — e.g. a hidden
886
- // array item (a multivariate wrapped in a `never` matcher, see the admin's
887
- // hideArrayItem) where no variant matched. A `never`-gated item must vanish
888
- // from the array, NOT become a `null` hole the section then renders as an
889
- // empty card. Legitimate `null` values (a matched variant that resolved to
890
- // null, a failed loader) are kept — only the no-match sentinel is filtered.
891
- return resolved.filter((item) => item !== undefined);
892
- }
893
-
894
- const obj = value as Record<string, unknown>;
895
-
896
- if (!obj.__resolveType) {
897
- return resolveProps(obj, rctx);
898
- }
899
-
900
- const resolveType = obj.__resolveType as string;
901
-
902
- if (SKIP_RESOLVE_TYPES.has(resolveType)) return null;
903
-
904
- if (rctx.depth > MAX_RESOLVE_DEPTH) {
905
- console.error(`[CMS] Max resolution depth (${MAX_RESOLVE_DEPTH}) exceeded at: ${resolveType}`);
906
- return null;
907
- }
908
-
909
- const childCtx: ResolveContext = { ...rctx, depth: rctx.depth + 1 };
910
-
911
- // ── `asResolved` ─────────────────────────────────────────────────────────
912
- //
913
- // `{ __resolveType: "resolved", data }` hands `data` back untouched — the
914
- // caller is telling us it is already resolved.
915
- //
916
- // With `deferred: true` it instead becomes a THUNK, and `data` is not walked
917
- // at all during the page pass. That is the point: the CMS resolver is
918
- // recursive and resolves every `__resolveType` it finds in a section's props,
919
- // including branches the section will not render. Measured on a real store, a
920
- // PDP's `notFoundSections` — the 404 fallback — carried a shelf whose
921
- // `products` was a full-text search: 1703ms of the EAGER critical path of
922
- // EVERY product page, with the result thrown away. Same shape applies to tab
923
- // content, modal content and unmatched A/B branches.
924
- //
925
- // The thunk closes over `childCtx`, so resolving it later still sees THIS
926
- // request: cookies, UA and url reach the matchers, and `rctx.memo` dedupes
927
- // named-block references the page already resolved. It does NOT dedupe
928
- // commerce loaders — those are keyed by their own cache layer, not the memo
929
- // (see the "Named block reference (memoized)" branch), so a deferred prop
930
- // pointing at the same loader as a rendered one still calls it twice.
931
- //
932
- // HAZARD, and it is why this is opt-in per prop: a thunk cannot be
933
- // serialized. If a section defers a prop and never calls it, the prop reaches
934
- // the client as `undefined` (JSON.stringify drops functions). Defer only what
935
- // the section itself resolves, and only on the branch that needs it.
936
- if (resolveType === "resolved") {
937
- if (obj.deferred === true) {
938
- const raw = obj.data;
939
- return () => internalResolve(raw, childCtx);
940
- }
941
- return obj.data ?? null;
942
- }
943
-
944
- // Lazy section wrapper — unwrap single inner section
945
- if (resolveType === WELL_KNOWN_TYPES.LAZY) {
946
- return obj.section ? internalResolve(obj.section, childCtx) : null;
947
- }
948
-
949
- // Deferred section wrapper (legacy Fresh/HTMX) — unwrap inner sections array
950
- if (resolveType === WELL_KNOWN_TYPES.DEFERRED) {
951
- return obj.sections ? internalResolve(obj.sections, childCtx) : null;
952
- }
953
-
954
- // Request param extraction
955
- if (resolveType === WELL_KNOWN_TYPES.REQUEST_TO_PARAM) {
956
- const paramName = (obj as any).param as string;
957
- return rctx.routeParams?.[paramName] ?? null;
958
- }
959
-
960
- // Commerce extension wrappers — unwrap to inner data
961
- if (
962
- resolveType === WELL_KNOWN_TYPES.COMMERCE_EXT_DETAILS ||
963
- resolveType === WELL_KNOWN_TYPES.COMMERCE_EXT_LISTING
964
- ) {
965
- return obj.data ? internalResolve(obj.data, childCtx) : null;
966
- }
967
-
968
- // Multivariate flags
969
- if (
970
- resolveType === WELL_KNOWN_TYPES.MULTIVARIATE ||
971
- resolveType === WELL_KNOWN_TYPES.MULTIVARIATE_SECTION
972
- ) {
973
- const variants = obj.variants as Array<{ value: unknown; rule?: unknown }> | undefined;
974
- // No variant matched (incl. a single `never`-gated variant, i.e. a hidden
975
- // item) → resolve to `undefined`, the "not present" sentinel the array
976
- // branch filters out, rather than `null`, which would survive as a hole.
977
- if (!variants || variants.length === 0) return undefined;
978
-
979
- for (const variant of variants) {
980
- const rule = variant.rule as Record<string, unknown> | undefined;
981
- if (evaluateVariantRule(rule, rctx.matcherCtx)) {
982
- return internalResolve(variant.value, childCtx);
983
- }
984
- }
985
- return undefined;
986
- }
987
-
988
- // Commerce loaders
989
- const commerceLoader = getCommerceLoader(resolveType);
990
- if (commerceLoader) {
991
- const { __resolveType: _, ...loaderProps } = obj;
992
- const resolvedProps = await resolveProps(loaderProps, childCtx);
993
-
994
- if (rctx.matcherCtx.path) {
995
- resolvedProps.__pagePath = rctx.matcherCtx.path;
996
- }
997
- if (rctx.matcherCtx.url) {
998
- // Strip tracking params before anything here reaches props.
999
- //
1000
- // The comment this replaces claimed the enrichment was "safe re: cache
1001
- // fragmentation" because commerce loaders run without a framework-level
1002
- // cache. That was wrong — `getCommerceLoader()` returns the
1003
- // `createCachedLoader`-wrapped functions, whose default keyFn hashes
1004
- // exactly these props — so a `?utm_source`/`gclid`/`srsltid` minted a
1005
- // fresh cache entry and made every paid-traffic landing a permanent cold
1006
- // miss. Measured on a production storefront: 0.2–1.5% hit rate on the
1007
- // default keyFn vs 73.5% on a loader that hand-rolled a key excluding it.
1008
- //
1009
- // Stripping here rather than in the keyFn covers `__pageUrl` and the
1010
- // param spread below in one place, and matches how the edge cache key is
1011
- // already normalized in workerEntry. No loader reads tracking params.
1012
- //
1013
- // Deliberately does NOT drop `__pageUrl`/`__pagePath` themselves: on a
1014
- // PDP the path IS the product identity (the CMS block leaves `slug`
1015
- // null) and on a PLP the query carries the facets. Dropping them would
1016
- // merge distinct results onto one entry and serve wrong content.
1017
- const pageUrl = stripTrackingParams(rctx.matcherCtx.url);
1018
- resolvedProps.__pageUrl = pageUrl;
1019
- // Auto-inject URL search params as top-level props so loaders that
1020
- // expect `props.skuId` / `props.q` / `props.page` (the apps-start
1021
- // canonical shape) get them populated on direct entry (Google
1022
- // Shopping deep links, paid ads, email campaigns). Existing values
1023
- // from the CMS block win — URL params are a fallback, not an
1024
- // override.
1025
- if (URL.canParse(pageUrl)) {
1026
- const url = new URL(pageUrl);
1027
- for (const [k, v] of url.searchParams.entries()) {
1028
- if (resolvedProps[k] !== undefined) continue;
1029
- // `page` is skipped on purpose (#391): loaders that read `page`
1030
- // from `__pageUrl` themselves (e.g. VTEX's PLP loader) apply their
1031
- // own 1-indexed-URL -> 0-indexed-internal conversion. Auto-injecting
1032
- // the raw 1-indexed URL string here as `props.page` bypasses that
1033
- // conversion and produces an off-by-one, on top of arriving as an
1034
- // un-coerced string. Numeric conventional names get coerced so a
1035
- // loader declaring `count?: number` doesn't receive a raw string.
1036
- if (k === "page") continue;
1037
- if ((k === "count" || k === "pageOffset") && Number.isFinite(Number(v))) {
1038
- resolvedProps[k] = Number(v);
1039
- continue;
1040
- }
1041
- resolvedProps[k] = v;
1042
- }
1043
- } else {
1044
- // Loud warning instead of silent swallow: matcherCtx.url should
1045
- // always be a fully-qualified URL (set from `getRequestUrl()` in
1046
- // cmsRoute.ts). If we see a malformed value here, something
1047
- // upstream is wrong — surface it so the caller can fix it.
1048
- console.warn(
1049
- `[CMS] malformed matcherCtx.url for "${resolveType}"; ` +
1050
- `skipping query-param injection: ${pageUrl}`,
1051
- );
1052
- }
1053
- }
1054
-
1055
- try {
1056
- return await commerceLoader(resolvedProps);
1057
- } catch (error) {
1058
- onResolveError(error, resolveType, "Commerce loader");
1059
- // Commerce loaders (VTEX product/PLP/PDP data) are the primary source of
1060
- // page-body data — this is exactly the layer that fails during a VTEX
1061
- // outage. Flag the page degraded so the edge won't cache the empty
1062
- // result as a healthy 200 (see X-Deco-Degraded in cmsRoute/workerEntry).
1063
- markSectionDegraded(resolveType);
1064
- return null;
1065
- }
1066
- }
1067
-
1068
- // Preview handler — admin sends { __resolveType: "preview", block: "BlockName", ...props }
1069
- // to preview a named block. Redirect resolution to the named block.
1070
- if (resolveType === "preview") {
1071
- const blockName = obj.block as string | undefined;
1072
- if (!blockName) return null;
1073
- const { __resolveType: _, block: _b, ...overrideProps } = obj;
1074
- return internalResolve({ __resolveType: blockName, ...overrideProps }, childCtx);
1075
- }
1076
-
1077
- // Named block reference (memoized)
1078
- const blocks = loadBlocks();
1079
- if (blocks[resolveType]) {
1080
- const memoKey = JSON.stringify(obj);
1081
- if (rctx.memo.has(memoKey)) {
1082
- return rctx.memo.get(memoKey);
1083
- }
1084
-
1085
- const referencedBlock = blocks[resolveType] as Record<string, unknown>;
1086
- const { __resolveType: _rt, ...restOverrides } = obj;
1087
- const resultPromise = internalResolve({ ...referencedBlock, ...restOverrides }, childCtx);
1088
- rctx.memo.set(memoKey, resultPromise);
1089
-
1090
- const result = await resultPromise;
1091
- rctx.memo.set(memoKey, result);
1092
- return result;
1093
- }
1094
-
1095
- // Dangling reference — unresolvable __resolveType
1096
- if (resolveType.includes("/loaders/") || resolveType.includes("/actions/")) {
1097
- return onDanglingReference(resolveType);
1098
- }
1099
-
1100
- // Unknown type — resolve props but preserve __resolveType (it's a section)
1101
- const { __resolveType: _, ...rest } = obj;
1102
-
1103
- // onBeforeResolveProps: let sections transform raw props before resolution.
1104
- // This runs with unresolved props (containing __resolveType refs) so sections
1105
- // can extract metadata that would be lost after resolution (e.g., collection IDs).
1106
- const propsToResolve = await applyOnBeforeResolveProps(resolveType, rest);
1107
-
1108
- const resolvedRest = await resolveProps(propsToResolve, childCtx);
1109
- return { __resolveType: resolveType, ...resolvedRest };
1110
- }
1111
-
1112
- // ---------------------------------------------------------------------------
1113
- // Nested section normalization
1114
- // ---------------------------------------------------------------------------
1115
-
1116
- /**
1117
- * Recursively walks resolved props and converts nested sections
1118
- * from `{ __resolveType: "site/sections/...", ...props }` to
1119
- * `{ component: "site/sections/...", props: {...} }`.
1120
- *
1121
- * This preserves the same `{ Component, props }` shape used by deco-cx/deco (Fresh)
1122
- * so that section code can be ported without API changes. In TanStack, `Component`
1123
- * is the registry key string (not a function ref), and the renderer does the lookup.
1124
- */
1125
- function normalizeNestedSections(value: unknown): unknown {
1126
- if (!value || typeof value !== "object") return value;
1127
-
1128
- if (Array.isArray(value)) {
1129
- return value.map(normalizeNestedSections);
1130
- }
1131
-
1132
- const obj = value as Record<string, unknown>;
1133
- const rt = obj.__resolveType as string | undefined;
1134
-
1135
- if (rt && getSection(rt)) {
1136
- const { __resolveType: _, ...rest } = obj;
1137
- const normalizedProps: Record<string, unknown> = {};
1138
- for (const [k, v] of Object.entries(rest)) {
1139
- normalizedProps[k] = normalizeNestedSections(v);
1140
- }
1141
- return { Component: rt, props: normalizedProps };
1142
- }
1143
-
1144
- const result: Record<string, unknown> = {};
1145
- for (const [k, v] of Object.entries(obj)) {
1146
- result[k] = normalizeNestedSections(v);
1147
- }
1148
- return result;
1149
- }
1150
-
1151
- // ---------------------------------------------------------------------------
1152
- // Public API
1153
- // ---------------------------------------------------------------------------
1154
-
1155
- /**
1156
- * Resolve a value by recursively processing __resolveType references.
1157
- * Supports memoization, commerce loaders, matchers, and flags.
1158
- */
1159
- export async function resolveValue(
1160
- value: unknown,
1161
- routeParams?: Record<string, string>,
1162
- matcherCtx?: MatcherContext,
1163
- options?: { select?: string[] },
1164
- ): Promise<unknown> {
1165
- const rctx: ResolveContext = {
1166
- routeParams,
1167
- matcherCtx: matcherCtx ?? {},
1168
- memo: new Map(),
1169
- depth: 0,
1170
- };
1171
- const result = await internalResolve(value, rctx);
1172
- return options?.select ? applySelect(result, options.select) : result;
1173
- }
1174
-
1175
- // ---------------------------------------------------------------------------
1176
- // Layout section CMS-resolve cache
1177
- // Caches the fully-resolved CMS output for layout sections so that
1178
- // commerce loaders (intelligent-search, cross-selling, etc.) inside
1179
- // Header/Footer blocks aren't re-executed on every page navigation.
1180
- // ---------------------------------------------------------------------------
1181
-
1182
- const RESOLVE_CACHE_TTL = 5 * 60_000;
1183
-
1184
- interface ResolvedSectionsCache {
1185
- sections: ResolvedSection[];
1186
- expiresAt: number;
1187
- }
1188
-
1189
- const resolvedLayoutCache = createCacheStore<ResolvedSectionsCache>("resolved-layouts");
1190
- const resolvedLayoutInflight = new Map<string, Promise<ResolvedSection[]>>();
1191
-
1192
- /**
1193
- * Cache key for a resolved layout block, segmented by DEVICE.
1194
- *
1195
- * The key used to be the component path alone, and that made the cache unusable
1196
- * for any site whose Header/Footer takes a per-request device prop: the first
1197
- * visitor's variant was served to everyone for the whole TTL (mobile header on
1198
- * desktop and vice-versa). The only escape was to leave those sections out of
1199
- * `registerLayoutSections` entirely — which is what a real store did, and it
1200
- * then re-resolved Header and Footer on every single page and navigation.
1201
- *
1202
- * Device is the right default axis because it is the one thing the framework
1203
- * itself injects into every section (`sectionLoaderContext` → `detectDevice`),
1204
- * so a layout section can depend on it WITHOUT the site opting into anything.
1205
- * A layout that does not vary by device just gets up to 3 identical entries —
1206
- * a bounded, negligible cost against silently serving the wrong markup.
1207
- *
1208
- * Anything else a layout varies on (region, sales channel, locale) is
1209
- * site-specific and NOT covered here: those sections should stay out of
1210
- * `registerLayoutSections` until there is a demonstrated need for a `vary`
1211
- * hook. Adding axes nobody asked for only shrinks the hit rate.
1212
- *
1213
- * Exported for unit testing.
1214
- */
1215
- export function layoutCacheKey(blockKey: string, matcherCtx?: MatcherContext): string {
1216
- return `${blockKey}::${detectDevice(matcherCtx?.userAgent ?? "")}`;
1217
- }
1218
-
1219
- async function getCachedResolvedLayout(blockKey: string): Promise<ResolvedSection[] | null> {
1220
- const entry = await resolvedLayoutCache.read(blockKey);
1221
- if (!entry) return null;
1222
- if (Date.now() > entry.expiresAt) {
1223
- resolvedLayoutCache.delete(blockKey);
1224
- return null;
1225
- }
1226
- return entry.sections;
1227
- }
1228
-
1229
- function setCachedResolvedLayout(blockKey: string, sections: ResolvedSection[]): void {
1230
- resolvedLayoutCache.set(
1231
- blockKey,
1232
- {
1233
- sections,
1234
- expiresAt: Date.now() + RESOLVE_CACHE_TTL,
1235
- },
1236
- Date.now() + RESOLVE_CACHE_TTL,
1237
- );
1238
- }
1239
-
1240
- /**
1241
- * Resolves a raw section block to ResolvedSection[].
1242
- * Used for both layout and non-layout sections.
1243
- */
1244
- async function resolveRawSection(
1245
- section: unknown,
1246
- rctx: ResolveContext,
1247
- ): Promise<ResolvedSection[]> {
1248
- const resolved = await internalResolve(section, rctx);
1249
- if (!resolved || typeof resolved !== "object") return [];
1250
-
1251
- const items = Array.isArray(resolved) ? resolved : [resolved];
1252
- const results: ResolvedSection[] = [];
1253
-
1254
- for (const item of items) {
1255
- if (!item || typeof item !== "object") continue;
1256
- const obj = item as Record<string, unknown>;
1257
- if (!obj.__resolveType) continue;
1258
-
1259
- const resolveType = obj.__resolveType as string;
1260
- const sectionLoader = getSection(resolveType);
1261
- if (!sectionLoader) {
1262
- console.warn(`[CMS] No component registered for: ${resolveType}`);
1263
- continue;
1264
- }
1265
-
1266
- const { __resolveType: _, ...rawProps } = obj;
1267
- const props = normalizeNestedSections(rawProps) as Record<string, unknown>;
1268
- results.push({
1269
- component: resolveType,
1270
- props,
1271
- key: resolveType,
1272
- });
1273
- }
1274
-
1275
- return results;
1276
- }
1277
-
1278
- // ---------------------------------------------------------------------------
1279
- // Page-level SEO block resolution
1280
- // ---------------------------------------------------------------------------
1281
-
1282
- /**
1283
- * Resolve the page-level `seo` field from the CMS page JSON.
1284
- *
1285
- * The CMS stores SEO config in `page.seo` as a separate field from
1286
- * `page.sections`. This field is typically a SeoV2.tsx block (homepage)
1287
- * or a site SEO section like SEOPDP.tsx wrapped in Lazy (PDP).
1288
- *
1289
- * This function always resolves eagerly — SEO metadata must never be
1290
- * deferred because search engine crawlers need it in the initial HTML.
1291
- * Lazy/Deferred wrappers are unwrapped, block references are followed,
1292
- * and commerce loader refs (e.g. PDP jsonLD) are resolved.
1293
- *
1294
- * Returns a ResolvedSection with the final component key and resolved props,
1295
- * or null if the seo field is absent/unresolvable.
1296
- */
1297
- export async function resolvePageSeoBlock(
1298
- seoBlock: Record<string, unknown> | undefined,
1299
- rctx: ResolveContext,
1300
- ): Promise<ResolvedSection | null> {
1301
- if (!seoBlock || typeof seoBlock !== "object") return null;
1302
-
1303
- // Bot-aware SEO: crawlers get the SEO block fully resolved (e.g. a
1304
- // ProductListingPage for JSON-LD ItemList) — that content exists for indexing;
1305
- // humans get only the lightweight metadata, with SEO props backed by a commerce
1306
- // loader skipped (see `stripCommerceLoaderProps`) so SSR doesn't block on the
1307
- // heavy upstream call and the bulky payload never reaches the human HTML.
1308
- //
1309
- // The skip is driven per-section by the editor's `ignoreStructuredData` toggle
1310
- // (the primary, client-facing lever — see `sectionIgnoresStructuredData`), OR
1311
- // site-wide by the legacy `setAsyncRenderingConfig({ botAwareSeo: true })`
1312
- // shortcut. When neither is set, resolve fully for EVERYONE (the previous
1313
- // default) so sites without a lightweight title fallback are not regressed to
1314
- // a generic `<title>`. The final decision is made at the terminal section
1315
- // below, where the section's raw props are known.
1316
- const isEagerReq = isEagerRequest(rctx.matcherCtx);
1317
- const globalBotAware = getAsyncConfig()?.botAwareSeo ?? false;
1318
-
1319
- const blocks = loadBlocks();
1320
- let current = seoBlock;
1321
-
1322
- for (let depth = 0; depth < 10; depth++) {
1323
- const rt = current.__resolveType as string | undefined;
1324
- if (!rt) return null;
1325
-
1326
- // Lazy wrapper — always unwrap for SEO (never defer)
1327
- if (rt === "website/sections/Rendering/Lazy.tsx") {
1328
- const inner = current.section;
1329
- if (!inner || typeof inner !== "object") return null;
1330
- current = inner as Record<string, unknown>;
1331
- continue;
1332
- }
1333
-
1334
- // Deferred wrapper — unwrap
1335
- if (rt === "website/sections/Rendering/Deferred.tsx") {
1336
- const inner = current.sections;
1337
- if (!inner || typeof inner !== "object") return null;
1338
- if (Array.isArray(inner) && inner.length === 1 && inner[0] && typeof inner[0] === "object") {
1339
- current = inner[0] as Record<string, unknown>;
1340
- continue;
1341
- }
1342
- return null;
1343
- }
1344
-
1345
- // Multivariate flag — evaluate matcher and follow matched variant
1346
- if (rt === "website/flags/multivariate.ts" || rt === "website/flags/multivariate/section.ts") {
1347
- const variants = current.variants as Array<{ value: unknown; rule?: unknown }> | undefined;
1348
- if (!variants?.length) return null;
1349
- let matched: unknown = null;
1350
- for (const variant of variants) {
1351
- const rule = variant.rule as Record<string, unknown> | undefined;
1352
- if (evaluateVariantRule(rule, rctx.matcherCtx)) {
1353
- matched = variant.value;
1354
- break;
1355
- }
1356
- }
1357
- if (!matched || typeof matched !== "object") return null;
1358
- current = matched as Record<string, unknown>;
1359
- continue;
1360
- }
1361
-
1362
- // Named block reference — follow the chain
1363
- const block = blocks[rt] as Record<string, unknown> | undefined;
1364
- if (block) {
1365
- const { __resolveType: _, ...overrides } = current;
1366
- current = { ...block, ...overrides };
1367
- continue;
1368
- }
1369
-
1370
- // Terminal section (site section or framework SEO type).
1371
- // Resolve all nested prop __resolveType refs (commerce loaders, etc.).
1372
- const { __resolveType: _, ...rawProps } = current;
1373
- // For humans, drop SEO props whose value resolves to a commerce loader
1374
- // (e.g. `jsonLD: { __resolveType: "PLP Loader" }`). This avoids the heavy
1375
- // SSR fetch and keeps the product payload out of the human HTML. Bots keep
1376
- // the full props so JSON-LD/rich metadata is still emitted for indexing.
1377
- // Skip only when the editor turned on `ignoreStructuredData` for this
1378
- // section, or the site-wide `botAwareSeo` shortcut is enabled.
1379
- const skipCommerceForHuman =
1380
- !isEagerReq && (globalBotAware || sectionIgnoresStructuredData(rawProps));
1381
- const propsToResolve = skipCommerceForHuman ? stripCommerceLoaderProps(rawProps) : rawProps;
1382
- try {
1383
- const resolvedProps = await resolveProps(propsToResolve, rctx);
1384
- return {
1385
- component: rt,
1386
- props: resolvedProps as Record<string, unknown>,
1387
- key: `seo:${rt}`,
1388
- };
1389
- } catch (e) {
1390
- onResolveError(e, rt, "Page SEO resolution");
1391
- return null;
1392
- }
1393
- }
1394
-
1395
- return null;
1396
- }
1397
-
1398
- /**
1399
- * Does resolving `value` invoke a commerce loader (a heavy upstream data
1400
- * fetch)? Walks named block references, Lazy/Deferred wrappers, commerce
1401
- * extension wrappers, and multivariate flags to find a terminal
1402
- * `__resolveType` registered in `commerceLoaders`.
1403
- *
1404
- * Used to keep commerce-backed SEO props (product listings/details for
1405
- * JSON-LD) out of the human SSR path while preserving them for bots.
1406
- */
1407
- function resolvesToCommerceLoader(value: unknown, depth = 0): boolean {
1408
- if (depth > 10 || !value || typeof value !== "object" || Array.isArray(value)) return false;
1409
- const obj = value as Record<string, unknown>;
1410
- const rt = obj.__resolveType as string | undefined;
1411
- if (!rt) return false;
1412
-
1413
- if (getCommerceLoader(rt)) return true;
1414
-
1415
- if (rt === WELL_KNOWN_TYPES.LAZY) return resolvesToCommerceLoader(obj.section, depth + 1);
1416
- if (rt === WELL_KNOWN_TYPES.DEFERRED) {
1417
- const inner = obj.sections;
1418
- const one = Array.isArray(inner) ? inner[0] : inner;
1419
- return resolvesToCommerceLoader(one, depth + 1);
1420
- }
1421
- if (
1422
- rt === WELL_KNOWN_TYPES.COMMERCE_EXT_DETAILS ||
1423
- rt === WELL_KNOWN_TYPES.COMMERCE_EXT_LISTING
1424
- ) {
1425
- // Extension wrappers carry their inner loader in `data`; they're commerce
1426
- // by definition, but guard the recursion for clarity.
1427
- return obj.data ? resolvesToCommerceLoader(obj.data, depth + 1) : true;
1428
- }
1429
- if (rt === WELL_KNOWN_TYPES.MULTIVARIATE || rt === WELL_KNOWN_TYPES.MULTIVARIATE_SECTION) {
1430
- const variants = obj.variants as Array<{ value?: unknown }> | undefined;
1431
- return Array.isArray(variants)
1432
- ? variants.some((v) => resolvesToCommerceLoader(v?.value, depth + 1))
1433
- : false;
1434
- }
1435
-
1436
- // Named block reference — follow one level of the chain.
1437
- const block = loadBlocks()[rt] as Record<string, unknown> | undefined;
1438
- if (block) return resolvesToCommerceLoader(block, depth + 1);
1439
-
1440
- return false;
1441
- }
1442
-
1443
- /**
1444
- * True when a commerce SEO section's props carry the editor's "Ignore Structured
1445
- * Data" toggle. This is the primary, client-facing lever for bot-aware SEO: with
1446
- * it on, humans receive no JSON-LD (and, on the page's SEO block, skip the heavy
1447
- * commerce fetch) while crawlers still get the full structured data.
1448
- *
1449
- * Two shapes, mirroring the Studio schema: top-level `ignoreStructuredData` on
1450
- * the PDP section, and nested under `configJsonLD` on the PLP section. Shared by
1451
- * the fetch-skip path (`resolvePageSeoBlock`, pre-resolution) and the
1452
- * output-strip path (`deriveCommerceSeoFromJsonLD`, post-resolution) so the two
1453
- * decisions can never read the toggle differently.
1454
- */
1455
- function sectionIgnoresStructuredData(props: Record<string, unknown>): boolean {
1456
- if (props.ignoreStructuredData === true) return true;
1457
- const configJsonLD = props.configJsonLD as { ignoreStructuredData?: boolean } | undefined;
1458
- return configJsonLD?.ignoreStructuredData === true;
1459
- }
1460
-
1461
- /**
1462
- * Return a copy of `rawProps` with every top-level field that resolves to a
1463
- * commerce loader removed. Applied to page SEO props for human (non-bot)
1464
- * requests so the heavy commerce fetch is skipped and its payload is never
1465
- * serialized into the HTML. Lightweight literal props (title, description,
1466
- * canonical, …) are preserved.
1467
- */
1468
- function stripCommerceLoaderProps(rawProps: Record<string, unknown>): Record<string, unknown> {
1469
- const out: Record<string, unknown> = {};
1470
- for (const [k, v] of Object.entries(rawProps)) {
1471
- if (resolvesToCommerceLoader(v)) continue;
1472
- out[k] = v;
1473
- }
1474
- return out;
1475
- }
1476
-
1477
- /**
1478
- * Check if a raw CMS section block will produce a layout section.
1479
- * Walks the block reference chain (up to 5 levels) to find the final
1480
- * section component key. Returns the top-level block name for caching.
1481
- *
1482
- * Example: {"__resolveType": "Header - 01"} -> block has
1483
- * __resolveType "site/sections/Header/Header.tsx" -> that's a layout section
1484
- * -> returns "Header - 01" as the cache key.
1485
- */
1486
- function isRawSectionLayout(section: unknown): string | null {
1487
- if (!section || typeof section !== "object") return null;
1488
- const obj = section as Record<string, unknown>;
1489
- const topLevelRt = obj.__resolveType as string | undefined;
1490
- if (!topLevelRt) return null;
1491
-
1492
- if (isLayoutSection(topLevelRt)) return topLevelRt;
1493
-
1494
- const blocks = loadBlocks();
1495
- let currentRt: string | undefined = topLevelRt;
1496
- for (let i = 0; i < 5; i++) {
1497
- const block = blocks[currentRt] as Record<string, unknown> | undefined;
1498
- if (!block) break;
1499
- currentRt = block.__resolveType as string | undefined;
1500
- if (!currentRt) break;
1501
- if (isLayoutSection(currentRt)) return topLevelRt;
1502
- }
1503
-
1504
- return null;
1505
- }
1506
-
1507
- /**
1508
- * Resolve the final section component key by walking block references,
1509
- * unwrapping Lazy/Deferred wrappers, and evaluating multivariate flags.
1510
- * Returns null if not determinable.
1511
- */
1512
- function resolveFinalSectionKey(section: unknown, matcherCtx?: MatcherContext): string | null {
1513
- if (!section || typeof section !== "object") return null;
1514
-
1515
- const blocks = loadBlocks();
1516
- let current = section as Record<string, unknown>;
1517
-
1518
- for (let depth = 0; depth < 10; depth++) {
1519
- const rt = current.__resolveType as string | undefined;
1520
- if (!rt) return null;
1521
-
1522
- // Lazy wrapper — unwrap single inner section
1523
- if (rt === WELL_KNOWN_TYPES.LAZY) {
1524
- const inner = current.section;
1525
- if (!inner || typeof inner !== "object") return null;
1526
- current = inner as Record<string, unknown>;
1527
- continue;
1528
- }
1529
-
1530
- // Deferred wrapper (legacy) — unwrap first inner section if deterministic
1531
- if (rt === "website/sections/Rendering/Deferred.tsx") {
1532
- const inner = current.sections;
1533
- if (!inner || typeof inner !== "object") return null;
1534
- if (Array.isArray(inner)) {
1535
- if (inner.length === 1 && inner[0] && typeof inner[0] === "object") {
1536
- current = inner[0] as Record<string, unknown>;
1537
- continue;
1538
- }
1539
- return null;
1540
- }
1541
- // sections is an object (e.g. a flag) — follow it
1542
- current = inner as Record<string, unknown>;
1543
- continue;
1544
- }
1545
-
1546
- if (rt === WELL_KNOWN_TYPES.MULTIVARIATE || rt === WELL_KNOWN_TYPES.MULTIVARIATE_SECTION) {
1547
- const variants = current.variants as Array<{ value: unknown; rule?: unknown }> | undefined;
1548
- if (!variants?.length) return null;
1549
-
1550
- let matched: unknown = null;
1551
- for (const variant of variants) {
1552
- const rule = variant.rule as Record<string, unknown> | undefined;
1553
- if (evaluateVariantRule(rule, matcherCtx ?? {})) {
1554
- matched = variant.value;
1555
- break;
1556
- }
1557
- }
1558
- if (!matched || typeof matched !== "object") return null;
1559
- current = matched as Record<string, unknown>;
1560
- continue;
1561
- }
1562
-
1563
- if (getSection(rt)) return rt;
1564
-
1565
- const block = blocks[rt] as Record<string, unknown> | undefined;
1566
- if (block) {
1567
- const { __resolveType: _, ...overrides } = current;
1568
- current = { ...block, ...overrides };
1569
- continue;
1570
- }
1571
-
1572
- return rt;
1573
- }
1574
-
1575
- return null;
1576
- }
1577
-
1578
- /**
1579
- * Walk the full wrapper chain (block refs, multivariate flags, Lazy, Deferred)
1580
- * and return true if a deferral wrapper (Lazy.tsx or Deferred.tsx) is found
1581
- * at any level. This is used by shouldDeferSection to determine if the CMS
1582
- * editor intended this section to be deferred.
1583
- */
1584
- function isCmsDeferralWrapped(section: unknown, matcherCtx?: MatcherContext): boolean {
1585
- if (!section || typeof section !== "object") return false;
1586
-
1587
- const blocks = loadBlocks();
1588
- let current = section as Record<string, unknown>;
1589
-
1590
- for (let depth = 0; depth < 10; depth++) {
1591
- const rt = current.__resolveType as string | undefined;
1592
- if (!rt) return false;
1593
-
1594
- if (rt === WELL_KNOWN_TYPES.LAZY || rt === WELL_KNOWN_TYPES.DEFERRED) {
1595
- return true;
1596
- }
1597
-
1598
- // Walk through multivariate flags to check the matched variant
1599
- if (rt === WELL_KNOWN_TYPES.MULTIVARIATE || rt === WELL_KNOWN_TYPES.MULTIVARIATE_SECTION) {
1600
- const variants = current.variants as Array<{ value: unknown; rule?: unknown }> | undefined;
1601
- if (!variants?.length) return false;
1602
-
1603
- let matched: unknown = null;
1604
- for (const variant of variants) {
1605
- const rule = variant.rule as Record<string, unknown> | undefined;
1606
- if (evaluateVariantRule(rule, matcherCtx ?? {})) {
1607
- matched = variant.value;
1608
- break;
1609
- }
1610
- }
1611
- if (!matched || typeof matched !== "object") return false;
1612
- current = matched as Record<string, unknown>;
1613
- continue;
1614
- }
1615
-
1616
- // Named block reference — follow the chain
1617
- const block = blocks[rt] as Record<string, unknown> | undefined;
1618
- if (block) {
1619
- const { __resolveType: _, ...overrides } = current;
1620
- current = { ...block, ...overrides, __resolveType: block.__resolveType as string };
1621
- continue;
1622
- }
1623
-
1624
- return false;
1625
- }
1626
-
1627
- return false;
1628
- }
1629
-
1630
- /**
1631
- * Decide whether a section is deferred (rendered client-side on scroll) or
1632
- * rendered eagerly (SSR).
1633
- *
1634
- * The admin is the source of truth: a section the editor marked async ⚡
1635
- * (wrapped in CMS `Lazy.tsx`/`Deferred.tsx`) is ALWAYS deferred, and a section
1636
- * the editor left unmarked is ALWAYS eager — independent of its position on the
1637
- * page and of any `export const eager`/`neverDefer`/`alwaysEager` flag in the
1638
- * section code. The admin ⚡ check runs first and overrides every code flag.
1639
- *
1640
- * The position threshold and code-level eager flags are an explicit per-site
1641
- * opt-in: they only take effect when a site sets a finite `foldThreshold`
1642
- * (default {@link DEFAULT_FOLD_THRESHOLD} = `Infinity`, i.e. disabled), and even
1643
- * then they can only force a NON-⚡ section eager — they never override the
1644
- * editor's ⚡ choice.
1645
- *
1646
- * Because deferral now applies to client (SPA) navigations too, a ⚡ section is
1647
- * resolved on a SECOND server hop (`loadDeferredSection`) in both cases. That
1648
- * hop rebuilds MatcherContext from the real request, but it cannot reconstruct
1649
- * "which branch of the page renders at all" — so a *gate* section (one whose
1650
- * loader picks between `children`/`fallback`, e.g. a combined PDP/PLP route)
1651
- * must be left un-⚡ in the admin. There is deliberately no code-level override
1652
- * for this: `neverDefer`/`alwaysEager` sit below the admin check and cannot win
1653
- * against an explicit editorial ⚡ (see decocms/blocks#277).
1654
- *
1655
- * Exported for unit testing.
1656
- */
1657
- export function shouldDeferSection(
1658
- section: unknown,
1659
- flatIndex: number,
1660
- cfg: AsyncRenderingConfig,
1661
- isBotReq: boolean,
1662
- matcherCtx?: MatcherContext,
1663
- ): boolean {
1664
- // Crawlers always get the full page server-rendered — deferral would hide
1665
- // content from indexing. This is an SEO guarantee, not a code override of
1666
- // editorial intent: it makes ⚡ content MORE visible to bots.
1667
- if (isBotReq) return false;
1668
-
1669
- if (!section || typeof section !== "object") return false;
1670
- const obj = section as Record<string, unknown>;
1671
- const rt = obj.__resolveType as string | undefined;
1672
- if (!rt) return false;
1673
-
1674
- const finalKey = resolveFinalSectionKey(section, matcherCtx);
1675
- if (!finalKey) return false;
1676
-
1677
- // ── PER-SECTION FORCE-DEFER (`export const deferred = true`) ───────────────
1678
- // Explicit code-level opt-in to defer one section regardless of the global
1679
- // `respectCmsLazy` config — lets a site async-render a single heavy section
1680
- // without a site-wide skeleton sweep. Bots already returned eager above.
1681
- if (isAlwaysDeferSection(finalKey)) return true;
1682
-
1683
- // ── ADMIN IS THE SOURCE OF TRUTH ──────────────────────────────────────────
1684
- // If the editor marked the section ⚡ (wrapped in CMS Lazy/Deferred at any
1685
- // nesting level, including multivariate flags), it is deferred —
1686
- // unconditionally, overriding every code-level flag below. This is the only
1687
- // thing that drives deferral in the default configuration.
1688
- if (cfg.respectCmsLazy && isCmsDeferralWrapped(section, matcherCtx)) return true;
1689
-
1690
- // ── Everything below is OPT-IN ONLY ───────────────────────────────────────
1691
- // These checks never override the admin (handled above). They are inert with
1692
- // the default `foldThreshold = Infinity` and only matter when a site
1693
- // explicitly opts into a finite threshold — where they protect specific
1694
- // NON-⚡ sections from position-based deferral.
1695
-
1696
- // Layout sections (Header, Footer, Theme) are shared across pages and their
1697
- // resolved output is cached; deferring them would flash a skeleton on every
1698
- // navigation.
1699
- if (isLayoutSection(finalKey)) return false;
1700
-
1701
- // `export const neverDefer = true` — keep eager regardless of threshold.
1702
- if (isNeverDeferSection(finalKey)) return false;
1703
-
1704
- // `export const eager = true` / alwaysEager — keep eager within the fold.
1705
- if (flatIndex < cfg.foldThreshold) {
1706
- if (isEagerSection(finalKey)) return false;
1707
- if (cfg.alwaysEager.has(finalKey)) return false;
1708
- }
1709
-
1710
- // Position-based fallback — disabled by default (foldThreshold = Infinity).
1711
- if (flatIndex >= cfg.foldThreshold) return true;
1712
-
1713
- return false;
1714
- }
1715
-
1716
- /**
1717
- * Follow the block reference chain to find the final section component
1718
- * and collect the CMS props WITHOUT running commerce loaders.
1719
- * Resolves named block references, Lazy/Deferred wrappers, and multivariate flags.
1720
- *
1721
- * For Deferred.tsx with a single inner section, the inner section is returned.
1722
- * For Deferred.tsx with multiple inner sections, returns null (falls back to eager).
1723
- */
1724
- function resolveSectionShallow(
1725
- section: unknown,
1726
- matcherCtx?: MatcherContext,
1727
- ): DeferredSection | null {
1728
- if (!section || typeof section !== "object") return null;
1729
-
1730
- const blocks = loadBlocks();
1731
- let current = section as Record<string, unknown>;
1732
- const MAX_DEPTH = 10;
1733
-
1734
- for (let depth = 0; depth < MAX_DEPTH; depth++) {
1735
- const rt = current.__resolveType as string | undefined;
1736
- if (!rt) return null;
1737
-
1738
- if (SKIP_RESOLVE_TYPES.has(rt)) return null;
1739
-
1740
- // Lazy wrapper — unwrap to the inner section
1741
- if (rt === WELL_KNOWN_TYPES.LAZY) {
1742
- const inner = current.section;
1743
- if (!inner || typeof inner !== "object") return null;
1744
- current = inner as Record<string, unknown>;
1745
- continue;
1746
- }
1747
-
1748
- // Deferred wrapper (legacy) — unwrap if it contains a single section
1749
- if (rt === "website/sections/Rendering/Deferred.tsx") {
1750
- const inner = current.sections;
1751
- if (!inner || typeof inner !== "object") return null;
1752
- if (Array.isArray(inner)) {
1753
- if (inner.length === 1 && inner[0] && typeof inner[0] === "object") {
1754
- current = inner[0] as Record<string, unknown>;
1755
- continue;
1756
- }
1757
- // Multiple inner sections can't be represented as a single DeferredSection
1758
- return null;
1759
- }
1760
- // sections is an object (e.g. a flag) — follow it
1761
- current = inner as Record<string, unknown>;
1762
- continue;
1763
- }
1764
-
1765
- // Multivariate flags — evaluate matchers and continue with matched variant
1766
- if (rt === WELL_KNOWN_TYPES.MULTIVARIATE || rt === WELL_KNOWN_TYPES.MULTIVARIATE_SECTION) {
1767
- const variants = current.variants as Array<{ value: unknown; rule?: unknown }> | undefined;
1768
- if (!variants?.length) return null;
1769
-
1770
- let matched: unknown = null;
1771
- for (const variant of variants) {
1772
- const rule = variant.rule as Record<string, unknown> | undefined;
1773
- if (evaluateVariantRule(rule, matcherCtx ?? {})) {
1774
- matched = variant.value;
1775
- break;
1776
- }
1777
- }
1778
- if (!matched || typeof matched !== "object") return null;
1779
- current = matched as Record<string, unknown>;
1780
- continue;
1781
- }
1782
-
1783
- // Check if this is a registered section — we found it
1784
- if (getSection(rt)) {
1785
- const { __resolveType: _, ...rawProps } = current;
1786
- return {
1787
- component: rt,
1788
- key: rt,
1789
- index: -1,
1790
- propsHash: djb2Hex(JSON.stringify(rawProps)),
1791
- rawProps: rawProps as Record<string, unknown>,
1792
- };
1793
- }
1794
-
1795
- // Named block reference — follow the chain
1796
- const block = blocks[rt] as Record<string, unknown> | undefined;
1797
- if (block) {
1798
- const { __resolveType: _rtOuter, ...overrides } = current;
1799
- current = { ...block, ...overrides };
1800
- continue;
1801
- }
1802
-
1803
- return null;
1804
- }
1805
-
1806
- return null;
1807
- }
1808
-
1809
- /**
1810
- * Resolve outer wrappers (flags, block references) around the sections list
1811
- * to get the raw section array without resolving each individual section.
1812
- * This allows the eager/deferred split to happen before section resolution.
1813
- */
1814
- export async function resolveSectionsList(
1815
- value: unknown,
1816
- rctx: ResolveContext,
1817
- depth = 0,
1818
- ): Promise<unknown[]> {
1819
- if (depth > MAX_RESOLVE_DEPTH) return [];
1820
- if (!value || typeof value !== "object") return [];
1821
- if (Array.isArray(value)) return value;
1822
-
1823
- const obj = value as Record<string, unknown>;
1824
- const rt = obj.__resolveType as string | undefined;
1825
-
1826
- // Page-level variant wrapper without __resolveType
1827
- // (CMS admin wraps ALL sections in a variant object with { variants: [...] })
1828
- if (!rt && Array.isArray(obj.variants)) {
1829
- const variants = obj.variants as Array<{ value: unknown; rule?: unknown }>;
1830
- for (const variant of variants) {
1831
- const rule = variant.rule as Record<string, unknown> | undefined;
1832
- if (evaluateVariantRule(rule, rctx.matcherCtx)) {
1833
- return resolveSectionsList(variant.value, rctx, depth + 1);
1834
- }
1835
- }
1836
- return [];
1837
- }
1838
-
1839
- if (!rt) return [];
1840
-
1841
- // Multivariate flags — evaluate matchers and recurse into matched variant
1842
- if (rt === WELL_KNOWN_TYPES.MULTIVARIATE || rt === WELL_KNOWN_TYPES.MULTIVARIATE_SECTION) {
1843
- const variants = obj.variants as Array<{ value: unknown; rule?: unknown }> | undefined;
1844
- if (!variants?.length) return [];
1845
- for (const variant of variants) {
1846
- const rule = variant.rule as Record<string, unknown> | undefined;
1847
- if (evaluateVariantRule(rule, rctx.matcherCtx)) {
1848
- return resolveSectionsList(variant.value, rctx, depth + 1);
1849
- }
1850
- }
1851
- return [];
1852
- }
1853
-
1854
- // Named block reference — follow the chain
1855
- const blocks = loadBlocks();
1856
- if (blocks[rt]) {
1857
- const referencedBlock = blocks[rt] as Record<string, unknown>;
1858
- const { __resolveType: _rtOuter, ...restOverrides } = obj;
1859
- return resolveSectionsList({ ...referencedBlock, ...restOverrides }, rctx, depth + 1);
1860
- }
1861
-
1862
- // Resolved — unwrap
1863
- if (rt === "resolved") {
1864
- const data = obj.data;
1865
- if (Array.isArray(data)) return data;
1866
- return [];
1867
- }
1868
-
1869
- return [];
1870
- }
1871
-
1872
- // ---------------------------------------------------------------------------
1873
- // Deferred props (`asResolved`)
1874
- // ---------------------------------------------------------------------------
1875
-
1876
- /** A prop deferred with `asResolved(value, true)`: call it to resolve. */
1877
- export type Deferred<T> = () => Promise<T>;
1878
-
1879
- /**
1880
- * Mark a prop as already-resolved, or defer its resolution to the section.
1881
- *
1882
- * Use it from a section's `onBeforeResolveProps`, which runs on the RAW CMS
1883
- * props before the resolver walks them:
1884
- *
1885
- * ```ts
1886
- * export const onBeforeResolveProps = (props: Props) => ({
1887
- * ...props,
1888
- * // The 404 fallback: only the branch that renders it should pay for it.
1889
- * notFoundSections: asResolved(props.notFoundSections, true),
1890
- * })
1891
- *
1892
- * export const loader = async (props: Props) => {
1893
- * if (props.page) return { ...props, notFoundSections: [] }
1894
- * return { ...props, notFoundSections: await resolveDeferred(props.notFoundSections) }
1895
- * }
1896
- * ```
1897
- *
1898
- * - `asResolved(v)` — hand `v` back untouched; the resolver does not walk it.
1899
- * - `asResolved(v, true)` — the section receives a {@link Deferred} thunk and
1900
- * decides whether to pay for it.
1901
- *
1902
- * A deferred prop that is never called reaches the client as `undefined`: a
1903
- * thunk cannot be serialized. That is deliberate — it is what keeps the unused
1904
- * branch out of the hydration payload too — but it means you must resolve it on
1905
- * the branch that renders it.
1906
- */
1907
- export function asResolved<T>(value: T, defer?: boolean): T {
1908
- return {
1909
- __resolveType: "resolved",
1910
- data: value,
1911
- ...(defer ? { deferred: true } : {}),
1912
- } as unknown as T;
1913
- }
1914
-
1915
- /** True when a prop came through as a {@link Deferred} thunk. */
1916
- export function isDeferred<T>(value: unknown): value is Deferred<T> {
1917
- return typeof value === "function";
1918
- }
1919
-
1920
- /**
1921
- * Resolve a possibly-deferred prop.
1922
- *
1923
- * Tolerant of a plain value, so a section reads the same whether the prop was
1924
- * deferred, marked already-resolved, or left alone — and so the admin preview
1925
- * (which does not run `onBeforeResolveProps`) keeps working.
1926
- */
1927
- export async function resolveDeferred<T>(value: Deferred<T> | T): Promise<T> {
1928
- return isDeferred<T>(value) ? await value() : (value as T);
1929
- }
1930
-
1931
- // ---------------------------------------------------------------------------
1932
- // Page-level SEO — extracted from registered SEO sections after resolution
1933
- // ---------------------------------------------------------------------------
1934
-
1935
- export interface PageSeo {
1936
- title?: string;
1937
- description?: string;
1938
- canonical?: string;
1939
- image?: string;
1940
- noIndexing?: boolean;
1941
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1942
- jsonLDs?: Record<string, any>[];
1943
- /** Open Graph type — "website" (default), "product", etc. */
1944
- type?: string;
1945
- }
1946
-
1947
- const seoSectionKeys: Set<string> = G.__deco.seoSections ?? (G.__deco.seoSections = new Set());
1948
-
1949
- /**
1950
- * Register section component keys whose resolved props contribute page-level
1951
- * SEO metadata (title, description, canonical, image, jsonLDs, noIndexing).
1952
- *
1953
- * After section loaders run, the framework scans these sections and extracts
1954
- * their SEO fields into `DecoPageResult.seo`, which `cmsRouteConfig` uses
1955
- * to generate `<head>` metadata (meta tags, OG, canonical, robots).
1956
- *
1957
- * JSON-LD structured data stays in the section props for the section
1958
- * component to render as `<script type="application/ld+json">`.
1959
- */
1960
- export function registerSeoSections(keys: string[]): void {
1961
- for (const k of keys) seoSectionKeys.add(k);
1962
- }
1963
-
1964
- /** Check if a section key is registered as an SEO section. */
1965
- export function isSeoSection(key: string): boolean {
1966
- return seoSectionKeys.has(key);
1967
- }
1968
-
1969
- /**
1970
- * Canonical URL from a schema.org BreadcrumbList — the `item` of its
1971
- * highest-position entry. Inlined from `@decocms/apps-commerce/utils/canonical`
1972
- * because `blocks` cannot depend on `apps-commerce` (apps-commerce depends on
1973
- * blocks, so the edge would be circular).
1974
- */
1975
- function canonicalFromBreadcrumb(breadcrumb: unknown): string | undefined {
1976
- const items = (
1977
- breadcrumb as { itemListElement?: { position: number; item: string }[] } | undefined
1978
- )?.itemListElement;
1979
- if (!Array.isArray(items) || items.length === 0) return undefined;
1980
- return items.reduce((acc, curr) => (acc.position < curr.position ? curr : acc)).item;
1981
- }
1982
-
1983
- /**
1984
- * Shallow-prune a PDP `jsonLD` before emitting it as structured data.
1985
- * Clones only when a prune option is set (the common path emits as-is), so a
1986
- * jsonLD shared with a body section is never mutated out from under it.
1987
- */
1988
- function pruneCommerceJsonLD(
1989
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1990
- jsonLD: Record<string, any>,
1991
- opts: { omitVariants: boolean },
1992
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1993
- ): Record<string, any> {
1994
- if (!opts.omitVariants || !jsonLD.product?.isVariantOf?.hasVariant) return jsonLD;
1995
- const clone = structuredClone(jsonLD);
1996
- clone.product.isVariantOf.hasVariant = [];
1997
- return clone;
1998
- }
1999
-
2000
- /**
2001
- * schema.org structured data for a listing page: an `ItemList` of
2002
- * position/url/name (what search engines read on category pages) plus the
2003
- * `BreadcrumbList`. Emitting the resolved ProductListingPage itself is not
2004
- * schema.org (no such type, no `@context`) and inlines every product with
2005
- * variants/specs/images — multiple MB per page, in the HTML *and* in the
2006
- * serialized route data, which pushes Workers past their memory limit.
2007
- */
2008
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2009
- function plpStructuredData(plp: Record<string, any>): Record<string, unknown>[] {
2010
- // Canonical product URL first: `url` is the SKU URL (`/p?skuId=N`), which
2011
- // canonicalises elsewhere. Items without a URL are dropped (Google requires
2012
- // `url` on summary-page items) before numbering, so positions stay contiguous.
2013
- const itemListElement = (plp.products as any[]) // eslint-disable-line @typescript-eslint/no-explicit-any
2014
- .map((p) => ({ url: p.isVariantOf?.url ?? p.url, name: p.isVariantOf?.name ?? p.name }))
2015
- .filter((item) => item.url)
2016
- .map((item, i) => ({ "@type": "ListItem", position: i + 1, ...item }));
2017
- const out: Record<string, unknown>[] = [
2018
- {
2019
- "@context": "https://schema.org",
2020
- "@type": "ItemList",
2021
- numberOfItems: itemListElement.length,
2022
- itemListElement,
2023
- },
2024
- ];
2025
- if (plp.breadcrumb?.itemListElement?.length) {
2026
- // Loaders emit path-only breadcrumb items (`/a/b`) for in-app links; in
2027
- // structured data make them absolute, using the products' origin.
2028
- const origin = originOf(itemListElement[0]?.url) ?? originOf(plp.seo?.canonical);
2029
- out.push({
2030
- ...plp.breadcrumb,
2031
- "@context": "https://schema.org",
2032
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2033
- itemListElement: plp.breadcrumb.itemListElement.map((el: any) =>
2034
- origin && typeof el.item === "string" && /^\/(?!\/)/.test(el.item)
2035
- ? { ...el, item: new URL(el.item, origin).href }
2036
- : el,
2037
- ),
2038
- });
2039
- }
2040
- return out;
2041
- }
2042
-
2043
- function originOf(url: unknown): string | undefined {
2044
- try {
2045
- return typeof url === "string" ? new URL(url).origin : undefined;
2046
- } catch {
2047
- return undefined;
2048
- }
2049
- }
2050
-
2051
- /**
2052
- * Derive SEO metadata from a commerce `jsonLD` data source (a resolved
2053
- * ProductListingPage / ProductDetailsPage), mirroring the deco-cx
2054
- * `commerce/sections/Seo/Seo{PLP,PDP}V2.tsx` section loaders.
2055
- *
2056
- * Those legacy sections have no component in @decocms/start (the commerce apps
2057
- * ship loaders/types, not sections), so nothing else runs this transform.
2058
- * Without it, PLP/PDP pages whose `page.seo` points at those types emit a
2059
- * <title>/canonical (from top-level override props) but NO schema.org
2060
- * structured data — the acme.com.br/eletroportateis regression.
2061
- *
2062
- * Manual override fields already read into `seo` always win; this only fills
2063
- * gaps and appends the JSON-LD. The caller guards on `seo.jsonLDs` so a real
2064
- * site SEO section that already computed structured data is never touched.
2065
- */
2066
- function deriveCommerceSeoFromJsonLD(
2067
- seo: PageSeo,
2068
- props: Record<string, unknown>,
2069
- isEager: boolean,
2070
- ): void {
2071
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2072
- const jsonLD = props.jsonLD as Record<string, any> | undefined;
2073
- if (!jsonLD) return;
2074
- const type = jsonLD["@type"];
2075
- if (type !== "ProductListingPage" && type !== "ProductDetailsPage") return;
2076
-
2077
- const jsonLDSeo = jsonLD.seo as
2078
- | { title?: string; description?: string; canonical?: string; noIndexing?: boolean }
2079
- | null
2080
- | undefined;
2081
-
2082
- if (!seo.title && jsonLDSeo?.title) seo.title = jsonLDSeo.title;
2083
- if (!seo.description && jsonLDSeo?.description) seo.description = jsonLDSeo.description;
2084
- if (!seo.canonical) {
2085
- seo.canonical =
2086
- jsonLDSeo?.canonical ||
2087
- canonicalFromBreadcrumb(
2088
- type === "ProductListingPage" ? jsonLD.breadcrumb : jsonLD.breadcrumbList,
2089
- );
2090
- }
2091
- if (type === "ProductDetailsPage" && !seo.image) {
2092
- seo.image = jsonLD.product?.image?.[0]?.url;
2093
- }
2094
-
2095
- const isEmpty =
2096
- type === "ProductListingPage"
2097
- ? !Array.isArray(jsonLD.products) || jsonLD.products.length === 0
2098
- : !jsonLD.product;
2099
- if (seo.noIndexing === undefined) {
2100
- seo.noIndexing = isEmpty || jsonLDSeo?.noIndexing || false;
2101
- }
2102
-
2103
- // Structured data — opt out via `ignoreStructuredData` (top-level on PDP,
2104
- // under `configJsonLD` on PLP). Bot-aware: the toggle suppresses JSON-LD for
2105
- // humans only; crawlers (and the `?__deco_ssr=1` audit override) still get it
2106
- // so indexing/rich results are unaffected. An empty page contributes no
2107
- // ItemList regardless.
2108
- const ignore = sectionIgnoresStructuredData(props);
2109
- if ((ignore && !isEager) || isEmpty) return;
2110
-
2111
- seo.jsonLDs =
2112
- type === "ProductListingPage"
2113
- ? plpStructuredData(jsonLD)
2114
- : [pruneCommerceJsonLD(jsonLD, { omitVariants: props.omitVariants === true })];
2115
- }
2116
-
2117
- /**
2118
- * Pick standard SEO fields from a props object.
2119
- * Works for both framework SEO types (SeoV2) and site SEO sections (SEOPDP).
2120
- */
2121
- export function extractSeoFromProps(
2122
- props: Record<string, unknown>,
2123
- opts?: { isEager?: boolean },
2124
- ): PageSeo {
2125
- const isEager = opts?.isEager ?? false;
2126
- const seo: PageSeo = {};
2127
- if (props.title) seo.title = props.title as string;
2128
- if (props.description) seo.description = props.description as string;
2129
- if (props.canonical) seo.canonical = props.canonical as string;
2130
- if (props.image) seo.image = props.image as string;
2131
- if (props.noIndexing !== undefined) seo.noIndexing = props.noIndexing as boolean;
2132
- if (props.type) seo.type = props.type as string;
2133
- if (Array.isArray(props.jsonLDs) && props.jsonLDs.length) {
2134
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2135
- seo.jsonLDs = props.jsonLDs as Record<string, any>[];
2136
- }
2137
- // Legacy commerce PLP/PDP sections carry a `jsonLD` data source with no
2138
- // component to turn it into structured data — derive it here (only when a
2139
- // real SEO section hasn't already emitted `jsonLDs`).
2140
- if (!seo.jsonLDs) deriveCommerceSeoFromJsonLD(seo, props, isEager);
2141
- return seo;
2142
- }
2143
-
2144
- /**
2145
- * Extract SEO metadata from resolved sections registered via
2146
- * `registerSeoSections`. Later sections override earlier ones
2147
- * (e.g., a PDP SEO section overrides a generic page SEO).
2148
- */
2149
- export function extractSeoFromSections(
2150
- sections: ResolvedSection[],
2151
- opts?: { isEager?: boolean },
2152
- ): PageSeo {
2153
- const seo: PageSeo = {};
2154
- for (const section of sections) {
2155
- if (!seoSectionKeys.has(section.component)) continue;
2156
- const extracted = extractSeoFromProps(section.props, opts);
2157
- if (extracted.jsonLDs) {
2158
- extracted.jsonLDs = [...(seo.jsonLDs ?? []), ...extracted.jsonLDs];
2159
- }
2160
- Object.assign(seo, extracted);
2161
- }
2162
- return seo;
2163
- }
2164
-
2165
- export interface DecoPageResult {
2166
- name: string;
2167
- path: string;
2168
- params: Record<string, string>;
2169
- /** CMS block key, e.g. "pages-Lista de cupons [APP]-397629" */
2170
- blockKey?: string;
2171
- resolvedSections: ResolvedSection[];
2172
- deferredSections: DeferredSection[];
2173
- /**
2174
- * Resolved SEO block from the page-level `seo` field in the CMS JSON.
2175
- * Contains the section component key and resolved props (with commerce
2176
- * loader data already fetched). Needs section loader enrichment in
2177
- * cmsRoute before SEO fields can be extracted.
2178
- */
2179
- seoSection?: ResolvedSection | null;
2180
- }
2181
-
2182
- export async function resolveDecoPage(
2183
- targetPath: string,
2184
- matcherCtx?: MatcherContext,
2185
- ): Promise<DecoPageResult | null> {
2186
- const startedAt = performance.now();
2187
- return withTracing(
2188
- "deco.cms.resolvePage",
2189
- async () => {
2190
- const result = await resolveDecoPageImpl(targetPath, matcherCtx);
2191
- try {
2192
- // No path label: resolve duration is a per-service latency signal, and
2193
- // the request path is unbounded cardinality (one histogram series per
2194
- // URL — product pages, search, facets) that made this the single
2195
- // biggest series in ClickHouse. Per-route latency lives on the span
2196
- // below (raw deco.route), which is sampled — the right place for it.
2197
- getMeter()?.histogramRecord?.(
2198
- MetricNames.RESOLVE_DURATION,
2199
- (performance.now() - startedAt) / 1000,
2200
- );
2201
- } catch {
2202
- /* observability never fails the request */
2203
- }
2204
- return result;
2205
- },
2206
- { "deco.route": targetPath },
2207
- );
2208
- }
2209
-
2210
- async function resolveDecoPageImpl(
2211
- targetPath: string,
2212
- matcherCtx?: MatcherContext,
2213
- ): Promise<DecoPageResult | null> {
2214
- ensureInitialized();
2215
-
2216
- const match = findPageByPath(targetPath);
2217
- if (!match) {
2218
- console.warn(`[CMS] No page found for path: ${targetPath}`);
2219
- return null;
2220
- }
2221
-
2222
- const { page, params, blockKey } = match;
2223
- const ctx: MatcherContext = { ...matcherCtx, path: targetPath };
2224
- const rctx: ResolveContext = { routeParams: params, matcherCtx: ctx, memo: new Map(), depth: 0 };
2225
-
2226
- let rawSections: unknown[];
2227
- if (Array.isArray(page.sections)) {
2228
- rawSections = page.sections;
2229
- } else {
2230
- // Resolve outer flag/wrapper to get the section array
2231
- // without recursively resolving each individual section.
2232
- const resolved = await resolveSectionsList(page.sections, rctx);
2233
- rawSections = resolved;
2234
- }
2235
-
2236
- const isBotReq = isEagerRequest(matcherCtx);
2237
- // Deferral applies identically to SSR documents and SPA navigations. A
2238
- // TanStack route loader is BLOCKING: the router does not commit the
2239
- // transition until the loader promise settles, so resolving every
2240
- // below-the-fold section eagerly on client nav freezes the previous page for
2241
- // as long as the slowest shelf/upstream takes (measured: 2.7s and a 3.4MB
2242
- // payload on a real PDP — worse than a full reload). Deferral's job is
2243
- // decoupling first paint from below-fold data, which matters MORE here, not
2244
- // less.
2245
- //
2246
- // #277 (deferred loaders missing per-request app context) is not a reason to
2247
- // disable deferral on client nav: the deferred second hop is the same
2248
- // `loadDeferredSection` server fn the SSR path has always used, and it runs
2249
- // server-side with matcherCtx rebuilt from the real request
2250
- // (url/path/cookies/request). It may well land in a DIFFERENT isolate — that
2251
- // is exactly why `reExtractRawProps` exists as the rawProps cache-miss path —
2252
- // but per-request state is reconstructed from the request either way, so a
2253
- // client nav is no more exposed than an SSR document already was. A section
2254
- // whose loader genuinely cannot be resolved on a second hop (e.g. a PDP/PLP
2255
- // gate that decides what renders at all) must not be marked ⚡ in the admin;
2256
- // see `shouldDeferSection`.
2257
- //
2258
- // `isClientNavigation` is still load-bearing for `derivePageUrl` (duplicate
2259
- // query params) and for `isProgrammaticFetch` (SPA `Sec-Fetch-Dest: empty`
2260
- // must not be mistaken for an AJAX call) — it just no longer gates deferral.
2261
- const currentAsyncConfig = getAsyncConfig();
2262
- const useAsync = currentAsyncConfig !== null && !isBotReq;
2263
-
2264
- const eagerResults: (ResolvedSection[] | Promise<ResolvedSection[]>)[] = [];
2265
- const deferredSections: DeferredSection[] = [];
2266
- let flatIndex = 0;
2267
-
2268
- for (const section of rawSections) {
2269
- const currentFlatIndex = flatIndex;
2270
-
2271
- const shouldDefer =
2272
- useAsync && shouldDeferSection(section, currentFlatIndex, currentAsyncConfig!, isBotReq, ctx);
2273
-
2274
- if (shouldDefer) {
2275
- let deferredOk = false;
2276
- try {
2277
- const deferred = resolveSectionShallow(section, ctx);
2278
- if (deferred) {
2279
- // Skip sections whose scheduling window has already closed (or
2280
- // hasn't opened yet). Without this check a LoadingFallback
2281
- // skeleton is rendered and immediately replaced by nothing once
2282
- // the component's own scheduling guard returns null — producing
2283
- // the "skeleton flashes then disappears" effect.
2284
- const sched = deferred.rawProps?.scheduling as
2285
- | { start?: string; end?: string }
2286
- | undefined;
2287
- if (sched) {
2288
- const now = Date.now();
2289
- if (sched.end && now > new Date(sched.end).getTime()) {
2290
- flatIndex++;
2291
- continue;
2292
- }
2293
- if (sched.start && now < new Date(sched.start).getTime()) {
2294
- flatIndex++;
2295
- continue;
2296
- }
2297
- }
2298
-
2299
- deferred.index = currentFlatIndex;
2300
-
2301
- // Cache rawProps server-side and strip from the deferred object
2302
- // so they are NOT serialized into the HTML payload.
2303
- if (deferred.rawProps) {
2304
- cacheDeferredRawProps(
2305
- targetPath,
2306
- deferred.component,
2307
- currentFlatIndex,
2308
- deferred.rawProps,
2309
- );
2310
- delete deferred.rawProps;
2311
- }
2312
-
2313
- deferredSections.push(deferred);
2314
- deferredOk = true;
2315
- }
2316
- } catch (e) {
2317
- onResolveError(e, "section", "Deferred section resolution");
2318
- }
2319
-
2320
- if (!deferredOk) {
2321
- // Shallow resolution failed — fall back to eager resolution
2322
- const idx = currentFlatIndex;
2323
- eagerResults.push(
2324
- // Clone the wrappers before stamping `index` — layout sections may
2325
- // be backed by the shared resolved-layout cache, and mutating
2326
- // `s.index` in place would corrupt that shared object across
2327
- // concurrent requests (causing sections to sort into the wrong
2328
- // position, e.g. the footer jumping above other sections).
2329
- resolveRawSection(section, rctx).then((sections) =>
2330
- sections.map((s) => ({ ...s, index: idx })),
2331
- ),
2332
- );
2333
- }
2334
- flatIndex++;
2335
- } else {
2336
- // Eager: full resolution (existing logic)
2337
- const promise = (async (): Promise<ResolvedSection[]> => {
2338
- try {
2339
- const layoutKey = isRawSectionLayout(section);
2340
-
2341
- if (layoutKey) {
2342
- const cacheKey = resolvedLayoutCache.key(layoutCacheKey(layoutKey, rctx.matcherCtx));
2343
- const cached = await getCachedResolvedLayout(cacheKey);
2344
- if (cached) return cached;
2345
-
2346
- const inflight = resolvedLayoutInflight.get(cacheKey);
2347
- if (inflight) return inflight;
2348
-
2349
- const p = withInflightTimeout(
2350
- resolveRawSection(section, rctx).then((results) => {
2351
- setCachedResolvedLayout(cacheKey, results);
2352
- return results;
2353
- }),
2354
- `resolvedLayout ${cacheKey}`,
2355
- ).finally(() => resolvedLayoutInflight.delete(cacheKey));
2356
- resolvedLayoutInflight.set(cacheKey, p);
2357
- return p;
2358
- }
2359
-
2360
- return resolveRawSection(section, rctx);
2361
- } catch (e) {
2362
- onResolveError(e, "section", "Section resolution");
2363
- return [];
2364
- }
2365
- })();
2366
-
2367
- const idx = currentFlatIndex;
2368
- eagerResults.push(
2369
- // Clone the wrappers before stamping `index`. `promise` may resolve to
2370
- // the shared resolved-layout cache array (line ~1491 `return cached`)
2371
- // or the shared in-flight array; mutating `s.index` in place would
2372
- // corrupt that shared object across concurrent requests, scrambling
2373
- // section order (e.g. the footer swapping position with top sections).
2374
- promise.then((sections) => sections.map((s) => ({ ...s, index: idx }))),
2375
- );
2376
- flatIndex++;
2377
- }
2378
- }
2379
-
2380
- const allResults = await Promise.all(eagerResults);
2381
-
2382
- // Resolve page-level SEO block (page.seo field) — always eager.
2383
- // Runs after sections to benefit from memoized commerce loader results.
2384
- let seoSection: ResolvedSection | null = null;
2385
- if (page.seo) {
2386
- try {
2387
- seoSection = await resolvePageSeoBlock(page.seo as Record<string, unknown>, rctx);
2388
- } catch (e) {
2389
- onResolveError(e, "page.seo", "Page SEO block resolution");
2390
- }
2391
- }
2392
-
2393
- return {
2394
- name: page.name,
2395
- path: page.path || targetPath,
2396
- params,
2397
- blockKey,
2398
- resolvedSections: allResults.flat(),
2399
- deferredSections,
2400
- seoSection,
2401
- };
2402
- }
2403
-
2404
- /**
2405
- * Resolve a raw sections array into ResolvedSection[] with the same
2406
- * optimizations as resolveDecoPage: parallel resolution, layout caching,
2407
- * in-flight dedup, and memoization.
2408
- *
2409
- * Unlike resolveDecoPage, this does NOT look up a page by path — the
2410
- * caller provides the raw section array directly. Used by the admin
2411
- * preview renderer where page data comes from the POST body.
2412
- *
2413
- * All sections are resolved eagerly (no deferred/async split) since
2414
- * admin previews need the full rendered output.
2415
- */
2416
- export async function resolvePageSections(
2417
- rawSectionsInput: unknown,
2418
- matcherCtx?: MatcherContext,
2419
- ): Promise<ResolvedSection[]> {
2420
- ensureInitialized();
2421
-
2422
- const ctx: MatcherContext = matcherCtx ?? {};
2423
- const rctx: ResolveContext = { matcherCtx: ctx, memo: new Map(), depth: 0 };
2424
-
2425
- let rawSections: unknown[];
2426
- if (Array.isArray(rawSectionsInput)) {
2427
- rawSections = rawSectionsInput;
2428
- } else {
2429
- rawSections = await resolveSectionsList(rawSectionsInput, rctx);
2430
- }
2431
-
2432
- const eagerResults: Promise<ResolvedSection[]>[] = [];
2433
-
2434
- for (const section of rawSections) {
2435
- const promise = (async (): Promise<ResolvedSection[]> => {
2436
- try {
2437
- const layoutKey = isRawSectionLayout(section);
2438
-
2439
- if (layoutKey) {
2440
- const cacheKey = resolvedLayoutCache.key(layoutCacheKey(layoutKey, rctx.matcherCtx));
2441
- const cached = await getCachedResolvedLayout(cacheKey);
2442
- if (cached) return cached;
2443
-
2444
- const inflight = resolvedLayoutInflight.get(cacheKey);
2445
- if (inflight) return inflight;
2446
-
2447
- const p = withInflightTimeout(
2448
- resolveRawSection(section, rctx).then((results) => {
2449
- setCachedResolvedLayout(cacheKey, results);
2450
- return results;
2451
- }),
2452
- `resolvedLayout ${cacheKey}`,
2453
- ).finally(() => resolvedLayoutInflight.delete(cacheKey));
2454
- resolvedLayoutInflight.set(cacheKey, p);
2455
- return p;
2456
- }
2457
-
2458
- return resolveRawSection(section, rctx);
2459
- } catch (e) {
2460
- onResolveError(e, "section", "Preview section resolution");
2461
- return [];
2462
- }
2463
- })();
2464
-
2465
- eagerResults.push(promise);
2466
- }
2467
-
2468
- const allResults = await Promise.all(eagerResults);
2469
- return allResults.flat();
2470
- }
2471
-
2472
- /**
2473
- * Resolve a single deferred section's raw props into a fully resolved section.
2474
- * Called by the loadDeferredSection server function when a section scrolls into view.
2475
- *
2476
- * This runs the full resolution pipeline on the raw CMS props:
2477
- * - Resolves nested __resolveType references (commerce loaders, block refs, flags)
2478
- * - Normalizes nested sections to { Component, props } shape
2479
- *
2480
- * After this, the section goes through runSingleSectionLoader for final enrichment.
2481
- */
2482
- export async function resolveDeferredSection(
2483
- component: string,
2484
- rawProps: Record<string, unknown>,
2485
- pagePath: string,
2486
- matcherCtx?: MatcherContext,
2487
- ): Promise<ResolvedSection | null> {
2488
- ensureInitialized();
2489
-
2490
- const ctx: MatcherContext = { ...matcherCtx, path: pagePath };
2491
- // Recover routeParams from the page match so nested `requestToParam`
2492
- // resolvers (e.g. `:slug` on PDPs) return the right value.
2493
- const match = findPageByPath(pagePath);
2494
- const rctx: ResolveContext = {
2495
- routeParams: match?.params,
2496
- matcherCtx: ctx,
2497
- memo: new Map(),
2498
- depth: 0,
2499
- };
2500
-
2501
- // onBeforeResolveProps: let sections transform raw props before resolution.
2502
- const propsToResolve = await applyOnBeforeResolveProps(component, rawProps);
2503
-
2504
- const resolvedProps = await resolveProps(propsToResolve, rctx);
2505
- const normalizedProps = normalizeNestedSections(resolvedProps) as Record<string, unknown>;
2506
-
2507
- return {
2508
- component,
2509
- props: normalizedProps,
2510
- key: component,
2511
- };
2512
- }
2513
-
2514
- /**
2515
- * Resolve AND enrich a deferred section in one call.
2516
- * Combines CMS prop resolution (resolveDeferredSection) with section loader
2517
- * enrichment (runSingleSectionLoader) and URL normalization.
2518
- *
2519
- * Used by the route loader to create streaming promises for TanStack's
2520
- * native deferred data pattern — each deferred section becomes an unawaited
2521
- * promise that TanStack streams via SSR.
2522
- */
2523
- export async function resolveDeferredSectionFull(
2524
- ds: DeferredSection,
2525
- pagePath: string,
2526
- request: Request,
2527
- matcherCtx?: MatcherContext,
2528
- ): Promise<ResolvedSection | null> {
2529
- // rawProps may be stripped from the client payload — resolve from cache or page
2530
- const rawProps =
2531
- ds.rawProps ??
2532
- (await readDeferredRawProps(pagePath, ds.component, ds.index)) ??
2533
- (await reExtractRawProps(pagePath, ds.component, ds.index, matcherCtx));
2534
-
2535
- if (!rawProps) return null;
2536
-
2537
- const section = await resolveDeferredSection(ds.component, rawProps, pagePath, matcherCtx);
2538
- if (!section) return null;
2539
- section.index = ds.index;
2540
- const enriched = await runSingleSectionLoader(section, request);
2541
- return normalizeUrlsInObject(enriched);
2542
- }
2543
-
2544
- /**
2545
- * Fallback for deferred rawProps cache miss: re-resolve the page and extract
2546
- * rawProps for the section at the given index. Expensive but ensures correctness
2547
- * when the in-memory cache has been evicted (different isolate, TTL expired).
2548
- */
2549
- export async function reExtractRawProps(
2550
- pagePath: string,
2551
- component: string,
2552
- sectionIndex: number,
2553
- matcherCtx?: MatcherContext,
2554
- ): Promise<Record<string, unknown> | null> {
2555
- ensureInitialized();
2556
-
2557
- const match = findPageByPath(pagePath);
2558
- if (!match) return null;
2559
-
2560
- const { page } = match;
2561
- const ctx: MatcherContext = { ...matcherCtx, path: pagePath };
2562
-
2563
- let rawSections: unknown[];
2564
- if (Array.isArray(page.sections)) {
2565
- rawSections = page.sections;
2566
- } else {
2567
- const rctx: ResolveContext = { matcherCtx: ctx, memo: new Map(), depth: 0 };
2568
- rawSections = await resolveSectionsList(page.sections, rctx);
2569
- }
2570
-
2571
- if (sectionIndex < 0 || sectionIndex >= rawSections.length) return null;
2572
-
2573
- const section = rawSections[sectionIndex];
2574
- const shallow = resolveSectionShallow(section, ctx);
2575
- if (!shallow || shallow.component !== component) return null;
2576
-
2577
- // Cache for subsequent requests
2578
- if (shallow.rawProps) {
2579
- cacheDeferredRawProps(pagePath, component, sectionIndex, shallow.rawProps);
2580
- }
2581
-
2582
- return shallow.rawProps ?? null;
2583
- }