@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
package/src/sdk/otel.ts DELETED
@@ -1,1118 +0,0 @@
1
- /**
2
- * Single observability entry point for `@decocms/start` on Cloudflare Workers.
3
- *
4
- * `instrumentWorker(handler, options)` wraps a Worker handler with:
5
- * - structured JSON logger (stdout → Cloudflare Workers Logs) — always
6
- * - Workers Analytics Engine metrics — when `env.DECO_METRICS` binding exists
7
- * - OTLP/HTTP metrics exporter, direct POST to `deco-otel-ingest`
8
- * `/v1/metrics` — when `env.DECO_OTEL_METRICS_ENDPOINT` is set. Buffered
9
- * per-isolate, flushed via `ctx.waitUntil` at the end of every request.
10
- * See `otelHttpMeter.ts` for the aggregation + flush model.
11
- * - OTLP/HTTP error-log channel, direct POST to `deco-otel-ingest`
12
- * `/v1/logs` — when `env.DECO_OTEL_LOGS_ENDPOINT` is set. Carries
13
- * `logger.error(...)` calls at 100% capture (rate-limited per
14
- * isolate) so head-sampled CF Destinations don't drop them.
15
- * See `otelHttpLog.ts` for the rate limiter + flush model.
16
- * - Bridges framework-internal `withTracing()` calls onto the global
17
- * `@opentelemetry/api` tracer, stamping `deco.*` attributes on every span
18
- * so they survive Cloudflare's platform-managed trace export
19
- *
20
- * **Transport split.** Logs (info/warn) and traces flow through Cloudflare
21
- * Destinations (configured in `wrangler.jsonc`
22
- * `observability.{logs,traces}.destinations`). Metrics are NOT supported
23
- * by Destinations today (CF only exports OTLP for logs and traces), so the
24
- * framework POSTs them directly. Errors travel BOTH paths — via
25
- * `console.error` (sampled by CF Destinations) and direct POST (100%
26
- * capture). Same OTLP/HTTP JSON wire format, same ingest Worker.
27
- *
28
- * Required `wrangler.jsonc` block (run `scripts/migrate-to-cf-observability.ts`
29
- * to inject this automatically). Sampling defaults follow the fleet-scale cost
30
- * model documented in `docs/observability.md`:
31
- * ```jsonc
32
- * "observability": {
33
- * "enabled": true,
34
- * "logs": { "enabled": true, "invocation_logs": true,
35
- * "head_sampling_rate": 1, "persist": true },
36
- * "traces": { "enabled": true,
37
- * "head_sampling_rate": 0.01, "persist": true }
38
- * },
39
- * "version_metadata": { "binding": "CF_VERSION_METADATA" },
40
- * "analytics_engine_datasets": [{ "binding": "DECO_METRICS",
41
- * "dataset": "deco_metrics_my_site" }]
42
- * ```
43
- *
44
- * @example
45
- * ```ts
46
- * // worker-entry.ts
47
- * import { createDecoWorkerEntry } from "@decocms/start/sdk/workerEntry";
48
- * import { instrumentWorker } from "@decocms/start/sdk/otel";
49
- *
50
- * const handler = createDecoWorkerEntry(serverEntry, options);
51
- * export default instrumentWorker(handler, { serviceName: "my-store" });
52
- * ```
53
- *
54
- * **Future ClickHouse path.** When a co-deployed OTel collector lands, an
55
- * exporter that pushes spans + logs + metrics to that collector will live in
56
- * `./otelAdapters/clickhouseCollector.ts` (today: documented stub that throws).
57
- * The `withTracing` / `recordRequestMetric` / `logger` instrumentation surface
58
- * does not change — only the transport layer wires up.
59
- */
60
-
61
- import { SpanStatusCode, trace } from "@opentelemetry/api";
62
- // OTel community SemConv constants — official attribute names from the OTel
63
- // specification. Importing from the package (rather than typing strings)
64
- // guards against typos, surfaces deprecations via TypeScript, and tracks
65
- // upstream spec changes via the dep version.
66
- // https://opentelemetry.io/docs/specs/semconv/resource/
67
- // https://www.npmjs.com/package/@opentelemetry/semantic-conventions
68
- //
69
- // Stable attributes (graduated in upstream SemConv) come from the default
70
- // entry point. Incubating attributes (still experimental upstream) come from
71
- // the `/incubating` subpath — using them is a deliberate trade-off: stable
72
- // attribute names + a stability disclaimer documented in the conventions
73
- // guide (see context/04_engineering/o11y/02-conventions.md §4.2).
74
- import {
75
- ATTR_DEPLOYMENT_ENVIRONMENT_NAME,
76
- ATTR_SERVICE_INSTANCE_ID,
77
- ATTR_SERVICE_NAME,
78
- ATTR_SERVICE_VERSION,
79
- } from "@opentelemetry/semantic-conventions";
80
- import {
81
- ATTR_CLOUD_PLATFORM,
82
- ATTR_CLOUD_PROVIDER,
83
- } from "@opentelemetry/semantic-conventions/incubating";
84
- import { createCompositeLogger, createCompositeMeter } from "./composite";
85
- import { isDevMode } from "./env";
86
- import { configureLogger, defaultLoggerAdapter, logger, setLogLevel, setLoggerAttributeFloor, type LogLevel } from "./logger";
87
- import { configureMeter, configureTracer, getActiveSpan, METRIC_METADATA } from "../middleware/observability";
88
- import { createAnalyticsEngineMeterAdapter } from "./otelAdapters";
89
- import { createOtlpHttpLogAdapter, type OtlpHttpLog } from "./otelHttpLog";
90
- import { createOtlpHttpMeterAdapter, type OtlpHttpMeter } from "./otelHttpMeter";
91
- import {
92
- createOtlpHttpTracerAdapter,
93
- type OtlpHttpTracer,
94
- type TraceContext,
95
- } from "./otelHttpTracer";
96
- import { RequestContext } from "./requestContext";
97
-
98
- // ---------------------------------------------------------------------------
99
- // Types
100
- // ---------------------------------------------------------------------------
101
-
102
- export interface OtelOptions {
103
- /**
104
- * When `true`, skips all observability exporters (AE, OTLP metrics,
105
- * logs, traces). Overridden by the env var.
106
- */
107
- disabled?: boolean;
108
- /**
109
- * Env var name holding the tri-state observability switch. Values:
110
- * - `"on"` → force enable (even in local dev)
111
- * - `"off"` → force disable
112
- * - unset → auto: enabled in real deploys, disabled in local
113
- *
114
- * Local is detected via `isDevMode()` (reads
115
- * `process.env.NODE_ENV === "development"`, which Vite and
116
- * `@cloudflare/vite-plugin` set during `vite dev`).
117
- *
118
- * Defaults to `"DECO_OTEL"`.
119
- */
120
- envVar?: string;
121
- /** Logical service name. Falls back to `env.DECO_SITE_NAME`, then "deco-site". */
122
- serviceName?: string;
123
- /** Env var name holding the AE binding. Defaults to `"DECO_METRICS"`. */
124
- analyticsEngineBindingName?: string;
125
- /** Set to `false` to disable AE even when the binding is present. */
126
- analyticsEngineEnabled?: boolean;
127
- /**
128
- * Env var name holding the OTLP/HTTP metrics endpoint. Defaults to
129
- * `"DECO_OTEL_METRICS_ENDPOINT"`. When the env var is set (and
130
- * `otlpMetricsEnabled !== false`), `instrumentWorker` wires a direct-POST
131
- * metrics exporter and flushes the buffer via `ctx.waitUntil` at the
132
- * end of every request. Cooldown + buffer cap are controlled by
133
- * `OtlpHttpMeterOptions`.
134
- */
135
- otlpMetricsEndpointEnvVar?: string;
136
- /** Set to `false` to disable the OTLP/HTTP metrics exporter explicitly. */
137
- otlpMetricsEnabled?: boolean;
138
- /**
139
- * Env var name holding the OTLP/HTTP logs endpoint — the primary log
140
- * transport. Defaults to `"DECO_OTEL_LOGS_ENDPOINT"`. When set (and
141
- * `otlpLogsEnabled !== false`), `instrumentWorker` patches `console.*`
142
- * at boot so all application and third-party log calls route through
143
- * the framework logger → direct-POST to this endpoint.
144
- */
145
- otlpLogsEndpointEnvVar?: string;
146
- /** Set to `false` to disable the OTLP/HTTP logs exporter explicitly. */
147
- otlpLogsEnabled?: boolean;
148
- /**
149
- * Minimum log level forwarded via direct-POST. Defaults to `"info"` per
150
- * the OpenTelemetry specification. Set to `"warn"` to forward only errors
151
- * and warnings, or `"debug"` to capture everything (can be high volume).
152
- *
153
- * Precedence: env var (`otlpLogsMinLevelEnvVar`, default
154
- * `DECO_OTEL_LOGS_MIN_LEVEL`) > this option > `"info"`. Invalid env
155
- * values fall through silently.
156
- */
157
- otlpLogsMinLevel?: LogLevel;
158
- /**
159
- * Env var name to read the minimum log level from. Defaults to
160
- * `"DECO_OTEL_LOGS_MIN_LEVEL"`. Value MUST be one of
161
- * `"debug"`, `"info"`, `"warn"`, `"error"`.
162
- */
163
- otlpLogsMinLevelEnvVar?: string;
164
- /**
165
- * Extra HTTP headers sent on every OTLP POST (logs, traces, metrics).
166
- * Merged with the adapter default (`Content-Type: application/json`).
167
- *
168
- * Resolved from `DECO_OTEL_HEADERS` env var (format: `key=value,key2=value2`)
169
- * when not set programmatically. Useful for collector auth:
170
- *
171
- * ```
172
- * DECO_OTEL_HEADERS=Authorization=Bearer <token>
173
- * ```
174
- */
175
- otlpHeaders?: Record<string, string>;
176
- /**
177
- * Env var name to read extra OTLP headers from. Defaults to `"DECO_OTEL_HEADERS"`.
178
- * Format: `key=value,key2=value2`.
179
- */
180
- otlpHeadersEnvVar?: string;
181
- /**
182
- * Authorization header value sent on every OTLP POST.
183
- * Equivalent to `otlpHeaders: { authorization: "<value>" }` but intended
184
- * for secrets: store via `wrangler secret put DECO_OTEL_AUTH_TOKEN` so the
185
- * token is never committed to the repo. Non-secret headers go in
186
- * `DECO_OTEL_HEADERS` (plaintext in `wrangler.jsonc`).
187
- *
188
- * Example: `DECO_OTEL_AUTH_TOKEN=Bearer eyJhbGci...`
189
- *
190
- * Precedence (lowest → highest): auth token env var → `DECO_OTEL_HEADERS`
191
- * env var → `otlpHeaders` option. An explicit `authorization` key in
192
- * `DECO_OTEL_HEADERS` or `otlpHeaders` overrides this value.
193
- */
194
- otlpAuthToken?: string;
195
- /**
196
- * Env var name to read the auth token from. Defaults to `"DECO_OTEL_AUTH_TOKEN"`.
197
- */
198
- otlpAuthTokenEnvVar?: string;
199
- /**
200
- * Env var name holding the OTLP/HTTP traces endpoint used by the
201
- * direct-POST span exporter. Defaults to `"DECO_OTEL_TRACES_ENDPOINT"`.
202
- * When set (and `otlpTracesEnabled !== false`), framework `deco.*`
203
- * spans created via `withTracing` are captured, sampled, and POSTed
204
- * directly to this endpoint. Flushed alongside metrics via
205
- * `ctx.waitUntil`.
206
- *
207
- * Without this endpoint configured, `withTracing` falls back to the
208
- * `@opentelemetry/api` global tracer (the legacy CF auto-instrumentation
209
- * path). The framework registers BOTH adapters when a traces endpoint
210
- * is set so CF auto-spans stay intact AND framework spans get
211
- * direct-POSTed to ClickHouse. See Phase 3 in
212
- * `MIGRATION_TOOLING_PLAN.md`.
213
- */
214
- otlpTracesEndpointEnvVar?: string;
215
- /** Set to `false` to disable the OTLP/HTTP traces exporter explicitly. */
216
- otlpTracesEnabled?: boolean;
217
- /**
218
- * Head sampling rate for framework spans direct-POSTed via the OTLP
219
- * traces endpoint. Default `0.01` matches the CF Destinations
220
- * `traces.head_sampling_rate` recommendation. Decisions are consistent
221
- * per trace (hash of `trace_id`), so child spans (`deco.cache.lookup`,
222
- * `deco.cms.resolvePage`, ...) are kept iff their root
223
- * `deco.http.request` span is kept. Set to `1` to capture every trace
224
- * (preview / debug only — production cost grows linearly).
225
- *
226
- * Precedence: env var (`otlpTracesSamplingRateEnvVar`, default
227
- * `DECO_OTEL_TRACES_SAMPLING_RATE`) > this option > `0.01`. Reading from
228
- * env lets local-dev opt into 100% sampling via `.dev.vars` without
229
- * changing the worker entry.
230
- */
231
- otlpTracesSamplingRate?: number;
232
- /**
233
- * Env var name to read the head sampling rate from when set on `env`.
234
- * Defaults to `DECO_OTEL_TRACES_SAMPLING_RATE`. Value MUST be a finite
235
- * number in `[0, 1]`. Invalid values are ignored (falls back to
236
- * `otlpTracesSamplingRate` then `0.01`).
237
- */
238
- otlpTracesSamplingRateEnvVar?: string;
239
- /**
240
- * When `true` (or when `DECO_OTEL_ERROR_PROMOTION=true` is set), any
241
- * `logger.error()` call with an active trace context marks that trace for
242
- * export even if head sampling did not select it. Useful for ensuring
243
- * errors always have a trace in ClickHouse without raising the global
244
- * sampling rate.
245
- *
246
- * Disabled by default — enable via env var or this option once validated
247
- * in production. Precedence: env var (`otlpTracesErrorPromotionEnvVar`,
248
- * default `DECO_OTEL_ERROR_PROMOTION`) > this option > `false`.
249
- */
250
- otlpTracesErrorPromotion?: boolean;
251
- /**
252
- * Env var name to read the error promotion flag from. Defaults to
253
- * `"DECO_OTEL_ERROR_PROMOTION"`. Value must be `"true"` to enable.
254
- */
255
- otlpTracesErrorPromotionEnvVar?: string;
256
- /**
257
- * Sampling rate applied to error-promoted traces, 0.0..1.0. Default `0.1`
258
- * (promote 10% of error traces). Lower values cap ClickHouse volume when
259
- * errors are frequent. Uses the same FNV-1a hash as head sampling.
260
- *
261
- * Precedence: env var (`otlpTracesErrorPromotionRateEnvVar`, default
262
- * `DECO_OTEL_ERROR_PROMOTION_RATE`) > this option > `0.1`.
263
- */
264
- otlpTracesErrorPromotionRate?: number;
265
- /**
266
- * Env var name to read the error promotion rate from. Defaults to
267
- * `"DECO_OTEL_ERROR_PROMOTION_RATE"`. Value must be a finite number in
268
- * `[0, 1]`. Invalid values are ignored.
269
- */
270
- otlpTracesErrorPromotionRateEnvVar?: string;
271
- /** Test seam — replace the global `fetch` used by the traces exporter. */
272
- otlpTracesFetchImpl?: typeof fetch;
273
- /**
274
- * Version of `@decocms/start` to advertise as `deco.runtime.version`
275
- * on every span and every log line. Falls back to a build-time constant;
276
- * override only for tests.
277
- */
278
- decoRuntimeVersion?: string;
279
- /** Optional `@decocms/apps` version, stamped as `deco.apps.version`. */
280
- decoAppsVersion?: string;
281
- /**
282
- * Test seam — replace the global `fetch` used by the OTLP metrics
283
- * exporter without touching the worker's outbound fetch.
284
- */
285
- otlpMetricsFetchImpl?: typeof fetch;
286
- /** Test seam — replace the global `fetch` used by the logs exporter. */
287
- otlpLogsFetchImpl?: typeof fetch;
288
- }
289
-
290
- interface WorkerExecutionContext {
291
- waitUntil(promise: Promise<unknown>): void;
292
- passThroughOnException(): void;
293
- }
294
-
295
- interface WorkerHandler {
296
- fetch(
297
- request: Request,
298
- env: Record<string, unknown>,
299
- ctx: WorkerExecutionContext,
300
- ): Promise<Response>;
301
- }
302
-
303
- // ---------------------------------------------------------------------------
304
- // Boot state — pinned to globalThis via Symbol.for so multiple bundled
305
- // copies of this module converge on the SAME state.
306
- //
307
- // Why: Vite (and any bundler chunking by entry) can produce more than one
308
- // inlined copy of this file when multiple package entries — e.g.
309
- // `@decocms/start/sdk/otel` and `@decocms/start/sdk/workerEntry` — both
310
- // pull it transitively. With plain module-scoped `let` variables, the
311
- // auto-wrap path inside `createDecoWorkerEntry` ends up writing the meter
312
- // into Copy A's `otlpMeter` while the per-request `recordRequestMetric`
313
- // closure reads from Copy B's empty `otlpMeter`. Net effect in prod:
314
- // `bootObservability` runs (we observed the very first `POST /v1/metrics`
315
- // from a production storefront), but every subsequent request's `flush()` finds an
316
- // empty buffer because the meter the framework writes into is a different
317
- // instance from the one the exporter drains.
318
- //
319
- // `observability.ts` already uses this pattern (see the `STATE_KEY` block
320
- // there); the comment there flags this exact failure mode. The reason it
321
- // took so long to surface here is that until PR #232 added the auto-wrap
322
- // inside `createDecoWorkerEntry`, sites always called `instrumentWorker`
323
- // once from their own `worker-entry.ts` — a single bundle entry — so
324
- // nobody hit the duplication path.
325
- //
326
- // CF Workers guarantee one `globalThis` per isolate, so there's no risk
327
- // of cross-isolate bleed. Symbol.for keeps the registry stable across
328
- // hot reloads in `wrangler dev` too.
329
- // ---------------------------------------------------------------------------
330
-
331
- type OrigConsole = Pick<typeof console, "log" | "info" | "warn" | "error" | "debug">;
332
-
333
- interface BootState {
334
- booted: boolean;
335
- otlpMeter: OtlpHttpMeter | null;
336
- otlpLog: OtlpHttpLog | null;
337
- otlpTracer: OtlpHttpTracer | null;
338
- spanAttributeFloor: Record<string, string>;
339
- origConsole: OrigConsole | null;
340
- }
341
-
342
- const BOOT_STATE_KEY = Symbol.for("@decocms/start/sdk/otel/boot.v1");
343
-
344
- function getBootState(): BootState {
345
- const g = globalThis as Record<symbol, unknown>;
346
- if (!g[BOOT_STATE_KEY]) {
347
- g[BOOT_STATE_KEY] = {
348
- booted: false,
349
- otlpMeter: null,
350
- otlpLog: null,
351
- otlpTracer: null,
352
- spanAttributeFloor: {},
353
- origConsole: null,
354
- } satisfies BootState;
355
- }
356
- return g[BOOT_STATE_KEY] as BootState;
357
- }
358
-
359
- /**
360
- * Per-request inbound W3C trace context, parsed from the `traceparent`
361
- * header at request entry. Read by the OTLP trace exporter when it
362
- * creates a root span so we honor remote parents and the `sampled`
363
- * flag. Stored on a request-scoped slot (via `RequestContext.bag`) so
364
- * concurrent requests in the same isolate don't trample each other.
365
- */
366
- const TRACE_CTX_BAG_KEY = "deco.observability.traceContext.v1";
367
- const DEBUG_SAMPLED_BAG_KEY = "deco.observability.debugSampled.v1";
368
-
369
- function getRequestTraceContext(): TraceContext | null {
370
- return RequestContext.getBag<TraceContext>(TRACE_CTX_BAG_KEY) ?? null;
371
- }
372
-
373
- function getDebugSampled(): boolean {
374
- return RequestContext.getBag<boolean>(DEBUG_SAMPLED_BAG_KEY) ?? false;
375
- }
376
-
377
- /**
378
- * Public entry point used by `workerEntry.ts` to stash the parsed
379
- * traceparent for the OTLP tracer to consume. Exported (not just
380
- * module-local) because the parser lives in `otelHttpTracer.ts` and
381
- * the call site is `workerEntry.ts`.
382
- */
383
- export function _setRequestTraceContext(ctx: TraceContext | null): void {
384
- if (ctx) RequestContext.setBag(TRACE_CTX_BAG_KEY, ctx);
385
- }
386
-
387
- /**
388
- * Called by `workerEntry.ts` when the inbound URL contains `?__d=<any>`.
389
- * Forces trace sampling for the current request regardless of `headSamplingRate`.
390
- * Useful for debugging individual requests in production without changing
391
- * the global sampling rate.
392
- */
393
- export function _setDebugSampled(): void {
394
- RequestContext.setBag(DEBUG_SAMPLED_BAG_KEY, true);
395
- }
396
-
397
- /**
398
- * Per-span attribute floor — stamped on every span we create via
399
- * `configureTracer().startSpan(...)`. Lives on the shared `BootState`
400
- * (see above) so framework code paths that read it through different
401
- * bundled copies of this module all see the floor `bootObservability`
402
- * just installed.
403
- */
404
-
405
- // ---------------------------------------------------------------------------
406
- // instrumentWorker
407
- // ---------------------------------------------------------------------------
408
-
409
- /**
410
- * Wraps a Cloudflare Worker handler with the @decocms/start observability
411
- * stack:
412
- * - structured JSON logger to console.* (CF captures via observability.logs)
413
- * - AE meter (when `DECO_METRICS` binding present)
414
- * - bridge from framework-internal `withTracing()` to `@opentelemetry/api`
415
- * global tracer (CF observability.traces ingests via auto-instrumentation
416
- * + the global-tracer hook)
417
- *
418
- * No external destinations, no OTLP transport. Forwarding to a future
419
- * OTel collector for ClickHouse will live behind a separate adapter
420
- * (see `./otelAdapters/clickhouseCollector.ts`).
421
- */
422
- export function instrumentWorker(
423
- handler: WorkerHandler,
424
- options: OtelOptions | ((env: Record<string, unknown>) => OtelOptions) = {},
425
- ): WorkerHandler {
426
- // Default tracer bridge — delegates to `@opentelemetry/api` global. When
427
- // `bootObservability` discovers `DECO_OTEL_TRACES_ENDPOINT`, it composes
428
- // this bridge with the direct-POST OTLP tracer so framework spans flow to
429
- // BOTH the CF dashboard AND ClickHouse (the bridge stays a no-op when CF
430
- // tracing isn't configured, which is the common case today). See
431
- // `configureTracerStack` below.
432
- configureTracer(buildOtelApiTracer());
433
-
434
- return {
435
- async fetch(request, env, ctx) {
436
- const opts =
437
- typeof options === "function" ? options(env as Record<string, unknown>) : options;
438
- bootObservability(opts, env as Record<string, unknown>);
439
- // RequestContext.run + setRuntimeEnv(env) is handled inside
440
- // workerEntry.ts on the inner handler — instrumentWorker does
441
- // NOT re-wrap so we don't double-enter AsyncLocalStorage.
442
- try {
443
- return await handler.fetch(request, env, ctx);
444
- } finally {
445
- // Drain the OTLP metrics + error-log + traces buffers via
446
- // ctx.waitUntil so no POST blocks the response. Each exporter
447
- // throttles itself per isolate — calling on every request is
448
- // cheap; the network only fires when the cooldown elapses or
449
- // the buffer fills. Skip the waitUntil call entirely when no
450
- // adapter is configured (nothing to flush).
451
- const state = getBootState();
452
- if (state.otlpMeter || state.otlpLog || state.otlpTracer) {
453
- try {
454
- ctx.waitUntil(flushObservability());
455
- } catch {
456
- /* ctx.waitUntil throwing is benign — never block the response */
457
- }
458
- }
459
- }
460
- },
461
- };
462
- }
463
-
464
- /**
465
- * Drains the OTLP metrics + error-log + traces buffers (whichever are
466
- * configured for this isolate). Extracted out of `instrumentWorker`'s
467
- * `finally` block so callers without a `{fetch}`/`ctx.waitUntil` lifecycle —
468
- * e.g. Cloudflare Workflow `run()` handlers — can flush explicitly too. See
469
- * `instrumentWorkflowRun` below.
470
- *
471
- * Each adapter's `flush()` is throttled by a per-isolate cooldown (default
472
- * 5s) so a busy fetch handler doesn't fire a POST per request — pass
473
- * `force: true` to bypass that cooldown for callers that only get one flush
474
- * attempt with no next request to retry on (Workflow `run()` exit).
475
- */
476
- export async function flushObservability(force = false): Promise<void> {
477
- const state = getBootState();
478
- await Promise.allSettled([
479
- state.otlpMeter?.flush(force),
480
- state.otlpLog?.flush(force),
481
- state.otlpTracer?.flush(force),
482
- ]);
483
- }
484
-
485
- /**
486
- * Boots observability (same env-var-driven wiring `instrumentWorker` uses)
487
- * and runs `fn`, flushing on the way out — the Workflow-entrypoint
488
- * equivalent of `instrumentWorker`. Cloudflare Workflows have no `{fetch}` /
489
- * `ctx.waitUntil` lifecycle, so this awaits the flush directly instead.
490
- *
491
- * Deliberately does NOT open a root span around `fn()`. Code in a
492
- * `WorkflowEntrypoint.run(event, step)` outside `step.do`/`step.sleep`
493
- * re-executes on every hibernate/wake replay — a span opened here would get
494
- * a fresh random trace ID on every replay leg, producing disconnected
495
- * traces instead of one coherent run. Create spans for individual
496
- * `step.do(...)` callbacks with `withTracing` instead (each step only truly
497
- * runs once, since `step.do` memoizes across replays), tagging them with
498
- * `event.instanceId` so a backend can group replay legs under one logical
499
- * run.
500
- *
501
- * The exit-time flush is `force`d (bypasses the per-isolate cooldown other
502
- * `flush()` callers respect) — a Workflow `run()` invocation gets exactly
503
- * one flush attempt on the way out, unlike a fetch handler where the next
504
- * request's `ctx.waitUntil(flush())` can pick up whatever a cooldown-skipped
505
- * flush left behind. Without forcing, a workflow with several replay legs in
506
- * quick succession could have its final leg's flush silently skipped by the
507
- * cooldown, losing that leg's buffered spans/metrics if the isolate is torn
508
- * down before the next wake.
509
- *
510
- * @example
511
- * ```ts
512
- * async run(event: WorkflowEvent<Params>, step: WorkflowStep) {
513
- * return instrumentWorkflowRun(this.env, undefined, async () => {
514
- * await step.do("fetch-product", () =>
515
- * withTracing("deco.workflow.step", () => fetchProduct(), {
516
- * "workflow.instance_id": event.instanceId,
517
- * "workflow.step": "fetch-product",
518
- * }),
519
- * );
520
- * });
521
- * }
522
- * ```
523
- */
524
- export async function instrumentWorkflowRun<T>(
525
- env: Record<string, unknown>,
526
- options: OtelOptions | undefined,
527
- fn: () => Promise<T>,
528
- ): Promise<T> {
529
- configureTracer(buildOtelApiTracer());
530
- bootObservability(options ?? {}, env);
531
- try {
532
- // Awaiting inside this try (rather than `return fn().finally(...)`)
533
- // ensures a synchronous throw from `fn` — not just a rejected promise —
534
- // still reaches the `finally` below instead of skipping it.
535
- return await fn();
536
- } finally {
537
- await flushObservability(true);
538
- }
539
- }
540
-
541
- /**
542
- * Build the legacy `@opentelemetry/api` global-tracer bridge. Stays a
543
- * no-op when no global TracerProvider is registered — same outcome as
544
- * the historical configuration.
545
- */
546
- function buildOtelApiTracer(): import("../middleware/observability").TracerAdapter {
547
- return {
548
- startSpan: (name, attrs) => {
549
- const merged = { ...getBootState().spanAttributeFloor, ...(attrs ?? {}) };
550
- const span = trace.getTracer("@decocms/start").startSpan(name, { attributes: merged });
551
- return {
552
- end: () => span.end(),
553
- setError: (error) => {
554
- const message = error instanceof Error ? error.message : String(error);
555
- if (error instanceof Error) span.recordException(error);
556
- span.setStatus({ code: SpanStatusCode.ERROR, message });
557
- },
558
- setAttribute: (k, v) => {
559
- span.setAttribute(k, v);
560
- if (k === "http.status_code" && typeof v === "number" && v >= 400) {
561
- span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${v}` });
562
- }
563
- },
564
- spanContext: () => {
565
- const ctx = span.spanContext();
566
- return {
567
- traceId: ctx.traceId,
568
- spanId: ctx.spanId,
569
- traceFlags: ctx.traceFlags,
570
- };
571
- },
572
- };
573
- },
574
- };
575
- }
576
-
577
- /**
578
- * Wire the framework tracer. When the OTLP traces endpoint is configured,
579
- * compose the direct-POST tracer ALONGSIDE the `@opentelemetry/api` bridge
580
- * via a fanout adapter so:
581
- * 1. `withTracing` calls feed BOTH adapters.
582
- * 2. A child span's `spanContext()` reports the direct-POST span's IDs
583
- * (the bridge is best-effort — if CF tracing isn't installed those
584
- * IDs are zeros anyway).
585
- *
586
- * When no traces endpoint is configured, fall back to the bridge alone —
587
- * preserves the legacy behavior for sites that haven't bumped wrangler.
588
- */
589
- function configureTracerStack(otlpAdapter: OtlpHttpTracer | null): void {
590
- const bridge = buildOtelApiTracer();
591
- if (!otlpAdapter) {
592
- configureTracer(bridge);
593
- return;
594
- }
595
- // Compose. The OTLP adapter is the "primary" (its IDs win for
596
- // `spanContext()` because callers downstream use them for trace
597
- // propagation). The bridge is best-effort — fed the same name/attrs
598
- // so CF Workers Observability still sees the spans if that channel
599
- // is enabled in wrangler.jsonc.
600
- configureTracer({
601
- startSpan(name, attrs) {
602
- const merged = { ...getBootState().spanAttributeFloor, ...(attrs ?? {}) };
603
- const primary = otlpAdapter.startSpan(name, merged);
604
- const secondary = bridge.startSpan(name, merged);
605
- return {
606
- end(): void {
607
- try {
608
- primary.end();
609
- } finally {
610
- try {
611
- secondary.end();
612
- } catch {
613
- /* swallow */
614
- }
615
- }
616
- },
617
- setError(error: unknown): void {
618
- try {
619
- primary.setError?.(error);
620
- } finally {
621
- try {
622
- secondary.setError?.(error);
623
- } catch {
624
- /* swallow */
625
- }
626
- }
627
- },
628
- setAttribute(key: string, value: string | number | boolean): void {
629
- primary.setAttribute?.(key, value);
630
- try {
631
- secondary.setAttribute?.(key, value);
632
- } catch {
633
- /* swallow */
634
- }
635
- },
636
- spanContext() {
637
- // The OTLP adapter owns the canonical IDs — those are the IDs
638
- // we propagate downstream via `traceparent` headers.
639
- return primary.spanContext?.() ?? secondary.spanContext?.() ?? {
640
- traceId: "",
641
- spanId: "",
642
- traceFlags: 0,
643
- };
644
- },
645
- };
646
- },
647
- });
648
- }
649
-
650
- // ---------------------------------------------------------------------------
651
- // Boot — wires the loggers/meters once (per worker isolate)
652
- // ---------------------------------------------------------------------------
653
-
654
- /**
655
- * Error's `name`/`message`/`stack` are non-enumerable, so a plain
656
- * `JSON.stringify(err)` ships `"{}"`. Duck-typed so DOMException and
657
- * cross-realm errors are covered too.
658
- */
659
- function isErrorLike(v: unknown): v is Error {
660
- return v instanceof Error || (
661
- typeof v === "object" && v !== null &&
662
- typeof (v as Error).message === "string" &&
663
- typeof (v as Error).name === "string" &&
664
- "stack" in v
665
- );
666
- }
667
-
668
- /** Expands nested errors (`{ error: err }`, `[err]`) instead of `{}`. */
669
- const errorReplacer = (_key: string, v: unknown) =>
670
- isErrorLike(v) ? { ...(v as object), name: v.name, message: v.message, stack: v.stack } : v;
671
-
672
- /** Formats one `console.*` argument as a log-body fragment. */
673
- function formatConsoleArg(a: unknown): string {
674
- if (typeof a === "string") return a;
675
- try {
676
- if (isErrorLike(a)) {
677
- const head = a.stack ?? `${a.name}: ${a.message}`;
678
- // Keep enumerable own fields (e.g. `status`, `host`) the old
679
- // JSON.stringify path used to ship.
680
- const { name: _n, message: _m, stack: _s, ...rest } = a as object as Record<string, unknown>;
681
- const extra = JSON.stringify(rest, errorReplacer);
682
- return extra === "{}" ? head : `${head} ${extra}`;
683
- }
684
- return JSON.stringify(a, errorReplacer);
685
- } catch {
686
- return String(a);
687
- }
688
- }
689
-
690
- /**
691
- * Replaces `console.*` with thin shims that route every call through the
692
- * framework `logger`, which forwards to the configured adapter (direct-POST
693
- * OTLP when active). The original functions are saved on `BootState` so
694
- * `_resetBootStateForTests()` can restore them between test runs.
695
- *
696
- * A re-entrancy guard (`busy`) prevents the loop that would occur if the
697
- * active logger adapter ever calls back into `console.*` (e.g. the
698
- * `defaultLoggerAdapter` in dev mode). Without the guard:
699
- * console.error → logger.error → defaultLoggerAdapter → console.error → …
700
- *
701
- * Only called when the OTLP logs endpoint is configured. In dev (no OTLP),
702
- * `console.*` is left untouched so `wrangler dev` / `wrangler tail` keep
703
- * showing output normally.
704
- */
705
- function patchConsole(state: BootState): void {
706
- if (state.origConsole) return; // already patched this isolate
707
-
708
- const orig: OrigConsole = {
709
- log: console.log.bind(console),
710
- info: console.info.bind(console),
711
- warn: console.warn.bind(console),
712
- error: console.error.bind(console),
713
- debug: console.debug.bind(console),
714
- };
715
- state.origConsole = orig;
716
-
717
- let busy = false;
718
-
719
- const forward = (level: LogLevel, args: unknown[]): void => {
720
- if (busy) return;
721
- busy = true;
722
- try {
723
- const msg = args.map(formatConsoleArg).join(" ");
724
- logger[level](msg);
725
- } finally {
726
- busy = false;
727
- }
728
- };
729
-
730
- console.log = (...args: unknown[]) => forward("info", args);
731
- console.info = (...args: unknown[]) => forward("info", args);
732
- console.warn = (...args: unknown[]) => forward("warn", args);
733
- console.error = (...args: unknown[]) => forward("error", args);
734
- console.debug = (...args: unknown[]) => forward("debug", args);
735
- }
736
-
737
- /**
738
- * Boots the observability stack for the current isolate: resolves the
739
- * `DECO_OTEL` on/off/auto switch, builds the resource-attribute floor
740
- * (service name/version/instance, deployment environment, cloud platform),
741
- * and — gated per env var — wires the AE meter and OTLP metrics/logs/traces
742
- * adapters. Idempotent per isolate (`BootState.booted` guards re-entry).
743
- *
744
- * Exported so callers with a lifecycle `instrumentWorker` doesn't fit
745
- * (Cloudflare Workflows — see `instrumentWorkflowRun`) can boot the same
746
- * stack directly.
747
- */
748
- export function bootObservability(opts: OtelOptions, env: Record<string, unknown>): void {
749
- const state = getBootState();
750
- if (state.booted) return;
751
-
752
- // `isDevMode()` reads `process.env.NODE_ENV === "development"`. Vite and
753
- // `@cloudflare/vite-plugin` set NODE_ENV during `vite dev`; `wrangler
754
- // deploy` does not. `CF_VERSION_METADATA` is NOT a reliable local signal —
755
- // wrangler dev populates it with a random per-session UUID.
756
- const mode = env[opts.envVar ?? "DECO_OTEL"];
757
- const isDisabled =
758
- mode === "off" ||
759
- (mode !== "on" && (opts.disabled || isDevMode()));
760
- if (isDisabled) {
761
- state.booted = true;
762
- return;
763
- }
764
-
765
- // Capture the original console.warn BEFORE patchConsole() runs. The onError
766
- // callbacks below need a direct channel to console that bypasses the logger
767
- // to avoid routing exporter-level warnings back through the OTLP adapter
768
- // that is currently failing.
769
- const warnDirect = console.warn.bind(console);
770
-
771
- const serviceName = opts.serviceName ?? (env.DECO_SITE_NAME as string | undefined) ?? "deco-site";
772
- const decoRuntimeVersion = opts.decoRuntimeVersion ?? DECO_RUNTIME_VERSION;
773
- const deploymentEnvironment = (env.DECO_ENV_NAME as string | undefined) ?? "production";
774
- const serviceVersion = (env.CF_VERSION_METADATA as { id?: string } | undefined)?.id;
775
-
776
- // service.name and service.version are OTel resource conventions. CF's
777
- // managed export already stamps service.name at the resource level (from
778
- // the Worker name in wrangler.jsonc) but framework-created spans don't
779
- // inherit resource attrs, so we stamp them per-span/per-log defensively.
780
- // service.version comes from the CF_VERSION_METADATA binding which is
781
- // unique per deployment — needed to correlate regressions with releases.
782
- //
783
- // service.instance.id (OTel SemConv required for distributed services) is a
784
- // per-isolate UUID generated at boot. Distinguishes parallel isolates on the
785
- // same deploy — required so the System Health Agent can attribute behavior
786
- // (memory creep, slow cold starts) to a specific instance.
787
- // https://opentelemetry.io/docs/specs/semconv/resource/#service
788
- //
789
- // cloud.provider / cloud.platform are stamped statically here because every
790
- // isolate runs on CF Workers. cloud.region (the CF colo) is per-request, not
791
- // per-isolate, so it's NOT in the resource floor — it MUST be attached at
792
- // the span level by the request handler.
793
- // https://opentelemetry.io/docs/specs/semconv/resource/cloud/
794
- //
795
- // Note: `deco.runtime.version` and `deco.apps.version` are Deco extensions
796
- // (not in OTel SemConv), so they remain as string literals.
797
- const floor: Record<string, string> = {
798
- [ATTR_SERVICE_NAME]: serviceName,
799
- [ATTR_SERVICE_INSTANCE_ID]: crypto.randomUUID(),
800
- [ATTR_DEPLOYMENT_ENVIRONMENT_NAME]: deploymentEnvironment,
801
- [ATTR_CLOUD_PROVIDER]: "cloudflare",
802
- [ATTR_CLOUD_PLATFORM]: "cloudflare_workers",
803
- "deco.runtime.version": decoRuntimeVersion,
804
- };
805
- if (serviceVersion) floor[ATTR_SERVICE_VERSION] = serviceVersion;
806
- if (opts.decoAppsVersion) floor["deco.apps.version"] = opts.decoAppsVersion;
807
-
808
- // Stamp on every span we create. CF-managed trace export emits its own
809
- // resource attribute set, so legacy resource attrs don't survive.
810
- // Stamping per-span preserves the dimensions dashboards / saved searches
811
- // filter on.
812
- state.spanAttributeFloor = floor;
813
-
814
- // Stamp on every log record. CF Workers Logs ships the JSON body
815
- // verbatim — without this floor, panels grouping logs by these
816
- // dimensions return empty. Caller-supplied `attrs` still win on
817
- // key collision (see logger.ts).
818
- setLoggerAttributeFloor(floor);
819
-
820
- // Logger — two paths composed:
821
- //
822
- // - `defaultLoggerAdapter`: structured JSON to `console.*`. CF
823
- // Workers Logs captures this and CF Destinations forwards a
824
- // `logs.head_sampling_rate` fraction to `deco-otel-ingest/v1/logs`.
825
- // Carries debug / info / warn / error.
826
- // - `otlpLog.adapter`: direct POST to `/v1/logs` for level=error
827
- // only, rate-limited (default 100/min, burst 20), buffered, flushed
828
- // via `ctx.waitUntil` at request end. Guarantees ≥99% error capture
829
- // regardless of the CF Destinations sampling rate. See
830
- // `otelHttpLog.ts` for the aggregation + rate-limit details.
831
- //
832
- // The two paths land in the SAME `default.otel_logs` table, so the
833
- // ingestor's existing PII redaction applies uniformly and dashboards
834
- // need no changes. Records from the direct-POST path are
835
- // distinguishable from CF-Destinations records by `ScopeName =
836
- // "@decocms/start"` if needed (CF stamps its own scope).
837
- const otlpLogsEnvVar = opts.otlpLogsEndpointEnvVar ?? "DECO_OTEL_LOGS_ENDPOINT";
838
- const otlpLogsEndpoint = (env[otlpLogsEnvVar] as string | undefined) ?? "";
839
- const otlpLogsEnabled =
840
- opts.otlpLogsEnabled !== false && otlpLogsEndpoint.length > 0;
841
- // Minimum log level precedence: env var > options > "info" default (OTel spec).
842
- // Invalid env values fall through silently.
843
- const otlpLogsMinLevelEnvVar =
844
- opts.otlpLogsMinLevelEnvVar ?? "DECO_OTEL_LOGS_MIN_LEVEL";
845
- const otlpLogsMinLevelFromEnv = (
846
- (env[otlpLogsMinLevelEnvVar] as string | undefined) ?? ""
847
- ).toLowerCase();
848
- const validLogLevels = ["debug", "info", "warn", "error"] as const;
849
- const otlpLogsMinLevel: LogLevel =
850
- (validLogLevels as readonly string[]).includes(otlpLogsMinLevelFromEnv)
851
- ? (otlpLogsMinLevelFromEnv as LogLevel)
852
- : opts.otlpLogsMinLevel ?? "info";
853
- // Sync the logger gate so logger.debug() calls are not silently dropped
854
- // before reaching the OTLP adapter when minLevel is "debug" or "info".
855
- setLogLevel(otlpLogsMinLevel);
856
- const otlpHeadersEnvVar = opts.otlpHeadersEnvVar ?? "DECO_OTEL_HEADERS";
857
- const otlpHeadersFromEnv = (env[otlpHeadersEnvVar] as string | undefined) ?? "";
858
- const parsedEnvHeaders: Record<string, string> = {};
859
- for (const pair of otlpHeadersFromEnv.split(",")) {
860
- const eqIdx = pair.indexOf("=");
861
- if (eqIdx > 0) {
862
- parsedEnvHeaders[pair.slice(0, eqIdx).trim()] = pair.slice(eqIdx + 1).trim();
863
- }
864
- }
865
- const otlpAuthTokenEnvVar = opts.otlpAuthTokenEnvVar ?? "DECO_OTEL_AUTH_TOKEN";
866
- const otlpAuthToken = (env[otlpAuthTokenEnvVar] as string | undefined) ?? opts.otlpAuthToken ?? "";
867
- const authHeader: Record<string, string> = otlpAuthToken ? { authorization: otlpAuthToken } : {};
868
- // Priority: auth token (lowest) → DECO_OTEL_HEADERS env → otlpHeaders option (highest).
869
- const otlpHeaders: Record<string, string> = { ...authHeader, ...parsedEnvHeaders, ...(opts.otlpHeaders ?? {}) };
870
-
871
- const errorPromotionEnvVar =
872
- opts.otlpTracesErrorPromotionEnvVar ?? "DECO_OTEL_ERROR_PROMOTION";
873
- const errorPromotionEnabled =
874
- (env[errorPromotionEnvVar] as string | undefined) === "true" ||
875
- (opts.otlpTracesErrorPromotion ?? false);
876
-
877
- if (otlpLogsEnabled) {
878
- state.otlpLog = createOtlpHttpLogAdapter({
879
- endpoint: otlpLogsEndpoint,
880
- resourceAttributes: floor,
881
- scopeVersion: decoRuntimeVersion,
882
- minLevel: otlpLogsMinLevel,
883
- headers: otlpHeaders,
884
- fetchImpl: opts.otlpLogsFetchImpl,
885
- promoteTrace: errorPromotionEnabled
886
- ? (traceId) => state.otlpTracer?.promoteTrace(traceId)
887
- : undefined,
888
- onError: (kind, err) => {
889
- // Use warnDirect (pre-patch console.warn) to avoid routing this
890
- // warning back through the OTLP adapter that is currently failing.
891
- try {
892
- warnDirect(
893
- JSON.stringify({
894
- level: "warn",
895
- msg: "otlp error-log exporter",
896
- kind,
897
- error: err instanceof Error ? err.message : String(err),
898
- timestamp: new Date().toISOString(),
899
- }),
900
- );
901
- } catch {
902
- /* swallow */
903
- }
904
- },
905
- });
906
- } else {
907
- state.otlpLog = null;
908
- }
909
-
910
- if (otlpLogsEnabled) {
911
- // OTLP active: direct-POST is the sole log transport.
912
- // console.* will be intercepted by patchConsole() below so all
913
- // application and third-party console calls route here too.
914
- // defaultLoggerAdapter is excluded to prevent workerd from capturing
915
- // framework logs (which would make them visible to the tail worker a
916
- // second time — the tail worker only needs to see what the worker
917
- // itself cannot capture: exceededCpu / exceededMemory / isolate crashes).
918
- configureLogger(createCompositeLogger([state.otlpLog!.adapter]));
919
- } else {
920
- // No OTLP endpoint — dev mode. Keep writing to console so wrangler dev /
921
- // wrangler tail show output normally. No monkey-patch applied.
922
- configureLogger(createCompositeLogger([defaultLoggerAdapter]));
923
- }
924
-
925
- // Meter — fan out to two backends when both are configured:
926
- //
927
- // - AE (binding `DECO_METRICS`): high-cardinality drill-down, queryable
928
- // via the per-site dataset.
929
- // - OTLP/HTTP (env `DECO_OTEL_METRICS_ENDPOINT`): SRE-grade rollups
930
- // landed in ClickHouse `otel_metrics_{sum,gauge,histogram}` via the
931
- // `deco-otel-ingest` Worker. Cumulative temporality, per-isolate
932
- // buffer flushed by `ctx.waitUntil` in `instrumentWorker`.
933
- //
934
- // The two emitters are NOT redundant — AE keeps per-request per-path
935
- // dimensions; OTLP carries the same metric names at coarser cardinality
936
- // and survives outside the CF dashboard. Cost model in
937
- // `docs/observability.md` accounts for both.
938
- const aeBindingName = opts.analyticsEngineBindingName ?? "DECO_METRICS";
939
- const aeEnabled = opts.analyticsEngineEnabled !== false && Boolean(env[aeBindingName]);
940
- const aeAdapter = aeEnabled
941
- ? createAnalyticsEngineMeterAdapter({ bindingName: aeBindingName })
942
- : null;
943
-
944
- const otlpEnvVar = opts.otlpMetricsEndpointEnvVar ?? "DECO_OTEL_METRICS_ENDPOINT";
945
- const otlpEndpoint = (env[otlpEnvVar] as string | undefined) ?? "";
946
- const otlpEnabled = opts.otlpMetricsEnabled !== false && otlpEndpoint.length > 0;
947
- if (otlpEnabled) {
948
- state.otlpMeter = createOtlpHttpMeterAdapter({
949
- endpoint: otlpEndpoint,
950
- resourceAttributes: floor,
951
- scopeVersion: decoRuntimeVersion,
952
- headers: otlpHeaders,
953
- fetchImpl: opts.otlpMetricsFetchImpl,
954
- metricMetadata: METRIC_METADATA,
955
- onError: (kind, err) => {
956
- try {
957
- warnDirect(
958
- JSON.stringify({
959
- level: "warn",
960
- msg: "otlp metrics exporter",
961
- kind,
962
- error: err instanceof Error ? err.message : String(err),
963
- timestamp: new Date().toISOString(),
964
- }),
965
- );
966
- } catch {
967
- /* swallow */
968
- }
969
- },
970
- });
971
- } else {
972
- state.otlpMeter = null;
973
- }
974
-
975
- const composedMeter = createCompositeMeter([aeAdapter, state.otlpMeter]);
976
- // Composite meter is always installed — when both backends are absent the
977
- // composite becomes a 0-element no-op via createCompositeMeter's filter.
978
- configureMeter(composedMeter);
979
-
980
- // Traces — direct-POST exporter for framework `deco.*` spans. Without
981
- // this, `withTracing` delegates to the no-op `@opentelemetry/api`
982
- // global tracer and every framework span silently disappears (the
983
- // Phase 3 gap documented in `MIGRATION_TOOLING_PLAN.md`). Same
984
- // transport pattern as metrics/error-logs — buffered, sampled by
985
- // trace-id hash, flushed via `ctx.waitUntil`.
986
- const otlpTracesEnvVar = opts.otlpTracesEndpointEnvVar ?? "DECO_OTEL_TRACES_ENDPOINT";
987
- const otlpTracesEndpoint = (env[otlpTracesEnvVar] as string | undefined) ?? "";
988
- const otlpTracesEnabled =
989
- opts.otlpTracesEnabled !== false && otlpTracesEndpoint.length > 0;
990
- if (otlpTracesEnabled) {
991
- // Sampling rate precedence: env var > options > 0.01 default.
992
- // Invalid env values (NaN, < 0, > 1) fall through silently.
993
- const otlpTracesSamplingRateEnvVar =
994
- opts.otlpTracesSamplingRateEnvVar ?? "DECO_OTEL_TRACES_SAMPLING_RATE";
995
- const samplingRateFromEnv = Number.parseFloat(
996
- (env[otlpTracesSamplingRateEnvVar] as string | undefined) ?? "",
997
- );
998
- const samplingRateOverride =
999
- Number.isFinite(samplingRateFromEnv) &&
1000
- samplingRateFromEnv >= 0 &&
1001
- samplingRateFromEnv <= 1
1002
- ? samplingRateFromEnv
1003
- : undefined;
1004
- const errorPromotionRateEnvVar =
1005
- opts.otlpTracesErrorPromotionRateEnvVar ?? "DECO_OTEL_ERROR_PROMOTION_RATE";
1006
- const errorPromotionRateFromEnv = Number.parseFloat(
1007
- (env[errorPromotionRateEnvVar] as string | undefined) ?? "",
1008
- );
1009
- const errorPromotionRate =
1010
- Number.isFinite(errorPromotionRateFromEnv) &&
1011
- errorPromotionRateFromEnv >= 0 &&
1012
- errorPromotionRateFromEnv <= 1
1013
- ? errorPromotionRateFromEnv
1014
- : (opts.otlpTracesErrorPromotionRate ?? 0.1);
1015
-
1016
- state.otlpTracer = createOtlpHttpTracerAdapter({
1017
- endpoint: otlpTracesEndpoint,
1018
- resourceAttributes: floor,
1019
- scopeVersion: decoRuntimeVersion,
1020
- headSamplingRate: samplingRateOverride ?? opts.otlpTracesSamplingRate ?? 0.01,
1021
- errorPromotionRate,
1022
- headers: otlpHeaders,
1023
- fetchImpl: opts.otlpTracesFetchImpl,
1024
- getActiveSpanForParent: () => getActiveSpan(),
1025
- getRequestTraceContext,
1026
- getForceSampled: getDebugSampled,
1027
- onError: (kind, err) => {
1028
- try {
1029
- warnDirect(
1030
- JSON.stringify({
1031
- level: "warn",
1032
- msg: "otlp traces exporter",
1033
- kind,
1034
- error: err instanceof Error ? err.message : String(err),
1035
- timestamp: new Date().toISOString(),
1036
- }),
1037
- );
1038
- } catch {
1039
- /* swallow */
1040
- }
1041
- },
1042
- });
1043
- } else {
1044
- state.otlpTracer = null;
1045
- }
1046
-
1047
- // Wire the tracer stack — composes the OTLP direct-POST adapter (when
1048
- // configured) with the @opentelemetry/api bridge. See
1049
- // `configureTracerStack` for the fanout semantics.
1050
- configureTracerStack(state.otlpTracer);
1051
-
1052
- state.booted = true;
1053
-
1054
- // Intercept console.* only when OTLP is active (production). In dev mode
1055
- // (no OTLP endpoint) console is left untouched so wrangler dev / wrangler
1056
- // tail keep showing output normally.
1057
- if (otlpLogsEnabled) {
1058
- patchConsole(state);
1059
- }
1060
-
1061
- // Boot breadcrumb — infra telemetry, not application telemetry. Goes to the
1062
- // original console (pre-patch) so it shows in wrangler dev / wrangler tail
1063
- // without polluting the OTLP buffer (where it would interfere with trace-
1064
- // based sampling — there is no active span at boot time).
1065
- try {
1066
- warnDirect(
1067
- JSON.stringify({
1068
- level: "info",
1069
- msg: "observability booted",
1070
- service: serviceName,
1071
- analyticsEngine: aeEnabled,
1072
- otlpMetrics: otlpEnabled,
1073
- otlpLogs: otlpLogsEnabled,
1074
- otlpLogsMinLevel: otlpLogsMinLevel,
1075
- otlpTraces: otlpTracesEnabled,
1076
- consolePatch: otlpLogsEnabled,
1077
- runtimeVersion: decoRuntimeVersion,
1078
- deploymentEnvironment,
1079
- ...(serviceVersion ? { serviceVersion } : {}),
1080
- }),
1081
- );
1082
- } catch {
1083
- /* swallow */
1084
- }
1085
- }
1086
-
1087
- /**
1088
- * Test-only: clear boot state so successive tests can re-boot
1089
- * `instrumentWorker` with different options. Do not call from app code.
1090
- */
1091
- export function _resetBootStateForTests(): void {
1092
- const state = getBootState();
1093
- state.booted = false;
1094
- state.spanAttributeFloor = {};
1095
- state.otlpMeter = null;
1096
- state.otlpLog = null;
1097
- state.otlpTracer = null;
1098
- if (state.origConsole) {
1099
- console.log = state.origConsole.log;
1100
- console.info = state.origConsole.info;
1101
- console.warn = state.origConsole.warn;
1102
- console.error = state.origConsole.error;
1103
- console.debug = state.origConsole.debug;
1104
- state.origConsole = null;
1105
- }
1106
- setLoggerAttributeFloor({});
1107
- }
1108
-
1109
- // ---------------------------------------------------------------------------
1110
- // Helpers
1111
- // ---------------------------------------------------------------------------
1112
-
1113
- /**
1114
- * @decocms/start version, read from package.json so it stays in sync
1115
- * automatically with every semantic-release cut.
1116
- */
1117
- import pkg from "../../package.json";
1118
- const DECO_RUNTIME_VERSION = pkg.version;