@classytic/arc 2.47.0 → 2.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (216) hide show
  1. package/dist/{EventTransport-BHKy4_Bi.mjs → EventTransport-DbHZK230.mjs} +2 -2
  2. package/dist/{HookSystem-CAIDVoKC.mjs → HookSystem-DMoeJ6Do.mjs} +2 -2
  3. package/dist/{QueryCache-DdvrGG8Q.d.mts → QueryCache-BE47tmlO.d.mts} +36 -1
  4. package/dist/{ResourceRegistry-23Ml6FNe.mjs → ResourceRegistry-CP-iTcKy.mjs} +2 -2
  5. package/dist/{acquire-DoFX06fm.mjs → acquire-CB0va87C.mjs} +1 -1
  6. package/dist/audit/index.d.mts +1 -1
  7. package/dist/audit/index.mjs +4 -4
  8. package/dist/auth/audit.mjs +1 -1
  9. package/dist/auth/index.d.mts +2 -2
  10. package/dist/auth/index.mjs +53 -15
  11. package/dist/auth/redis-session.mjs +1 -1
  12. package/dist/{authorizationDecision-DYiubkYw.mjs → authorizationDecision-DHO94aV2.mjs} +4 -4
  13. package/dist/{boundedMap-CtdzpJ3X.mjs → boundedMap-C51EUUOm.mjs} +1 -1
  14. package/dist/{buildHandler-CARdmPNo.mjs → buildHandler-9DuwEKvr.mjs} +23 -16
  15. package/dist/cache/index.d.mts +2 -2
  16. package/dist/cache/index.mjs +4 -4
  17. package/dist/{caching-QRiryDLs.mjs → caching-COTX3sDa.mjs} +3 -6
  18. package/dist/{claimed-BLecr1j3.mjs → claimed-C7T1nHlo.mjs} +1 -1
  19. package/dist/cleanup/index.d.mts +2 -2
  20. package/dist/cleanup/index.mjs +4 -4
  21. package/dist/cli/commands/describe.d.mts +1 -1
  22. package/dist/cli/commands/describe.mjs +3 -3
  23. package/dist/cli/commands/docs.mjs +3 -3
  24. package/dist/cli/commands/doctor.mjs +1 -1
  25. package/dist/cli/commands/generate.mjs +2 -2
  26. package/dist/cli/commands/init.mjs +2 -2
  27. package/dist/cli/commands/introspect.mjs +2 -2
  28. package/dist/cli/index.mjs +3 -3
  29. package/dist/{constants-Cx7BcnHT.mjs → constants-DOnfMd7i.mjs} +1 -1
  30. package/dist/context/index.mjs +5 -5
  31. package/dist/core/index.d.mts +3 -3
  32. package/dist/core/index.mjs +7 -7
  33. package/dist/{core-0WyMuo0f.mjs → core-BoEdFDDw.mjs} +3 -3
  34. package/dist/{createActionRouter-mLAGbpDV.mjs → createActionRouter-CpTn15dm.mjs} +54 -18
  35. package/dist/{createAggregationRouter-BEAjn3dA.mjs → createAggregationRouter-CD_Hydp0.mjs} +13 -11
  36. package/dist/{createApp-QDP4vYWH.mjs → createApp-Be6XTGD9.mjs} +332 -40
  37. package/dist/{createMcpServer-DzXHX0SO.d.mts → createMcpServer-CS2KOVP6.d.mts} +9 -10
  38. package/dist/{defineAggregation-CFNfvz-C.mjs → defineAggregation-BI5pRb8c.mjs} +1 -1
  39. package/dist/{defineResource-BROJmhzJ.mjs → defineResource-BAzNu5Um.mjs} +8 -8
  40. package/dist/discovery/index.mjs +1 -1
  41. package/dist/docs/index.d.mts +1 -1
  42. package/dist/docs/index.mjs +3 -3
  43. package/dist/{elevation-DrXeEWWk.mjs → elevation-DupGuM41.mjs} +6 -9
  44. package/dist/encryption/index.mjs +3 -3
  45. package/dist/{errorHandler-BiBXtxj4.mjs → errorHandler-DA03vRqp.mjs} +4 -7
  46. package/dist/{errors-DnrUChAy.mjs → errors-BpYV859Y.mjs} +1 -1
  47. package/dist/{eventPlugin-BhKLUe7H.mjs → eventPlugin-D7LYtYzL.mjs} +9 -13
  48. package/dist/{eventTypes-CCIRGakw.mjs → eventTypes-BqA-N-Uz.mjs} +2 -2
  49. package/dist/events/index.d.mts +18 -5
  50. package/dist/events/index.mjs +8 -8
  51. package/dist/events/transports/redis-stream-entry.mjs +4 -4
  52. package/dist/events/transports/redis.d.mts +35 -0
  53. package/dist/events/transports/redis.mjs +87 -11
  54. package/dist/factory/index.d.mts +4 -4
  55. package/dist/factory/index.mjs +6 -6
  56. package/dist/{fastify-augmentation-bzkWPt1f.d.mts → fastify-augmentation-baQc3MaO.d.mts} +2 -2
  57. package/dist/fieldTypes-EFWxCkZ5.mjs +80 -0
  58. package/dist/{fields-CYdpcV73.mjs → fields-CT1Erg7o.mjs} +1 -1
  59. package/dist/{filter-merge-6kasezRH.mjs → filter-merge-B1eJ1pMx.mjs} +1 -1
  60. package/dist/{generate-DUkcbc4r.mjs → generate-Cr0ULavs.mjs} +2 -2
  61. package/dist/{headers-KxhrKevA.mjs → headers-D4bncIOf.mjs} +2 -2
  62. package/dist/{health-jkYNdobJ.mjs → health-BoFxrkJE.mjs} +1 -1
  63. package/dist/{health-CRJg3IIq.mjs → health-DN_pUVMX.mjs} +1 -1
  64. package/dist/hooks/index.d.mts +1 -1
  65. package/dist/hooks/index.mjs +2 -2
  66. package/dist/http-cache/index.d.mts +2 -2
  67. package/dist/http-cache/index.mjs +4 -4
  68. package/dist/http-cache/purgers/cloudflare.mjs +2 -2
  69. package/dist/http-cache/purgers/fastly.mjs +2 -2
  70. package/dist/http-cache/testing/index.mjs +1 -1
  71. package/dist/idempotency/index.d.mts +1 -1
  72. package/dist/idempotency/index.mjs +10 -8
  73. package/dist/idempotency/redis.mjs +2 -2
  74. package/dist/{index-B5i9-vuP.d.mts → index-CMNpMBtW.d.mts} +1 -1
  75. package/dist/{index-BxZS-8So.d.mts → index-DKM2p5w5.d.mts} +48 -23
  76. package/dist/{index-Cy2-QffW.d.mts → index-DLCcLUQT.d.mts} +69 -6
  77. package/dist/{index-DFCCQ9AE.d.mts → index-DexdFs1a.d.mts} +1 -1
  78. package/dist/{index-D1X_C_qz.d.mts → index-Dhrks-hM.d.mts} +60 -10
  79. package/dist/index.d.mts +4 -4
  80. package/dist/index.mjs +11 -11
  81. package/dist/{init-CACwpktI.mjs → init-C4a24wD2.mjs} +1 -1
  82. package/dist/integrations/event-gateway.mjs +2 -2
  83. package/dist/integrations/index.d.mts +2 -2
  84. package/dist/integrations/index.mjs +1 -1
  85. package/dist/integrations/jobs/index.mjs +3 -3
  86. package/dist/integrations/mcp/index.d.mts +6 -38
  87. package/dist/integrations/mcp/index.mjs +2 -2
  88. package/dist/integrations/mcp/testing.d.mts +11 -15
  89. package/dist/integrations/mcp/testing.mjs +22 -42
  90. package/dist/integrations/streamline.mjs +3 -3
  91. package/dist/integrations/webhooks.d.mts +1 -1
  92. package/dist/integrations/webhooks.mjs +4 -4
  93. package/dist/integrations/websocket-pushref-redis.mjs +1 -1
  94. package/dist/integrations/websocket-redis.mjs +1 -1
  95. package/dist/integrations/websocket.mjs +2 -2
  96. package/dist/{jsonBody-CzDBkCme.mjs → jsonBody-DoTt5BS6.mjs} +2 -2
  97. package/dist/{keys-Cbwf6r1B.mjs → keys--l9n7aOC.mjs} +1 -1
  98. package/dist/{loadResources-Kr6vuljv.mjs → loadResources-rygByIQA.mjs} +3 -3
  99. package/dist/{loadResourcesFromEntry-D2e0qoDR.mjs → loadResourcesFromEntry-ItNBIQ5w.mjs} +2 -2
  100. package/dist/logger/index.mjs +2 -2
  101. package/dist/{logger-C110X5Yz.mjs → logger-UbknHqHy.mjs} +1 -1
  102. package/dist/{mcpPlugin-4lIPr9OJ.mjs → mcpPlugin-CTkk4RP8.mjs} +218 -378
  103. package/dist/{memory-D9qkhXiB.mjs → memory-C47xVsjX.mjs} +3 -3
  104. package/dist/{metrics-B-qrrWfI.mjs → metrics-TJyAb1Xk.mjs} +4 -7
  105. package/dist/middleware/index.d.mts +1 -1
  106. package/dist/middleware/index.mjs +3 -3
  107. package/dist/migrations/index.mjs +2 -2
  108. package/dist/{module-BD8xHgrz.mjs → module-CWiqsXnh.mjs} +1 -1
  109. package/dist/{multiTenant-KZj8j1uJ.d.mts → multiTenant-QtDzxx_K.d.mts} +1 -1
  110. package/dist/{multipartBody-qU7KCn1l.mjs → multipartBody-BdG1qbn1.mjs} +1 -1
  111. package/dist/{observeSend-BnPtTotW.mjs → observeSend-DrA3ADFN.mjs} +1 -1
  112. package/dist/{openapi-DoVa5SVP.mjs → openapi-D6MAbYpv.mjs} +7 -7
  113. package/dist/outbox-admin/index.d.mts +1 -1
  114. package/dist/outbox-admin/index.mjs +5 -5
  115. package/dist/{outbox-module-DyITEIop.mjs → outbox-module-D5QABFQW.mjs} +197 -28
  116. package/dist/{outbox-module-5Mnwcycy.d.mts → outbox-module-DzW6zwWJ.d.mts} +103 -10
  117. package/dist/permissions/index.d.mts +2 -2
  118. package/dist/permissions/index.mjs +7 -7
  119. package/dist/{permissions-BBy4bOGi.mjs → permissions-CFsmdYUt.mjs} +9 -9
  120. package/dist/{pipe-BOm2o4UA.mjs → pipe-B_05AgGt.mjs} +2 -2
  121. package/dist/pipeline/index.d.mts +1 -1
  122. package/dist/pipeline/index.mjs +2 -2
  123. package/dist/{plan-DDIGwuxr.mjs → plan-BnlNJhrj.mjs} +1 -1
  124. package/dist/{plugin-Bn4D_0XK.mjs → plugin-CrMPYbdj.mjs} +94 -50
  125. package/dist/plugins/index.d.mts +6 -5
  126. package/dist/plugins/index.mjs +19 -18
  127. package/dist/plugins/response-cache.mjs +4 -4
  128. package/dist/plugins/tracing-entry.mjs +2 -2
  129. package/dist/{pluralize-ClEjcKlG.mjs → pluralize-oVIxJ4CY.mjs} +1 -1
  130. package/dist/presets/filesUpload.d.mts +1 -1
  131. package/dist/presets/filesUpload.mjs +5 -5
  132. package/dist/presets/index.d.mts +2 -2
  133. package/dist/presets/index.mjs +2 -2
  134. package/dist/presets/multiTenant.d.mts +1 -1
  135. package/dist/presets/multiTenant.mjs +5 -5
  136. package/dist/presets/search.d.mts +1 -1
  137. package/dist/presets/search.mjs +2 -2
  138. package/dist/{presets-DK2jh5YR.mjs → presets-CUd3L7v6.mjs} +4 -4
  139. package/dist/{projection-BHH-sXyS.mjs → projection-DowJlIto.mjs} +2 -2
  140. package/dist/{purger.types-2wNJK_89.mjs → purger.types-BjKy8869.mjs} +1 -1
  141. package/dist/{queryCachePlugin-Ckqe98AM.mjs → queryCachePlugin-BvB3k_Fh.mjs} +114 -14
  142. package/dist/{queryCachePlugin-DYQUyeJ9.d.mts → queryCachePlugin-DrQNnGws.d.mts} +1 -1
  143. package/dist/{rateLimitKey-CWAjlqcN.mjs → rateLimitKey-56nH1cWN.mjs} +1 -1
  144. package/dist/{realtime-BIJi9USY.mjs → realtime-DXGBPtYK.mjs} +19 -22
  145. package/dist/registry/index.d.mts +2 -2
  146. package/dist/registry/index.mjs +3 -3
  147. package/dist/{registry-y9ZA-R_J.mjs → registry-Biz-6sEZ.mjs} +2 -2
  148. package/dist/{relay-BNrC1CEP.mjs → relay-DEIoMntZ.mjs} +200 -99
  149. package/dist/{renewingLease-CS43br5E.mjs → renewingLease-BCJpW9-u.mjs} +1 -1
  150. package/dist/{replyHelpers-oZDzakGb.mjs → replyHelpers-DliJNb0-.mjs} +2 -2
  151. package/dist/{requestContext-fWb_YaV2.mjs → requestContext-tUgLt9Ky.mjs} +1 -1
  152. package/dist/{requirement--2hWyyHi.mjs → requirement-0l2DApiQ.mjs} +1 -1
  153. package/dist/{resourceRateLimit-DCWglD7V.d.mts → resourceRateLimit-BPiESPtG.d.mts} +4 -0
  154. package/dist/{resourceRateLimit-1WbcyMZY.mjs → resourceRateLimit-iSXF8rLH.mjs} +19 -4
  155. package/dist/{rolldown-runtime-yH2lHMo_.mjs → rolldown-runtime-gKJR3o-6.mjs} +1 -1
  156. package/dist/{routeValidator-BSlRIA5c.mjs → routeValidator-xNYA4rr1.mjs} +47 -5
  157. package/dist/{runtimeCapabilities-CYCEtU1W.mjs → runtimeCapabilities-BQK-GrYe.mjs} +1 -1
  158. package/dist/{schedules-B5WGlYIT.mjs → schedules-D9iMVFhF.mjs} +6 -9
  159. package/dist/{schemaConverter-DtNvts-6.mjs → schemaConverter-cIh4oX9a.mjs} +2 -2
  160. package/dist/{actionPermissions-DXrlWHHK.mjs → schemaIR-BsY4y9VP.mjs} +184 -16
  161. package/dist/schemas/index.mjs +1 -1
  162. package/dist/scim/index.mjs +2 -2
  163. package/dist/scope/index.d.mts +1 -1
  164. package/dist/scope/index.mjs +5 -5
  165. package/dist/{scope-BwVLSyNG.mjs → scope-QyhM9w8z.mjs} +4 -4
  166. package/dist/{shutdown-BJiJN7FT.mjs → shutdown-BM7Q0h4B.mjs} +1 -1
  167. package/dist/{sse-B_50llZu.mjs → sse-ofvlcTQQ.mjs} +9 -35
  168. package/dist/sseStats-DQqNN385.d.mts +112 -0
  169. package/dist/sseStream-BxQW7hPq.mjs +166 -0
  170. package/dist/{store-helpers-D-n5cwy5.mjs → store-helpers-_FRhHDyv.mjs} +1 -1
  171. package/dist/{simpleEqualityMatcher-DGRLq-1k.mjs → streamFrames-B3ZJfI02.mjs} +19 -2
  172. package/dist/{streaming-Dcgqa-hH.mjs → streaming-HZr63UiM.mjs} +1 -1
  173. package/dist/{subscriberIdentity-C9KhIXTF.mjs → subscriberIdentity-DSgnoT_D.mjs} +1 -1
  174. package/dist/{tenancy-COrhjPRZ.mjs → tenancy-_ukT0oBt.mjs} +2 -2
  175. package/dist/{tenantPreparation-BElWHytd.mjs → tenantPreparation-DSlQI53c.mjs} +4 -4
  176. package/dist/testing/cleanupStoreContract.mjs +1 -1
  177. package/dist/testing/index.d.mts +4 -4
  178. package/dist/testing/index.mjs +324 -17
  179. package/dist/testing/outboxStoreContract.mjs +2 -2
  180. package/dist/testing/requiredPorts.mjs +2 -2
  181. package/dist/testing/storageContract.mjs +1 -1
  182. package/dist/{timing-CaxKbRk_.mjs → timing-Z8p-Zlw1.mjs} +1 -1
  183. package/dist/{transactionContext-8qKON0Nk.mjs → transactionContext-DBbSTfY3.mjs} +1 -1
  184. package/dist/{typeGuards-DVjVSsXO.mjs → typeGuards-_6nNQqgq.mjs} +1 -1
  185. package/dist/types/index.d.mts +1 -1
  186. package/dist/types/index.mjs +1 -1
  187. package/dist/types/storage.mjs +1 -1
  188. package/dist/{types-DeLiuaNv.d.mts → types-B4E0sc6D.d.mts} +20 -31
  189. package/dist/{types-DZHqOuJE.mjs → types-CrOlZ4rY.mjs} +4 -4
  190. package/dist/usage/index.d.mts +1 -1
  191. package/dist/usage/index.mjs +7 -7
  192. package/dist/{userHelpers-_eGj6kf0.mjs → userHelpers-CBKx3XJN.mjs} +1 -1
  193. package/dist/utils/index.d.mts +239 -34
  194. package/dist/utils/index.mjs +13 -13
  195. package/dist/{utils-Dd6MWpye.mjs → utils--HE8R8sH.mjs} +761 -8
  196. package/dist/{validate-BaF5wd0x.mjs → validate-BUeE2MLR.mjs} +3 -3
  197. package/dist/{versioning-S18y2-0C.d.mts → versioning-B07RgD27.d.mts} +2 -13
  198. package/dist/{versioning-DyV7mwtK.mjs → versioning-qYgqwOhL.mjs} +4 -7
  199. package/dist/{workScope-CmCBUmPR.mjs → workScope-C-1QHNmV.mjs} +2 -2
  200. package/llms.txt +2 -2
  201. package/package.json +42 -50
  202. package/skills/arc/references/api-reference.md +2 -2
  203. package/skills/arc/references/auth-better-auth.md +1 -0
  204. package/skills/arc/references/events-outbox.md +7 -4
  205. package/skills/arc/references/events.md +2 -2
  206. package/skills/arc/references/mcp-custom-tools.md +1 -1
  207. package/skills/arc/references/mcp-setup.md +11 -10
  208. package/skills/arc/references/mcp-testing.md +3 -3
  209. package/skills/arc/references/production-api.md +4 -0
  210. package/skills/arc/references/production-boot.md +2 -0
  211. package/skills/arc/references/production-idempotency.md +1 -1
  212. package/skills/arc/references/production-realtime.md +28 -2
  213. package/skills/arc/references/validation.md +4 -0
  214. package/skills/arc/references/writes-hooks-errors.md +1 -0
  215. package/dist/schemaIR-uS_RHqa3.mjs +0 -108
  216. package/dist/sseStream-BjSo9Ult.mjs +0 -57
@@ -1,16 +1,17 @@
1
- /*! @classytic/arc v2.47.0 | MIT | https://classytic.com */
2
- import { f as createError } from "./errors-DnrUChAy.mjs";
3
- import { n as getUserRoles } from "./userHelpers-_eGj6kf0.mjs";
4
- import { b as isElevated, n as PUBLIC_SCOPE, u as getRequestScope, x as isMember } from "./types-DZHqOuJE.mjs";
5
- import { a as resolveEffectiveRoles, r as deriveHiddenFieldPermissions, t as applyFieldReadPermissions } from "./fields-CYdpcV73.mjs";
6
- import { t as buildRequestScopeProjection } from "./projection-BHH-sXyS.mjs";
7
- import { n as requestContext } from "./requestContext-fWb_YaV2.mjs";
8
- import { n as isTenantPreparation } from "./tenantPreparation-BElWHytd.mjs";
9
- import { n as evaluateAndApplyPermission } from "./authorizationDecision-DYiubkYw.mjs";
10
- import { t as executePipeline } from "./pipe-BOm2o4UA.mjs";
11
- import { n as idempotencyConfigProblem, t as declaresIdempotencyFence } from "./requirement--2hWyyHi.mjs";
12
- import { i as resolveResourceRateLimiter, r as recordUnenforcedRateLimit } from "./resourceRateLimit-1WbcyMZY.mjs";
13
- import { n as arcRouteValidatorCompiler } from "./routeValidator-BSlRIA5c.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { f as createError } from "./errors-BpYV859Y.mjs";
3
+ import { n as getUserRoles } from "./userHelpers-CBKx3XJN.mjs";
4
+ import { b as isElevated, n as PUBLIC_SCOPE, u as getRequestScope, x as isMember } from "./types-CrOlZ4rY.mjs";
5
+ import { a as resolveEffectiveRoles, r as deriveHiddenFieldPermissions, t as applyFieldReadPermissions } from "./fields-CT1Erg7o.mjs";
6
+ import { o as toJsonSchema } from "./schemaConverter-cIh4oX9a.mjs";
7
+ import { t as buildRequestScopeProjection } from "./projection-DowJlIto.mjs";
8
+ import { n as requestContext } from "./requestContext-tUgLt9Ky.mjs";
9
+ import { n as isTenantPreparation } from "./tenantPreparation-DSlQI53c.mjs";
10
+ import { n as evaluateAndApplyPermission } from "./authorizationDecision-DHO94aV2.mjs";
11
+ import { t as executePipeline } from "./pipe-B_05AgGt.mjs";
12
+ import { n as idempotencyConfigProblem, t as declaresIdempotencyFence } from "./requirement-0l2DApiQ.mjs";
13
+ import { i as resolveResourceRateLimiter, r as recordUnenforcedRateLimit } from "./resourceRateLimit-iSXF8rLH.mjs";
14
+ import { n as arcRouteValidatorCompiler } from "./routeValidator-xNYA4rr1.mjs";
14
15
  import { isPaginatedResult, toCanonicalList } from "@classytic/repo-core/pagination";
15
16
  // src/core/fastifyAdapter.ts
16
17
  /** Type guard for Mongoose-like documents with toObject() */
@@ -650,6 +651,29 @@ function buildRateLimitConfig(rateLimit) {
650
651
  } };
651
652
  }
652
653
  // src/core/middlewares/registerRoute.ts
654
+ const SUPPORTED_RATE_OPTIONS = [
655
+ "max",
656
+ "timeWindow",
657
+ "keyGenerator",
658
+ "groupId",
659
+ "allowList"
660
+ ];
661
+ /** `@fastify/rate-limit` per-route options arc's limiter honours; any other option refuses. */
662
+ function routeRateHostOptions(policy, where) {
663
+ const fail = (problem) => /* @__PURE__ */ new Error(`[arc] ${where}: config.rateLimit.${problem}`);
664
+ for (const [option, value] of Object.entries(policy)) if (value !== void 0 && !SUPPORTED_RATE_OPTIONS.includes(option)) throw fail(`${option} is not supported on arc's resource limiter (supported: ${SUPPORTED_RATE_OPTIONS.join(", ")}). Remove it, or set it on the app-wide createApp({ rateLimit }).`);
665
+ const { keyGenerator, allowList, groupId } = policy;
666
+ if (keyGenerator !== void 0 && typeof keyGenerator !== "function") throw fail("keyGenerator must be a function of the request.");
667
+ if (allowList !== void 0 && typeof allowList !== "function" && !(Array.isArray(allowList) && allowList.every((key) => typeof key === "string"))) throw fail("allowList must be an array of keys or a function (req, key).");
668
+ if (groupId !== void 0 && (typeof groupId !== "string" || groupId.length === 0)) throw fail("groupId must be a non-empty string.");
669
+ return {
670
+ ...keyGenerator ? { keyGenerator } : {},
671
+ ...allowList ? { allowList } : {},
672
+ ...groupId ? { groupId } : {}
673
+ };
674
+ }
675
+ /** One group, one limit: a shared budget cannot be counted against two maxima. */
676
+ const groupLimits = /* @__PURE__ */ new WeakMap();
653
677
  /**
654
678
  * Register a route with friendly handling of `FST_ERR_DUPLICATED_ROUTE`.
655
679
  *
@@ -664,6 +688,8 @@ function buildRateLimitConfig(rateLimit) {
664
688
  function tryRegisterRoute(fastify, opts, context) {
665
689
  const ratePolicy = opts.config?.rateLimit;
666
690
  if (ratePolicy && typeof ratePolicy === "object" && typeof ratePolicy.max === "number" && typeof ratePolicy.timeWindow === "string") {
691
+ const where = `${String(opts.method)} ${opts.url} on resource "${context.resourceName}"`;
692
+ const host = routeRateHostOptions(ratePolicy, where);
667
693
  const limiter = resolveResourceRateLimiter(fastify);
668
694
  if (!limiter && !recordUnenforcedRateLimit(fastify, context.resourceName)) throw new Error(`[arc] Resource "${context.resourceName}" declares rateLimit; register @fastify/rate-limit before mounting the resource, or disable rate limiting for the app (createApp({ rateLimit: false })).`);
669
695
  if (!limiter) opts = {
@@ -677,13 +703,29 @@ function tryRegisterRoute(fastify, opts, context) {
677
703
  const policy = {
678
704
  max: ratePolicy.max,
679
705
  timeWindow: ratePolicy.timeWindow,
680
- bucket: context.rateLimitBucket
706
+ bucket: context.rateLimitBucket,
707
+ ...host.groupId ? { groupId: host.groupId } : {}
681
708
  };
709
+ if (host.groupId) {
710
+ const limits = groupLimits.get(limiter) ?? /* @__PURE__ */ new Map();
711
+ groupLimits.set(limiter, limits);
712
+ const declared = `${policy.max} per ${policy.timeWindow}`;
713
+ const prior = limits.get(host.groupId);
714
+ if (prior !== void 0 && prior !== declared) throw new Error(`[arc] ${where}: config.rateLimit.groupId "${host.groupId}" is declared with two different limits (${prior} and ${declared}); routes sharing a group must declare the same max and timeWindow.`);
715
+ limits.set(host.groupId, declared);
716
+ }
717
+ const { keyGenerator, allowList } = host;
682
718
  const handlers = Array.isArray(opts.preHandler) ? opts.preHandler : opts.preHandler ? [opts.preHandler] : [];
683
719
  const limit = async (req, reply) => {
720
+ const key = keyGenerator ? String(await keyGenerator(req)) : void 0;
721
+ if (allowList) {
722
+ const candidate = key ?? req.ip;
723
+ if (typeof allowList === "function" ? await allowList(req, candidate) : allowList.includes(candidate)) return;
724
+ }
684
725
  const decision = await limiter.consume(context.resourceName, policy, {
685
726
  scope: req.scope,
686
- ip: req.ip
727
+ ip: req.ip,
728
+ ...key !== void 0 ? { key } : {}
687
729
  });
688
730
  for (const [header, value] of Object.entries(decision.headers)) reply.header(header, value);
689
731
  if (!decision.allowed) {
@@ -764,4 +806,130 @@ function resolveActionPermission(input) {
764
806
  const updateFallback = resourcePermissions?.update;
765
807
  if (updateFallback) return updateFallback;
766
808
  }
767
- export { sendControllerResponse as C, getControllerScope as S, buildArcDecorator as _, resolveRouterPluginMw as a, createRequestContext as b, buildPipelineHandler as c, buildCrudPermissionMw as d, buildRouteHooks as f, buildAuthMiddlewareForPermissions as g, buildAuthMiddleware as h, buildRouteConfig as i, resolvePipelineSteps as l, routeHookOptions as m, tryRegisterRoute as n, selectPluginMw as o, resolveRoutePreHandlers as p, buildRateLimitConfig as r, buildActionPipelineHandler as s, resolveActionPermission as t, buildActionPermissionMw as u, createCrudHandlers as v, getControllerContext as x, createFastifyHandler as y };
809
+ // src/core/schemaIR.ts
810
+ /**
811
+ * Schema IR — one canonical representation, two adapters.
812
+ *
813
+ * arc's action-schema handling used to live in two parallel translators:
814
+ * `normalizeActionSchema()` in [createActionRouter.ts](./createActionRouter.ts)
815
+ * produced JSON Schema for AJV, and `convertActionSchemaToZod()` in
816
+ * [../integrations/mcp/action-tools.ts](../integrations/mcp/action-tools.ts)
817
+ * produced Zod shapes for MCP. Same input shape, two implementations — the
818
+ * exact drift pattern routerShared exists to eliminate.
819
+ *
820
+ * This module is the single source of truth: every caller normalizes to
821
+ * `SchemaIR` first, then emits whichever surface they need. If a future
822
+ * refactor adds a field to the IR (e.g. `propertyOrder`, `examples`),
823
+ * both adapters pick it up automatically.
824
+ *
825
+ * **The IR preserves `additionalProperties`.** The previous implementation
826
+ * dropped the flag during normalization, so `additionalProperties: false`
827
+ * silently no-opped even though [createActionRouter.ts:425-428](./createActionRouter.ts#L425-L428)
828
+ * documented it as the opt-in escape hatch for strict validation. The IR
829
+ * carries the flag verbatim; both adapters honor it.
830
+ */
831
+ /**
832
+ * Normalize anything the author handed us (Zod schema, plain JSON Schema,
833
+ * or `undefined`) into a canonical `SchemaIR`.
834
+ *
835
+ * Accepts:
836
+ * - `undefined` / non-object → empty IR (no properties, no required)
837
+ * - Zod v4 object schema — converted via `toJsonSchema` from the shared utility
838
+ * - Plain JSON Schema with `type: 'object'` or `properties`
839
+ *
840
+ * Anything that can't be read as an object schema collapses to an empty IR
841
+ * (no throw — the caller decides whether that's a validation error).
842
+ *
843
+ * @example
844
+ * ```ts
845
+ * normalizeSchemaIR({
846
+ * type: 'object',
847
+ * properties: { carrier: { type: 'string' } },
848
+ * required: ['carrier'],
849
+ * additionalProperties: false,
850
+ * });
851
+ * // → { properties: { carrier: { type: 'string' } }, required: ['carrier'], additionalProperties: false }
852
+ * ```
853
+ */
854
+ function normalizeSchemaIR(raw) {
855
+ if (!raw || typeof raw !== "object") return {
856
+ properties: {},
857
+ required: []
858
+ };
859
+ const converted = toJsonSchema(raw, "draft-7", "throw");
860
+ if (!converted || typeof converted !== "object" || converted.type !== "object" && !("properties" in converted)) return {
861
+ properties: {},
862
+ required: []
863
+ };
864
+ const properties = converted.properties ?? {};
865
+ const required = (Array.isArray(converted.required) ? converted.required : []).filter((field) => !("default" in (properties[field] ?? {})));
866
+ const additionalProperties = converted.additionalProperties;
867
+ return {
868
+ properties,
869
+ required,
870
+ ...additionalProperties !== void 0 ? { additionalProperties } : {}
871
+ };
872
+ }
873
+ /**
874
+ * An action schema's IR WITHOUT the `action` discriminator. Arc owns `action`:
875
+ * the router emits it (top-level enum, per-branch `const`), the MCP tool name
876
+ * carries it, and the handler's `data` never has it. A schema that declares it
877
+ * anyway (`z.strictObject({ action: z.literal('issue'), ... })`, one branch of
878
+ * a contracts discriminated union) must not override arc's: a declared
879
+ * `action` used to replace the top-level enum and, merged into the other
880
+ * branches, their `const`, so `oneOf` stopped discriminating. Strictness
881
+ * (`additionalProperties`) is kept as declared.
882
+ */
883
+ function actionSchemaIR(raw) {
884
+ const ir = normalizeSchemaIR(raw);
885
+ if (!("action" in ir.properties)) return ir;
886
+ const { action: _owned, ...properties } = ir.properties;
887
+ return {
888
+ ...ir,
889
+ properties,
890
+ required: ir.required.filter((f) => f !== "action")
891
+ };
892
+ }
893
+ /**
894
+ * Emit a JSON Schema branch from the IR, with optional extra properties
895
+ * merged in (e.g. the `action: { const: 'approve' }` discriminator added
896
+ * by `buildActionBodySchema`).
897
+ *
898
+ * Preserves `additionalProperties` verbatim — strict schemas (`false`)
899
+ * reach AJV intact, so HTTP validation rejects unknown fields before the
900
+ * handler runs. This closes the bug where the documented strict-mode
901
+ * escape hatch silently no-opped because normalization dropped the flag.
902
+ *
903
+ * `default` is stripped from each property schema. Zod v4's `z.toJSONSchema()`
904
+ * emits `default` for `.default()` fields, but AJV with `useDefaults: true`
905
+ * cannot apply defaults inside `oneOf` branches and throws a strict-mode error
906
+ * (`strict mode: default is ignored for: <path>`). The action router applies
907
+ * each action's own top-level defaults itself once the action is known
908
+ * (`collectActionDefaults` in createActionRouter.ts). OpenAPI passes
909
+ * `keepDefaults` so each branch documents its own defaults.
910
+ */
911
+ function schemaIRToJsonSchemaBranch(ir, extras = {}, keepDefaults = false) {
912
+ const mergedProperties = {};
913
+ for (const [key, prop] of Object.entries({
914
+ ...extras.properties ?? {},
915
+ ...ir.properties
916
+ })) if (!keepDefaults && typeof prop === "object" && prop !== null && "default" in prop) {
917
+ const { default: _dropped, ...rest } = prop;
918
+ mergedProperties[key] = rest;
919
+ } else mergedProperties[key] = prop;
920
+ return {
921
+ type: "object",
922
+ properties: mergedProperties,
923
+ required: [...extras.required ?? [], ...ir.required.filter((f) => !(extras.required ?? []).includes(f))],
924
+ ...ir.additionalProperties !== void 0 ? { additionalProperties: ir.additionalProperties } : {}
925
+ };
926
+ }
927
+ /**
928
+ * Returns `true` when the IR declares `additionalProperties: false`. MCP
929
+ * tool handlers should reject inputs with unknown keys when this is true,
930
+ * matching HTTP's AJV-level strict enforcement.
931
+ */
932
+ function shouldRejectAdditionalProperties(ir) {
933
+ return ir.additionalProperties === false;
934
+ }
935
+ export { createFastifyHandler as C, sendControllerResponse as D, getControllerScope as E, createCrudHandlers as S, getControllerContext as T, resolveRoutePreHandlers as _, resolveActionPermission as a, buildAuthMiddlewareForPermissions as b, buildRouteConfig as c, buildActionPipelineHandler as d, buildPipelineHandler as f, buildRouteHooks as g, buildCrudPermissionMw as h, shouldRejectAdditionalProperties as i, resolveRouterPluginMw as l, buildActionPermissionMw as m, normalizeSchemaIR as n, tryRegisterRoute as o, resolvePipelineSteps as p, schemaIRToJsonSchemaBranch as r, buildRateLimitConfig as s, actionSchemaIR as t, selectPluginMw as u, routeHookOptions as v, createRequestContext as w, buildArcDecorator as x, buildAuthMiddleware as y };
@@ -1,4 +1,4 @@
1
- /*! @classytic/arc v2.47.0 | MIT | https://classytic.com */
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
2
  import { errorContractSchema, errorDetailSchema } from "@classytic/repo-core/errors";
3
3
  import { Type, Type as Type$1 } from "typebox";
4
4
  // src/schemas/index.ts
@@ -1,5 +1,5 @@
1
- /*! @classytic/arc v2.47.0 | MIT | https://classytic.com */
2
- import { t as parseJsonBody } from "../jsonBody-CzDBkCme.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { t as parseJsonBody } from "../jsonBody-DoTt5BS6.mjs";
3
3
  import fp from "fastify-plugin";
4
4
  // src/scim/errors.ts
5
5
  var ScimError = class extends Error {
@@ -1,6 +1,6 @@
1
1
 
2
- import { A as requireOrgId, C as hasOrgAccess, D as isOrgInScope, E as isMember, M as requireUserId, N as scopeFirstCtx, O as isService, S as getUserRoles, T as isElevated, _ as getScopeContextMap, a as ScopeFirstCtx, b as getTenantFromRequest, c as getAncestorOrgIds, d as getMandate, f as getOrgContext, g as getScopeContext, h as getRequestScope, i as RequestScope, j as requireTeamId, k as requireClientId, l as getClientId, m as getOrgRoles, n as Mandate, o as ScopeFirstCtxOptions, p as getOrgId, r as PUBLIC_SCOPE, s as ScopeFirstCtxRequest, t as AUTHENTICATED_SCOPE, u as getDPoPJkt, v as getServiceScopes, w as isAuthenticated, x as getUserId, y as getTeamId } from "../types-DnkIALZ8.mjs";
3
2
  import { n as ElevationOptions, r as _default, t as ElevationEvent } from "../elevation-DPD0hcU-.mjs";
3
+ import { A as requireOrgId, C as hasOrgAccess, D as isOrgInScope, E as isMember, M as requireUserId, N as scopeFirstCtx, O as isService, S as getUserRoles, T as isElevated, _ as getScopeContextMap, a as ScopeFirstCtx, b as getTenantFromRequest, c as getAncestorOrgIds, d as getMandate, f as getOrgContext, g as getScopeContext, h as getRequestScope, i as RequestScope, j as requireTeamId, k as requireClientId, l as getClientId, m as getOrgRoles, n as Mandate, o as ScopeFirstCtxOptions, p as getOrgId, r as PUBLIC_SCOPE, s as ScopeFirstCtxRequest, t as AUTHENTICATED_SCOPE, u as getDPoPJkt, v as getServiceScopes, w as isAuthenticated, x as getUserId, y as getTeamId } from "../types-DnkIALZ8.mjs";
4
4
  import { FastifyReply, FastifyRequest } from "fastify";
5
5
  interface RateLimitKeyContext {
6
6
  ip: string;
@@ -1,6 +1,6 @@
1
- /*! @classytic/arc v2.47.0 | MIT | https://classytic.com */
2
- import { C as isService, D as requireUserId, E as requireTeamId, O as scopeFirstCtx, S as isOrgInScope, T as requireOrgId, _ as getUserRoles, a as getDPoPJkt, b as isElevated, c as getOrgId, d as getScopeContext, f as getScopeContextMap, g as getUserId, h as getTenantFromRequest, i as getClientId, l as getOrgRoles, m as getTeamId, n as PUBLIC_SCOPE, o as getMandate, p as getServiceScopes, r as getAncestorOrgIds, s as getOrgContext, t as AUTHENTICATED_SCOPE, u as getRequestScope, v as hasOrgAccess, w as requireClientId, x as isMember, y as isAuthenticated } from "../types-DZHqOuJE.mjs";
3
- import { t as createTenantKeyGenerator } from "../rateLimitKey-CWAjlqcN.mjs";
4
- import { t as elevation_default } from "../elevation-DrXeEWWk.mjs";
5
- import { t as resolveOrgFromHeader } from "../scope-BwVLSyNG.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { C as isService, D as requireUserId, E as requireTeamId, O as scopeFirstCtx, S as isOrgInScope, T as requireOrgId, _ as getUserRoles, a as getDPoPJkt, b as isElevated, c as getOrgId, d as getScopeContext, f as getScopeContextMap, g as getUserId, h as getTenantFromRequest, i as getClientId, l as getOrgRoles, m as getTeamId, n as PUBLIC_SCOPE, o as getMandate, p as getServiceScopes, r as getAncestorOrgIds, s as getOrgContext, t as AUTHENTICATED_SCOPE, u as getRequestScope, v as hasOrgAccess, w as requireClientId, x as isMember, y as isAuthenticated } from "../types-CrOlZ4rY.mjs";
3
+ import { t as createTenantKeyGenerator } from "../rateLimitKey-56nH1cWN.mjs";
4
+ import { t as elevation_default } from "../elevation-DupGuM41.mjs";
5
+ import { t as resolveOrgFromHeader } from "../scope-QyhM9w8z.mjs";
6
6
  export { AUTHENTICATED_SCOPE, PUBLIC_SCOPE, createTenantKeyGenerator, elevation_default as elevationPlugin, getAncestorOrgIds, getClientId, getDPoPJkt, getMandate, getOrgContext, getOrgId, getOrgRoles, getRequestScope, getScopeContext, getScopeContextMap, getServiceScopes, getTeamId, getTenantFromRequest, getUserId, getUserRoles, hasOrgAccess, isAuthenticated, isElevated, isMember, isOrgInScope, isService, requireClientId, requireOrgId, requireTeamId, requireUserId, resolveOrgFromHeader, scopeFirstCtx };
@@ -1,7 +1,7 @@
1
- /*! @classytic/arc v2.47.0 | MIT | https://classytic.com */
2
- import { a as OrgAccessDeniedError, l as UnauthorizedError } from "./errors-DnrUChAy.mjs";
3
- import { n as requireSingleHeaderValue } from "./headers-KxhrKevA.mjs";
4
- import { n as getUserRoles } from "./userHelpers-_eGj6kf0.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { a as OrgAccessDeniedError, l as UnauthorizedError } from "./errors-BpYV859Y.mjs";
3
+ import { n as requireSingleHeaderValue } from "./headers-D4bncIOf.mjs";
4
+ import { n as getUserRoles } from "./userHelpers-CBKx3XJN.mjs";
5
5
  // src/scope/resolveOrgFromHeader.ts
6
6
  /**
7
7
  * Create a preHandler hook that resolves org scope from a header.
@@ -1,4 +1,4 @@
1
- /*! @classytic/arc v2.47.0 | MIT | https://classytic.com */
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
3
  // src/utils/shutdown.ts
4
4
  /** Stop admissions across every runtime before draining work and disposing domain engines. */
@@ -1,40 +1,14 @@
1
- /*! @classytic/arc v2.47.0 | MIT | https://classytic.com */
2
- import { t as __exportAll } from "./rolldown-runtime-yH2lHMo_.mjs";
3
- import { t as arcLog } from "./logger-C110X5Yz.mjs";
4
- import { g as getUserId, n as PUBLIC_SCOPE } from "./types-DZHqOuJE.mjs";
5
- import { n as isEventVisible, t as eventAudienceOf } from "./tenancy-COrhjPRZ.mjs";
6
- import { a as promoteStreamTokenToHeader } from "./streaming-Dcgqa-hH.mjs";
7
- import { t as openSseStream } from "./sseStream-BjSo9Ult.mjs";
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { t as __exportAll } from "./rolldown-runtime-gKJR3o-6.mjs";
3
+ import { n as isEventVisible, t as eventAudienceOf } from "./tenancy-_ukT0oBt.mjs";
4
+ import { t as arcLog } from "./logger-UbknHqHy.mjs";
5
+ import { g as getUserId, n as PUBLIC_SCOPE } from "./types-CrOlZ4rY.mjs";
6
+ import { a as registerSseStats, r as openSseStream } from "./sseStream-BxQW7hPq.mjs";
7
+ import { a as promoteStreamTokenToHeader } from "./streaming-HZr63UiM.mjs";
8
8
  import fp from "fastify-plugin";
9
9
  // src/plugins/sse.ts
10
- var sse_exports = /* @__PURE__ */ __exportAll({
11
- default: () => sse_default,
12
- ssePlugin: () => ssePlugin
13
- });
10
+ var sse_exports = /* @__PURE__ */ __exportAll({ default: () => sse_default });
14
11
  const log = arcLog("sse");
15
- /** Per-registration stats providers behind one `sseStats` decorator. */
16
- const statsProviders = /* @__PURE__ */ new WeakMap();
17
- function registerStats(fastify, provider) {
18
- if (fastify.hasDecorator("sseStats")) {
19
- statsProviders.get(fastify.sseStats)?.add(provider);
20
- return;
21
- }
22
- const providers = /* @__PURE__ */ new Set([provider]);
23
- const sseStats = () => {
24
- const total = {
25
- connections: 0,
26
- keys: 0
27
- };
28
- for (const p of providers) {
29
- const s = p();
30
- total.connections += s.connections;
31
- total.keys += s.keys;
32
- }
33
- return total;
34
- };
35
- statsProviders.set(sseStats, providers);
36
- fastify.decorate("sseStats", sseStats);
37
- }
38
12
  const serializeEvent = (event) => JSON.stringify({
39
13
  type: event.type,
40
14
  payload: event.payload,
@@ -96,7 +70,7 @@ const ssePlugin = async (fastify, opts = {}) => {
96
70
  });
97
71
  return sharedSubscription;
98
72
  };
99
- registerStats(fastify, () => resolveAudience ? {
73
+ registerSseStats(fastify, () => resolveAudience ? {
100
74
  connections: connections.size,
101
75
  keys: byKey.size
102
76
  } : {
@@ -0,0 +1,112 @@
1
+
2
+ import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
3
+ interface SseStreamOptions {
4
+ /** Heartbeat comment interval in ms (default: 30000). */
5
+ heartbeatMs?: number;
6
+ /**
7
+ * Reconnection-delay hint written once at connect as the standard SSE
8
+ * `retry:` field (WHATWG EventSource honors it natively). Omit to send
9
+ * no hint (browser default ~3s).
10
+ */
11
+ retryMs?: number;
12
+ /**
13
+ * Bytes a client may leave unread in the response buffer before the
14
+ * connection is destroyed. Checked whenever a write finds the buffer full,
15
+ * against the bytes queued before that write, so a single frame larger than
16
+ * the budget still reaches a client that reads.
17
+ * Default 1 MiB. `0` restores the fail-fast rule of arc 2.48 and earlier:
18
+ * the first write that finds the buffer full destroys the connection.
19
+ */
20
+ maxBufferedBytes?: number;
21
+ /**
22
+ * How long a full buffer may wait for the socket's `drain` before the
23
+ * connection is destroyed, in ms. Default 10000.
24
+ */
25
+ drainTimeoutMs?: number;
26
+ }
27
+ /** Default {@link SseStreamOptions.maxBufferedBytes}: 1 MiB. */
28
+ declare const SSE_DEFAULT_MAX_BUFFERED_BYTES: number;
29
+ /** Default {@link SseStreamOptions.drainTimeoutMs}: 10 s. */
30
+ declare const SSE_DEFAULT_DRAIN_TIMEOUT_MS = 10000;
31
+ interface SseStream {
32
+ /**
33
+ * Write one SSE frame. `id` (optional) becomes the standard SSE `id:`
34
+ * field — clients receive it as `lastEventId` (WHATWG), enabling
35
+ * client-side dedup/resume bookkeeping even when the server keeps no
36
+ * replay log. Returns `false` when the stream is closed or the write
37
+ * exceeded the backpressure budget (the connection was destroyed and the
38
+ * stream is already cleaned up; stop writing). `true` means the frame was
39
+ * accepted, possibly into the buffer: check {@link needsDrain} to pace a burst.
40
+ */
41
+ write(eventName: string, data: string, id?: string): boolean;
42
+ /**
43
+ * Write an id-only frame (`id: <id>` and no `data:`). Under the WHATWG SSE
44
+ * rules it moves the client's `lastEventId` without firing an event, so a
45
+ * reconnect resumes after entries this client was not shown. Optional so a
46
+ * host's own `SseStream` double still type-checks; `openSseStream` has it.
47
+ * Same return contract as {@link write}.
48
+ */
49
+ writeId?(id: string): boolean;
50
+ /**
51
+ * `true` while the socket buffer is full and the stream waits for `drain`.
52
+ * A writer with a burst (a replay) awaits {@link drain} before writing more,
53
+ * so the burst never exceeds the byte budget. Optional so a host's own
54
+ * `SseStream` double still type-checks; `openSseStream` has it.
55
+ */
56
+ readonly needsDrain?: boolean;
57
+ /**
58
+ * Resolves `true` once the buffer has drained (at once when it is not full),
59
+ * `false` when the stream closed first (destroyed after `drainTimeoutMs`, the
60
+ * client left, or `close()`). Optional for the same reason as {@link needsDrain}.
61
+ */
62
+ drain?(): Promise<boolean>;
63
+ /** Idempotent teardown: heartbeat cleared, cleanups run, socket ended. */
64
+ close(): void;
65
+ /** Register teardown work (unsubscribes etc.) — runs exactly once. */
66
+ onCleanup(fn: () => void): void;
67
+ }
68
+ /**
69
+ * Take over the reply socket and open an SSE stream. Call ONLY after every
70
+ * gate (auth, permissions, validation) has passed — after `hijack()` no
71
+ * JSON error can be sent.
72
+ */
73
+ declare function openSseStream(request: FastifyRequest, reply: FastifyReply, options?: SseStreamOptions): SseStream;
74
+ /** Live connection gauge, summed across every registered SSE surface on the instance. */
75
+ interface SSEStats {
76
+ /** Open SSE connections. */
77
+ connections: number;
78
+ /** Distinct `connectionKey`s indexed (0 without `audience`). */
79
+ keys: number;
80
+ }
81
+ declare module "fastify" {
82
+ interface FastifyInstance {
83
+ sseStats: () => SSEStats;
84
+ }
85
+ }
86
+ /**
87
+ * Add a provider to `fastify.sseStats()`, decorating the instance on first use.
88
+ * Call at boot (see the module note: decorating after `ready` throws).
89
+ */
90
+ declare function registerSseStats(fastify: FastifyInstance, provider: () => SSEStats): void;
91
+ /** Counts the open streams of a host's own `openSseStream` routes. */
92
+ interface SseConnectionGauge {
93
+ /** Count `stream` until it closes. Call right after `openSseStream`; repeat calls are no-ops. */
94
+ track(stream: SseStream): void;
95
+ /** Streams currently tracked. */
96
+ size(): number;
97
+ }
98
+ /**
99
+ * A connection gauge for custom `openSseStream` routes, registered into
100
+ * `fastify.sseStats()`. Create it at boot (same rule as {@link registerSseStats}),
101
+ * then `gauge.track(stream)` in the route handler.
102
+ *
103
+ * ```ts
104
+ * const gauge = createSseConnectionGauge(app);
105
+ * app.get('/alerts/stream', async (req, reply) => {
106
+ * const stream = openSseStream(req, reply);
107
+ * gauge.track(stream);
108
+ * });
109
+ * ```
110
+ */
111
+ declare function createSseConnectionGauge(fastify: FastifyInstance): SseConnectionGauge;
112
+ export { SSE_DEFAULT_DRAIN_TIMEOUT_MS as a, SseStreamOptions as c, registerSseStats as i, openSseStream as l, SseConnectionGauge as n, SSE_DEFAULT_MAX_BUFFERED_BYTES as o, createSseConnectionGauge as r, SseStream as s, SSEStats as t };
@@ -0,0 +1,166 @@
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
+ import { n as forwardedStreamHeaders } from "./streaming-HZr63UiM.mjs";
3
+ // src/utils/sseStats.ts
4
+ /** Per-instance stats providers behind one `sseStats` decorator. */
5
+ const statsProviders = /* @__PURE__ */ new WeakMap();
6
+ /**
7
+ * Add a provider to `fastify.sseStats()`, decorating the instance on first use.
8
+ * Call at boot (see the module note: decorating after `ready` throws).
9
+ */
10
+ function registerSseStats(fastify, provider) {
11
+ if (fastify.hasDecorator("sseStats")) {
12
+ statsProviders.get(fastify.sseStats)?.add(provider);
13
+ return;
14
+ }
15
+ const providers = /* @__PURE__ */ new Set([provider]);
16
+ const sseStats = () => {
17
+ const total = {
18
+ connections: 0,
19
+ keys: 0
20
+ };
21
+ for (const p of providers) {
22
+ const s = p();
23
+ total.connections += s.connections;
24
+ total.keys += s.keys;
25
+ }
26
+ return total;
27
+ };
28
+ statsProviders.set(sseStats, providers);
29
+ fastify.decorate("sseStats", sseStats);
30
+ }
31
+ /**
32
+ * A connection gauge for custom `openSseStream` routes, registered into
33
+ * `fastify.sseStats()`. Create it at boot (same rule as {@link registerSseStats}),
34
+ * then `gauge.track(stream)` in the route handler.
35
+ *
36
+ * ```ts
37
+ * const gauge = createSseConnectionGauge(app);
38
+ * app.get('/alerts/stream', async (req, reply) => {
39
+ * const stream = openSseStream(req, reply);
40
+ * gauge.track(stream);
41
+ * });
42
+ * ```
43
+ */
44
+ function createSseConnectionGauge(fastify) {
45
+ const open = /* @__PURE__ */ new Set();
46
+ registerSseStats(fastify, () => ({
47
+ connections: open.size,
48
+ keys: 0
49
+ }));
50
+ return {
51
+ track(stream) {
52
+ if (open.has(stream)) return;
53
+ open.add(stream);
54
+ stream.onCleanup(() => open.delete(stream));
55
+ },
56
+ size: () => open.size
57
+ };
58
+ }
59
+ // src/utils/sseStream.ts
60
+ /** Default {@link SseStreamOptions.maxBufferedBytes}: 1 MiB. */
61
+ const SSE_DEFAULT_MAX_BUFFERED_BYTES = 1048576;
62
+ /** Default {@link SseStreamOptions.drainTimeoutMs}: 10 s. */
63
+ const SSE_DEFAULT_DRAIN_TIMEOUT_MS = 1e4;
64
+ /**
65
+ * Take over the reply socket and open an SSE stream. Call ONLY after every
66
+ * gate (auth, permissions, validation) has passed — after `hijack()` no
67
+ * JSON error can be sent.
68
+ */
69
+ function openSseStream(request, reply, options = {}) {
70
+ const { heartbeatMs = 3e4, retryMs, maxBufferedBytes = SSE_DEFAULT_MAX_BUFFERED_BYTES, drainTimeoutMs = SSE_DEFAULT_DRAIN_TIMEOUT_MS } = options;
71
+ if (!Number.isFinite(maxBufferedBytes) || maxBufferedBytes < 0) throw new Error(`openSseStream: maxBufferedBytes must be a number >= 0, got ${String(maxBufferedBytes)}.`);
72
+ if (!Number.isFinite(drainTimeoutMs) || drainTimeoutMs <= 0) throw new Error(`openSseStream: drainTimeoutMs must be a positive number, got ${String(drainTimeoutMs)}.`);
73
+ reply.hijack();
74
+ reply.raw.writeHead(200, {
75
+ "content-type": "text/event-stream",
76
+ "cache-control": "no-cache",
77
+ connection: "keep-alive",
78
+ "x-accel-buffering": "no",
79
+ ...forwardedStreamHeaders(reply)
80
+ });
81
+ reply.raw.flushHeaders();
82
+ if (retryMs !== void 0) reply.raw.write(`retry: ${retryMs}\n\n`);
83
+ const cleanups = [];
84
+ let closed = false;
85
+ /** The last write found the buffer full; cleared by the socket's `drain`. */
86
+ let needDrain = false;
87
+ let drainTimer;
88
+ let drainWaiters = [];
89
+ const settleDrainWaiters = (drained) => {
90
+ const waiters = drainWaiters;
91
+ drainWaiters = [];
92
+ for (const resolve of waiters) resolve(drained);
93
+ };
94
+ const onDrain = () => {
95
+ if (!needDrain) return;
96
+ needDrain = false;
97
+ if (drainTimer !== void 0) clearTimeout(drainTimer);
98
+ drainTimer = void 0;
99
+ settleDrainWaiters(true);
100
+ };
101
+ const close = () => {
102
+ if (closed) return;
103
+ closed = true;
104
+ clearInterval(heartbeatTimer);
105
+ if (drainTimer !== void 0) clearTimeout(drainTimer);
106
+ drainTimer = void 0;
107
+ reply.raw.off?.("drain", onDrain);
108
+ settleDrainWaiters(false);
109
+ for (const fn of cleanups) try {
110
+ fn();
111
+ } catch {}
112
+ if (!reply.raw.writableEnded) reply.raw.end();
113
+ };
114
+ const destroyOnBackpressure = (context) => {
115
+ request.raw.destroy(/* @__PURE__ */ new Error(`SSE connection terminated: ${context} backpressure`));
116
+ close();
117
+ };
118
+ /**
119
+ * Write a chunk. A full buffer is tolerated within the byte budget while a
120
+ * `drain` is awaited for at most `drainTimeoutMs`; past either budget the
121
+ * connection is destroyed and `false` returned.
122
+ */
123
+ const send = (chunk, context) => {
124
+ if (closed) return false;
125
+ const prior = reply.raw.writableLength;
126
+ if (reply.raw.write(chunk)) return true;
127
+ if (maxBufferedBytes === 0 || typeof prior === "number" && prior > maxBufferedBytes) {
128
+ destroyOnBackpressure(context);
129
+ return false;
130
+ }
131
+ if (!needDrain) {
132
+ needDrain = true;
133
+ drainTimer = setTimeout(() => destroyOnBackpressure(`${context} (no drain within ${drainTimeoutMs} ms)`), drainTimeoutMs);
134
+ drainTimer.unref?.();
135
+ }
136
+ return true;
137
+ };
138
+ reply.raw.on?.("drain", onDrain);
139
+ const heartbeatTimer = setInterval(() => {
140
+ if (closed || needDrain) return;
141
+ send(": heartbeat\n\n", "heartbeat");
142
+ }, heartbeatMs);
143
+ request.raw.on("close", close);
144
+ return {
145
+ write(eventName, data, id) {
146
+ const idField = id !== void 0 ? `id: ${id}\n` : "";
147
+ return send(`${idField}event: ${eventName}\ndata: ${data}\n\n`, "slow client");
148
+ },
149
+ writeId(id) {
150
+ return send(`id: ${id}\n\n`, "slow client");
151
+ },
152
+ get needsDrain() {
153
+ return needDrain && !closed;
154
+ },
155
+ drain() {
156
+ if (closed) return Promise.resolve(false);
157
+ if (!needDrain) return Promise.resolve(true);
158
+ return new Promise((resolve) => drainWaiters.push(resolve));
159
+ },
160
+ close,
161
+ onCleanup(fn) {
162
+ cleanups.push(fn);
163
+ }
164
+ };
165
+ }
166
+ export { registerSseStats as a, createSseConnectionGauge as i, SSE_DEFAULT_MAX_BUFFERED_BYTES as n, openSseStream as r, SSE_DEFAULT_DRAIN_TIMEOUT_MS as t };
@@ -1,4 +1,4 @@
1
- /*! @classytic/arc v2.47.0 | MIT | https://classytic.com */
1
+ /*! @classytic/arc v2.49.0 | MIT | https://classytic.com */
2
2
  // src/utils/store-helpers.ts
3
3
  /**
4
4
  * Classify an error thrown by `getOne` / `getById` / `update` as a