@classytic/arc 2.48.0 → 2.50.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 (213) hide show
  1. package/dist/{EventTransport-BWwg5YAU.mjs → EventTransport-B18mcj_M.mjs} +2 -2
  2. package/dist/{HookSystem-B9x-Y_k7.mjs → HookSystem-FUBaLTRm.mjs} +2 -2
  3. package/dist/{QueryCache-DdvrGG8Q.d.mts → QueryCache-BE47tmlO.d.mts} +36 -1
  4. package/dist/{ResourceRegistry-BcvEJoZd.mjs → ResourceRegistry-C5NM07fZ.mjs} +2 -2
  5. package/dist/{acquire-D2yj6Zzl.mjs → acquire-MHCnbDtH.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-BZSJcPNE.mjs → authorizationDecision-BD8K4jdQ.mjs} +4 -4
  13. package/dist/{boundedMap-o2KZDCWy.mjs → boundedMap-CuCwos_X.mjs} +1 -1
  14. package/dist/{buildHandler-G3k59KY2.mjs → buildHandler-BttjNkTM.mjs} +23 -16
  15. package/dist/cache/index.d.mts +2 -2
  16. package/dist/cache/index.mjs +4 -4
  17. package/dist/{caching-CJIDPZOv.mjs → caching-CxUQLHfR.mjs} +3 -6
  18. package/dist/{claimed-D0A43wjT.mjs → claimed-CQ4ZpD8K.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-D-faL5SX.mjs → constants-BZFsZwJh.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-NSu1peyq.mjs → core-DWA1-5IE.mjs} +3 -3
  34. package/dist/{createActionRouter-DTSVv1VK.mjs → createActionRouter-fP3l2xVF.mjs} +54 -18
  35. package/dist/{createAggregationRouter-zEasm-ax.mjs → createAggregationRouter-BJZeOmBa.mjs} +13 -11
  36. package/dist/{createApp-CjqhkX1x.mjs → createApp-Db9JRumw.mjs} +332 -40
  37. package/dist/{createMcpServer-hSFeqRUb.d.mts → createMcpServer-CS2KOVP6.d.mts} +1 -1
  38. package/dist/{defineAggregation-DH2L6_v9.mjs → defineAggregation-BskqRz8M.mjs} +1 -1
  39. package/dist/{defineResource-zYCrhNaN.mjs → defineResource-B2vTvKzW.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-z--rFcZ5.mjs → elevation-XoY0C73T.mjs} +6 -9
  44. package/dist/encryption/index.mjs +3 -3
  45. package/dist/{errorHandler-3_3oN-Uc.mjs → errorHandler-BYI-JQMm.mjs} +4 -7
  46. package/dist/{errors-DyY48oRi.mjs → errors-3xaK0i9n.mjs} +1 -1
  47. package/dist/{eventPlugin-Co9sABCg.mjs → eventPlugin-CVQ9ddnL.mjs} +9 -13
  48. package/dist/{eventTypes-HmAFyJmJ.mjs → eventTypes-UPYg7gW1.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-CxRvCaaZ.mjs +80 -0
  58. package/dist/{fields-rfsl26Ov.mjs → fields-DLFcJiDe.mjs} +1 -1
  59. package/dist/{filter-merge-8glLr7Dk.mjs → filter-merge-Bvjk_8dV.mjs} +1 -1
  60. package/dist/{generate-BOfBueRt.mjs → generate-0OpCUjUv.mjs} +2 -2
  61. package/dist/{headers-CHSOqpcY.mjs → headers-BROW65-r.mjs} +2 -2
  62. package/dist/{health-ezwTHQh2.mjs → health-Cfh-kYI_.mjs} +1 -1
  63. package/dist/{health-DHvAIVmM.mjs → health-Cy6aOg1i.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-MoE3eZNR.mjs → init-D7PQcvvL.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 +5 -5
  87. package/dist/integrations/mcp/index.mjs +2 -2
  88. package/dist/integrations/mcp/testing.d.mts +2 -2
  89. package/dist/integrations/mcp/testing.mjs +2 -2
  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-DZGiCawf.mjs → jsonBody-C0oREwUc.mjs} +2 -2
  97. package/dist/{keys-CrMOZuk6.mjs → keys-CGlPoVSn.mjs} +1 -1
  98. package/dist/{loadResources-CVQvYUhN.mjs → loadResources-Oi47dogA.mjs} +3 -3
  99. package/dist/{loadResourcesFromEntry-D0naccV2.mjs → loadResourcesFromEntry-BW-LexBz.mjs} +2 -2
  100. package/dist/logger/index.mjs +2 -2
  101. package/dist/{logger-VyMcSmVG.mjs → logger-BagW7_YA.mjs} +1 -1
  102. package/dist/{mcpPlugin-DQACaqVu.mjs → mcpPlugin-C6-wFsOX.mjs} +29 -26
  103. package/dist/{memory-Lpfu8Hga.mjs → memory-Bl7kv6TS.mjs} +3 -3
  104. package/dist/{metrics-DjVj1sg5.mjs → metrics-CqnMJKrJ.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-BqPJpZ_L.mjs → module-lbEbHUfI.mjs} +1 -1
  109. package/dist/{multiTenant-KZj8j1uJ.d.mts → multiTenant-QtDzxx_K.d.mts} +1 -1
  110. package/dist/{multipartBody-BNgNv7r0.mjs → multipartBody-CqNezaB3.mjs} +1 -1
  111. package/dist/{observeSend-BKJHibJz.mjs → observeSend-BjilzlYl.mjs} +1 -1
  112. package/dist/{openapi-T90KrPR6.mjs → openapi-DXNbadgd.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-5Mnwcycy.d.mts → outbox-module-DzW6zwWJ.d.mts} +103 -10
  116. package/dist/{outbox-module-C874VgBr.mjs → outbox-module-k5rIszQ4.mjs} +197 -28
  117. package/dist/permissions/index.d.mts +2 -2
  118. package/dist/permissions/index.mjs +7 -7
  119. package/dist/{permissions-R9T2G1PH.mjs → permissions-BJylQopQ.mjs} +9 -9
  120. package/dist/{pipe-DzqbsZy-.mjs → pipe-D1cq8hET.mjs} +2 -2
  121. package/dist/pipeline/index.d.mts +1 -1
  122. package/dist/pipeline/index.mjs +2 -2
  123. package/dist/{plan-C0gkeABY.mjs → plan-iEgaS5_H.mjs} +1 -1
  124. package/dist/{plugin-BJcVOX5r.mjs → plugin-DsLr6L4O.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-CrCpyoZs.mjs → pluralize-CX4ZvwCa.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-CNDvNYsz.mjs → presets-D_suT4OY.mjs} +4 -4
  139. package/dist/{projection-CIUe8b59.mjs → projection-CmjGjFih.mjs} +2 -2
  140. package/dist/{purger.types-f83fTzGy.mjs → purger.types-CZwkTZ7B.mjs} +1 -1
  141. package/dist/{queryCachePlugin-B2jpwFcv.mjs → queryCachePlugin-BDOPEAmH.mjs} +114 -14
  142. package/dist/{queryCachePlugin-DYQUyeJ9.d.mts → queryCachePlugin-DrQNnGws.d.mts} +1 -1
  143. package/dist/{rateLimitKey-BWx-qep0.mjs → rateLimitKey-igF1x64n.mjs} +1 -1
  144. package/dist/{realtime-D2tqi3d2.mjs → realtime-Cq_ugiWw.mjs} +75 -22
  145. package/dist/registry/index.d.mts +2 -2
  146. package/dist/registry/index.mjs +3 -3
  147. package/dist/{registry-Dl0k6UXy.mjs → registry-DmF9Akvn.mjs} +2 -2
  148. package/dist/{relay-ZYvS4xyW.mjs → relay-DA89IhFt.mjs} +200 -99
  149. package/dist/{renewingLease-DT4yLb29.mjs → renewingLease-DBtGUt8T.mjs} +1 -1
  150. package/dist/{replyHelpers-BJFN5AW7.mjs → replyHelpers-CUbeUc5q.mjs} +2 -2
  151. package/dist/{requestContext-Ct5la-SA.mjs → requestContext-DO9Qv0gw.mjs} +1 -1
  152. package/dist/{requirement-CxDxjB6V.mjs → requirement-C3GaQmkR.mjs} +1 -1
  153. package/dist/{resourceRateLimit-DCWglD7V.d.mts → resourceRateLimit-BPiESPtG.d.mts} +4 -0
  154. package/dist/{resourceRateLimit-D1oH2obv.mjs → resourceRateLimit-KKn-sFhb.mjs} +19 -4
  155. package/dist/{rolldown-runtime-BdTN42uL.mjs → rolldown-runtime-Ck1Tj4Ax.mjs} +1 -1
  156. package/dist/{routeValidator-DclDl5WJ.mjs → routeValidator-BF7n34xV.mjs} +47 -5
  157. package/dist/{runtimeCapabilities-ClWr60El.mjs → runtimeCapabilities-D0A4kkrC.mjs} +1 -1
  158. package/dist/{schedules-gVkRcs-9.mjs → schedules-CLrQRSTt.mjs} +6 -9
  159. package/dist/{schemaConverter-CIwB5wPO.mjs → schemaConverter-JEmU21fu.mjs} +2 -2
  160. package/dist/{actionPermissions-Dha8sAz2.mjs → schemaIR-wOffQlbq.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-VMZhdkbT.mjs → scope-CcTMRd7s.mjs} +4 -4
  166. package/dist/{shutdown-Bi19vH0z.mjs → shutdown-BIR-QBYM.mjs} +1 -1
  167. package/dist/{simpleEqualityMatcher-CaCS09fh.mjs → simpleEqualityMatcher-DqqJqovq.mjs} +1 -1
  168. package/dist/{sse-BqM359f1.mjs → sse-OEuPpgss.mjs} +9 -35
  169. package/dist/sseStats-DQqNN385.d.mts +112 -0
  170. package/dist/sseStream-DknHE2K5.mjs +166 -0
  171. package/dist/{store-helpers-rx-F2ZGR.mjs → store-helpers-D4vtEXt2.mjs} +1 -1
  172. package/dist/{streaming-CPChx3A7.mjs → streaming-CcIpcx02.mjs} +1 -1
  173. package/dist/{subscriberIdentity-CYNYw8p_.mjs → subscriberIdentity-PO6kimAl.mjs} +1 -1
  174. package/dist/{tenancy-BoWImS3K.mjs → tenancy-CH2Kuksc.mjs} +2 -2
  175. package/dist/{tenantPreparation-oqKCZQZM.mjs → tenantPreparation-BTGpblQW.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-Dsteq59c.mjs → timing-Dii5X7AP.mjs} +1 -1
  183. package/dist/{transactionContext-C1OgH-hW.mjs → transactionContext-DMPhYEOt.mjs} +1 -1
  184. package/dist/{typeGuards-DNlpASzd.mjs → typeGuards-C1o_XEyp.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-DduBiYaI.d.mts → types-B4E0sc6D.d.mts} +2 -2
  189. package/dist/{types-HFFSwF_K.mjs → types-BuV_cFqT.mjs} +4 -4
  190. package/dist/usage/index.d.mts +1 -1
  191. package/dist/usage/index.mjs +7 -7
  192. package/dist/{userHelpers-N-k-8dNF.mjs → userHelpers-D4m_pLSC.mjs} +1 -1
  193. package/dist/utils/index.d.mts +193 -34
  194. package/dist/utils/index.mjs +13 -13
  195. package/dist/{utils-C7w_RVlx.mjs → utils-CxLMXGn5.mjs} +761 -8
  196. package/dist/{validate-Brr4b_fH.mjs → validate-CZ975J8N.mjs} +3 -3
  197. package/dist/{versioning-S18y2-0C.d.mts → versioning-B07RgD27.d.mts} +2 -13
  198. package/dist/{versioning-CE5kdWOY.mjs → versioning-B2_8SBZo.mjs} +4 -7
  199. package/dist/{workScope-A3XBpYTa.mjs → workScope-B3W3r35s.mjs} +2 -2
  200. package/llms.txt +2 -2
  201. package/package.json +34 -34
  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/production-api.md +4 -0
  207. package/skills/arc/references/production-boot.md +2 -0
  208. package/skills/arc/references/production-idempotency.md +1 -1
  209. package/skills/arc/references/production-realtime.md +28 -2
  210. package/skills/arc/references/validation.md +4 -0
  211. package/skills/arc/references/writes-hooks-errors.md +1 -0
  212. package/dist/schemaIR-A0IoD05P.mjs +0 -108
  213. package/dist/sseStream-qSa-F2Qm.mjs +0 -57
@@ -1,6 +1,6 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { t as __exportAll } from "./rolldown-runtime-BdTN42uL.mjs";
3
- import { x as pathTouchesBlocked } from "./plugin-BJcVOX5r.mjs";
1
+ /*! @classytic/arc v2.50.0 | MIT | https://classytic.com */
2
+ import { t as __exportAll } from "./rolldown-runtime-Ck1Tj4Ax.mjs";
3
+ import { x as pathTouchesBlocked } from "./plugin-DsLr6L4O.mjs";
4
4
  // src/core/aggregation/normalize.ts
5
5
  /**
6
6
  * Framework cap on URL-driven aggregation limits when the host opts
@@ -1,5 +1,6 @@
1
1
 
2
2
  import { n as DomainEvent } from "./EventTransport-CYEoCJGe.mjs";
3
+ import "./sseStats-DQqNN385.mjs";
3
4
  import { FastifyPluginAsync, FastifyRequest } from "fastify";
4
5
  interface GracefulShutdownOptions {
5
6
  /** Maximum time to wait for graceful shutdown in ms (default: 30000) */
@@ -125,18 +126,6 @@ interface SSEOptions {
125
126
  /** Key a connection is indexed under for `audience` (default: scope user id; none = broadcasts only). */
126
127
  connectionKey?: (request: FastifyRequest) => string | null | undefined;
127
128
  }
128
- /** Live connection gauge, summed across every `ssePlugin` registration on the instance. */
129
- interface SSEStats {
130
- /** Open SSE connections. */
131
- connections: number;
132
- /** Distinct `connectionKey`s indexed (0 without `audience`). */
133
- keys: number;
134
- }
135
- declare module "fastify" {
136
- interface FastifyInstance {
137
- sseStats: () => SSEStats;
138
- }
139
- }
140
129
  declare const _default$3: FastifyPluginAsync<SSEOptions>;
141
130
  declare const CHANGE_OPERATIONS: readonly ["created", "updated", "deleted"];
142
131
  type ChangeOperation = (typeof CHANGE_OPERATIONS)[number];
@@ -251,4 +240,4 @@ declare module "fastify" {
251
240
  }
252
241
  }
253
242
  declare const _default: FastifyPluginAsync<VersioningOptions>;
254
- export { ShutdownState as _, MetricsOptions as a, RealtimeOptions as c, SSEStats as d, _default$3 as f, GracefulShutdownOptions as g, _default$4 as h, MetricsCollector as i, _default$2 as l, CachingRule as m, _default as n, _default$1 as o, CachingOptions as p, MetricEntry as r, ChangeOperation as s, VersioningOptions as t, SSEOptions as u, _default$5 as v };
243
+ export { _default$5 as _, MetricsOptions as a, RealtimeOptions as c, _default$3 as d, CachingOptions as f, ShutdownState as g, GracefulShutdownOptions as h, MetricsCollector as i, _default$2 as l, _default$4 as m, _default as n, _default$1 as o, CachingRule as p, MetricEntry as r, ChangeOperation as s, VersioningOptions as t, SSEOptions as u };
@@ -1,12 +1,9 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { t as __exportAll } from "./rolldown-runtime-BdTN42uL.mjs";
3
- import { d as createDomainError } from "./errors-DyY48oRi.mjs";
1
+ /*! @classytic/arc v2.50.0 | MIT | https://classytic.com */
2
+ import { t as __exportAll } from "./rolldown-runtime-Ck1Tj4Ax.mjs";
3
+ import { d as createDomainError } from "./errors-3xaK0i9n.mjs";
4
4
  import fp from "fastify-plugin";
5
5
  // src/plugins/versioning.ts
6
- var versioning_exports = /* @__PURE__ */ __exportAll({
7
- default: () => versioning_default,
8
- versioningPlugin: () => versioningPlugin
9
- });
6
+ var versioning_exports = /* @__PURE__ */ __exportAll({ default: () => versioning_default });
10
7
  const PREFIX_REGEX = /^\/v(\d+)\//;
11
8
  const versioningPlugin = async (fastify, opts) => {
12
9
  const { type, defaultVersion = "1", headerName = "accept-version", responseHeader = "x-api-version", versions, deprecated = [], sunset } = opts;
@@ -1,5 +1,5 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { n as requestContext } from "./requestContext-Ct5la-SA.mjs";
1
+ /*! @classytic/arc v2.50.0 | MIT | https://classytic.com */
2
+ import { n as requestContext } from "./requestContext-DO9Qv0gw.mjs";
3
3
  // src/context/workScope.ts
4
4
  /** Enter a scope for `fn`, or run it inside the active one. */
5
5
  function runWorkScope(seed, fn) {
package/llms.txt CHANGED
@@ -22,7 +22,7 @@ Hand-rolling is a bug in arc apps. Check this table before writing any route, va
22
22
  | Usage counters, quotas, plan limits | @classytic/arc/usage: usagePlugin, requireQuota; rateLimit.plan |
23
23
  | Audit, record history | audit: true, history: true |
24
24
  | Idempotency | @classytic/arc/idempotency |
25
- | Events, outbox, webhooks | @classytic/arc/events, createOutboxModule, integrations/webhooks |
25
+ | Events, outbox, webhooks, SSE replay | @classytic/arc/events, createOutboxModule, integrations/webhooks, createReplayHub |
26
26
  | AI / MCP tools | generated per resource; mcpPlugin from @classytic/arc/mcp |
27
27
  | Unknown route 404 | built in: ErrorContract arc.not_found (errorHandler.notFound to replace) |
28
28
  | Tests | createTestApp, expectArc from @classytic/arc/testing |
@@ -31,7 +31,7 @@ Hand-rolling is a bug in arc apps. Check this table before writing any route, va
31
31
  ## Read next
32
32
 
33
33
  - skills/arc/SKILL.md: golden paths, gotchas, reference index
34
- - skills/arc/references/: one topic per file (validation, schedules, resources, permissions, auth, events, mcp, production, testing)
34
+ - skills/arc/references/: topics (validation, schedules, resources, permissions, auth, events, mcp, production, tests)
35
35
  - skills/arc-code-review/SKILL.md: audit a codebase for hand-rolled code
36
36
  - skills/arc-module-publishing/SKILL.md: ship a reusable arc module
37
37
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classytic/arc",
3
- "version": "2.48.0",
3
+ "version": "2.50.0",
4
4
  "description": "Resource-oriented backend framework for Fastify - clean, minimal, powerful, tree-shakable",
5
5
  "type": "module",
6
6
  "exports": {
@@ -378,8 +378,8 @@
378
378
  "node": ">=22"
379
379
  },
380
380
  "peerDependencies": {
381
- "@classytic/primitives": ">=0.35.0",
382
- "@classytic/repo-core": ">=0.35.0",
381
+ "@classytic/primitives": ">=0.36.0",
382
+ "@classytic/repo-core": ">=0.38.0",
383
383
  "@classytic/streamline": ">=2.12.0",
384
384
  "@fastify/cors": ">=11.0.0",
385
385
  "@fastify/helmet": ">=13.0.0",
@@ -400,9 +400,9 @@
400
400
  "@opentelemetry/instrumentation-http": ">=0.50.0",
401
401
  "@opentelemetry/instrumentation-mongodb": ">=0.40.0",
402
402
  "@opentelemetry/sdk-node": ">=0.50.0",
403
- "better-auth": ">=1.7.14",
404
- "bullmq": ">=6.5.1",
405
- "fastify": ">=5.12.7",
403
+ "better-auth": ">=1.7.15",
404
+ "bullmq": ">=6.5.4",
405
+ "fastify": ">=5.12.8",
406
406
  "fastify-raw-body": ">=6.0.3",
407
407
  "h3-js": ">=4.0.0",
408
408
  "ioredis": ">=6.0.0",
@@ -508,58 +508,58 @@
508
508
  },
509
509
  "devDependencies": {
510
510
  "@arethetypeswrong/cli": "^0.18.5",
511
- "@better-auth/drizzle-adapter": "^1.7.10",
512
- "@better-auth/mongo-adapter": "^1.7.10",
513
- "@biomejs/biome": "^2.6.3",
511
+ "@better-auth/drizzle-adapter": "^1.7.15",
512
+ "@better-auth/mongo-adapter": "^1.7.15",
513
+ "@biomejs/biome": "^2.6.4",
514
514
  "@classytic/dev-tools": "^0.2.1",
515
515
  "@classytic/gitkit": ">=0.3.0",
516
- "@classytic/mongokit": "^3.43.1",
516
+ "@classytic/mongokit": "^3.44.0",
517
517
  "@classytic/pgkit": "^0.1.1",
518
- "@classytic/primitives": "^0.35.0",
519
- "@classytic/repo-core": "^0.35.0",
520
- "@classytic/sqlitekit": "^0.12.0",
518
+ "@classytic/primitives": "^0.36.0",
519
+ "@classytic/repo-core": "^0.38.0",
520
+ "@classytic/sqlitekit": "^0.13.0",
521
521
  "@classytic/streamline": "^2.12.0",
522
- "@electric-sql/pglite": "^0.5.10",
523
- "@fastify/cors": "^11.3.1",
522
+ "@electric-sql/pglite": "^0.5.15",
523
+ "@fastify/cors": "^11.4.0",
524
524
  "@fastify/helmet": "^13.2.0",
525
- "@fastify/jwt": "^10.2.5",
526
- "@fastify/multipart": "^10.1.4",
527
- "@fastify/rate-limit": "^11.2.1",
525
+ "@fastify/jwt": "^10.2.7",
526
+ "@fastify/multipart": "^10.1.7",
527
+ "@fastify/rate-limit": "^11.2.2",
528
528
  "@fastify/sensible": "^6.0.7",
529
- "@fastify/static": "^10.1.6",
529
+ "@fastify/static": "^10.1.8",
530
530
  "@fastify/type-provider-typebox": "^6.3.0",
531
531
  "@fastify/under-pressure": "^9.2.1",
532
- "@fastify/websocket": "^11.3.4",
532
+ "@fastify/websocket": "^11.3.6",
533
533
  "@modelcontextprotocol/client": "^2.4.0",
534
534
  "@modelcontextprotocol/node": "^2.1.2",
535
535
  "@modelcontextprotocol/server": "^2.4.0",
536
- "@opentelemetry/api": "^1.9.1",
537
- "@types/node": "^26.6.5",
536
+ "@opentelemetry/api": "^1.10.0",
537
+ "@types/node": "^26.6.6",
538
538
  "@types/qs": "^6.15.1",
539
- "@vitest/coverage-v8": "^5.0.5",
539
+ "@vitest/coverage-v8": "^5.1.0",
540
540
  "ajv": "^8.20.0",
541
- "better-auth": "^1.7.14",
541
+ "better-auth": "^1.7.15",
542
542
  "better-sqlite3": "^13.0.3",
543
- "bullmq": "^6.5.1",
544
- "dotenv": "^18.0.8",
543
+ "bullmq": "^6.5.4",
544
+ "dotenv": "^18.0.9",
545
545
  "drizzle-orm": "^0.45.4",
546
546
  "fast-check": "^4.10.2",
547
- "fastify": "^5.12.7",
547
+ "fastify": "^5.12.8",
548
548
  "fastify-raw-body": "^6.0.3",
549
549
  "h3-js": "^4.5.0",
550
550
  "ioredis": "^6.0.0",
551
- "jose": "^6.2.12",
551
+ "jose": "^6.2.15",
552
552
  "jsonwebtoken": "^9.0.3",
553
- "knip": "^6.43.0",
554
- "mongodb": "^7.7.0",
553
+ "knip": "^6.44.1",
554
+ "mongodb": "~7.7.0",
555
555
  "mongodb-memory-server": "^11.3.0",
556
556
  "mongoose": "^9.11.4",
557
557
  "publint": "^0.3.25",
558
- "tsdown": "^0.23.3",
559
- "typebox": "^1.4.2",
558
+ "tsdown": "^0.23.4",
559
+ "typebox": "^1.4.3",
560
560
  "typescript": "~7.0.2",
561
- "vitest": "^5.0.5",
562
- "ws": "^8.22.0",
561
+ "vitest": "^5.1.0",
562
+ "ws": "^8.22.1",
563
563
  "zod": "^4.6.7"
564
564
  },
565
565
  "config": {
@@ -16,7 +16,7 @@ Import only from these subpaths (tree-shaken, no deep imports). Authoritative li
16
16
  | `/events` | `eventPlugin`, `MemoryEventTransport`, `defineEvent`, `createEventRegistry`, `withRetry`, `withInbox`, `withSubscriberId`, `wrapWithSchema`, `subscribeWithSchema`, `wrapWithBoundary`, `subscribeWithBoundary`, `createDeadLetterPublisher`, `EventOutbox`, `MemoryOutboxStore`, `repositoryAsOutboxStore`, `createOutboxModule`, `exponentialBackoff`, `readOutboxHealth`, `crudEventType`, `ARC_LIFECYCLE_EVENTS` |
17
17
  | `/events/redis`, `/events/redis-stream` | `RedisEventTransport`, `RedisStreamTransport` |
18
18
  | `/outbox-admin` | `createOutboxAdminModule` |
19
- | `/plugins` | `healthPlugin`, `gracefulShutdownPlugin`, `ssePlugin`, `metricsPlugin`, `versioningPlugin`, `schedulesPlugin`, `cachingPlugin`, `pressurePlugin`, `realtimePlugin`, `requestIdPlugin`, `errorHandlerPlugin`, `createPlugin`, `createDailyGate`, `createMemoryDailyLedger`; types `DailyLedger`, `DailyScheduleOptions`, `ScheduleRunContext`, `ScheduleDefinition` |
19
+ | `/plugins` | `healthPlugin`, `gracefulShutdownPlugin`, `ssePlugin`, `metricsPlugin`, `versioningPlugin`, `schedulesPlugin`, `cachingPlugin`, `pressurePlugin`, `realtimePlugin`, `requestIdPlugin`, `errorHandlerPlugin`, `createPlugin`, `createDailyGate`, `createMemoryDailyLedger`, `registerSseStats`, `createSseConnectionGauge`; types `DailyLedger`, `DailyScheduleOptions`, `ScheduleRunContext`, `ScheduleDefinition` |
20
20
  | `/plugins/tracing`, `/plugins/response-cache` | `tracingPlugin`, `traced`, `createSpan`; `responseCachePlugin` |
21
21
  | `/audit` | `auditPlugin`, `MemoryAuditStore`, `repositoryAsAuditStore`, `createAuditEntry` |
22
22
  | `/idempotency` (+ `/idempotency/redis`) | `idempotencyPlugin`, `MemoryIdempotencyStore`, `repositoryAsIdempotencyStore`, `IdempotencyStoreMisconfiguredError`; `RedisIdempotencyStore` |
@@ -25,7 +25,7 @@ Import only from these subpaths (tree-shaken, no deep imports). Authoritative li
25
25
  | `/context`, `/logger` | `requestContext`, `transactionContext`, `runWorkScope`; `arcLog`, `configureArcLogger` |
26
26
  | `/registry`, `/discovery`, `/docs` | `ResourceRegistry`, `introspectionPlugin`; `discoverResources`; `openApiPlugin`, `scalarPlugin`, `buildOpenApiSpec` |
27
27
  | `/schemas` | `Type`, `ArcListResponse`, `ArcErrorResponse`, `ArcPaginationQuery` |
28
- | `/utils` | `createStateMachine`, `CircuitBreaker`, `withCompensation`, `defineGuard`, `declareRuntimeCapability`, `createQueryParser`, `ArcQueryParser`, `createError`, `pipeUIMessageStreamToReply`, `listResponse`, `errorContractSchema`, error classes |
28
+ | `/utils` | `createStateMachine`, `CircuitBreaker`, `withCompensation`, `defineGuard`, `declareRuntimeCapability`, `createQueryParser`, `ArcQueryParser`, `createError`, `pipeUIMessageStreamToReply`, `openSseStream`, `createReplayHub`, `lastEventIdOf`, `registerSseStats`, `createSseConnectionGauge`, `listResponse`, `errorContractSchema`, error classes |
29
29
  | `/migrations` | `defineMigration`, `MigrationRunner`, `MigrationRegistry`, `MongoMigrationStore` |
30
30
  | `/cleanup` | `createDataCleanupModule`, `createCleanupService`, `createCleanupRegistry`, `recipeFromSteps` |
31
31
  | `/encryption` | `encryptionPlugin`, `encryptField`, `decryptField`, `createStaticKeyProvider` |
@@ -68,6 +68,7 @@ BA stores several roles in one `member.role` string. Arc reads `scope.orgRoles`
68
68
  - Redis sessions: BA `secondaryStorage` (sessions skip the DB unless `session.storeSessionInDatabase: true`). Arc's `RedisSessionStore` (`@classytic/arc/auth/redis`) belongs to `createSessionManager`, a different layer. Do not mix.
69
69
  - BA `session.cookieCache` never caches custom session fields such as `activeOrganizationId`, so scope cannot go stale, but the org lookup still runs.
70
70
  - BA has its own limiter (`rateLimit.storage: 'secondary-storage'`). Exempt it from arc's bucket: `rateLimit: { skipPaths: ['/api/auth/*'] }`.
71
+ - BA JSON refusals (status >= 400) from `/api/auth/*` gain `status` and `correlationId` (`request.id`) when absent, like arc's own errors. Other responses pass through byte-identical. Drop any host `onSend` that added them.
71
72
 
72
73
  ## Bearer transport (SPA, mobile)
73
74
 
@@ -32,14 +32,17 @@ const app = await createApp({
32
32
  | `transport` | Default: the app's raw event transport (not the `app.events` facade) |
33
33
  | `name` | Module name and `dependsOn` key (default `'outbox'`) |
34
34
  | `relayEveryMs` | Default 5000 |
35
- | `batchSize`, `leaseMs`, `consumerId` | Relay tuning; `consumerId` defaults to a per-instance unique id |
35
+ | `batchSize`, `leaseMs`, `consumerId` | Relay tuning; `consumerId` defaults to a per-instance unique id. `leaseMs` must exceed one publish + ack, not a batch: claims shrink to fit the lease. A repository page `maxLimit` below `batchSize` warns `OUTBOX_CLAIM_CAPPED` once and `batchSize` drops to the store's `claimCap` |
36
+ | `maxPassesPerTick` | Default 1. Above 1, a tick (and `requestDrain`) keeps relaying while the last pass claimed and relayed something (a claim capped below `batchSize` does not stop it); an empty or all-failed pass stops. Replaces hand-rolled `relayBatch` loops |
36
37
  | `failurePolicy` | `({ attempts, error }) => { retryAt } \| { deadLetter: true }`. Set one: without it failed rows retry every poll forever |
37
- | `onError` | Per-event relay problems (default: structured logger) |
38
+ | `onError` | Per-event relay problems (default: structured logger; lost leases log one `OUTBOX_LEASE_LOST` warning per pass, then back off) |
38
39
  | `sessionProvider` | Default `() => transactionContext.get()`; `false` opts out |
39
40
  | `runOnStart` | Drain backlog at boot (default true) |
40
41
  | `health` | Readiness check `<name>.relay` + log alerts; `false` disables. `{ relayLagUnhealthyMs, probeCacheMs, alertEveryMs }` |
41
42
 
42
- Exports at `getModuleExports<OutboxModuleExports>(app, 'outbox')`: `store`, `relay` (an `EventOutbox`), `requestDrain()` (coalesced, call after commit), `drain({ maxPasses })` (await in tests), `health()`.
43
+ Exports at `getModuleExports<OutboxModuleExports>(app, 'outbox')`: `store`, `relay` (an `EventOutbox`), `requestDrain({ types? })` (coalesced, call after commit; `types` = a priority pass for those event types ahead of the backlog, published once by the relay), `drain({ maxPasses })` (await in tests), `health()`.
44
+
45
+ Passes are single-flight: a `requestDrain` during a pass queues one follow-up, a tick waits instead of overlapping. Typed drains run in their own lane. A pass publishes a claimed row only while its lease has budget left and acks it at once; rows past the budget stay leased and are re-claimed after expiry, never published twice by one relay. Leave `batchSize` at its default on a slow store.
43
46
 
44
47
  ## Writing
45
48
 
@@ -59,7 +62,7 @@ await outbox.store(
59
62
  ```typescript
60
63
  const outbox = new EventOutbox({ repository: repo, transport, failurePolicy, batchSize: 100, leaseMs: 30000 });
61
64
  const r = await outbox.relayBatch();
62
- // { relayed, attempted, publishFailed, ackFailed, ownershipMismatches, malformed, failHookErrors, deadLettered, usedPublishMany }
65
+ // { relayed, attempted, publishFailed, ackFailed, ownershipMismatches, malformed, failHookErrors, deadLettered, usedPublishMany, leaseDeferred? }
63
66
  const dead = await outbox.getDeadLettered(100); // DeadLetteredEvent[]
64
67
  await outbox.purge(olderThanMs); // delivered rows
65
68
  ```
@@ -104,7 +104,7 @@ await subscribeWithBoundary(app, 'cache.*', invalidate); // log and swallow,
104
104
  | Helper | Use |
105
105
  |---|---|
106
106
  | `withSubscriberId(id, handler)` | Stable per-handler identity for durable per-handler progress (never an index) |
107
- | `withInbox(name, handler, { store, leaseMs?, transaction? })` | Run a handler once per event id; `store` is a repo-core `IdempotencyClaimStore`; handler gets `{ session, eventId }` |
107
+ | `withInbox(name, handler, { store, leaseMs?, transaction? })` | Run a handler once per event id; `store` is a repo-core `IdempotencyClaimStore`; handler gets `{ session, eventId }`; `transaction` covers only writes made with that `session` (omit it when a handler writes elsewhere) |
108
108
  | `createDeadLetterPublisher(app.events)` | Handler that publishes exhausted events to `$deadLetter`; pass as `onDead` or `deadLetter` |
109
109
 
110
110
  Dead-letter contract: a transport may implement `deadLetter(dlq: DeadLetteredEvent)`.
@@ -114,7 +114,7 @@ Dead-letter contract: a transport may implement `deadLetter(dlq: DeadLetteredEve
114
114
  | Transport | Import | Use |
115
115
  |---|---|---|
116
116
  | `MemoryEventTransport` | `@classytic/arc/events` | Dev, tests, one process |
117
- | `RedisEventTransport(redis, { channel, externalLifecycle, logger })` | `@classytic/arc/events/redis` | Pub/Sub, fire-and-forget, live fan-out |
117
+ | `RedisEventTransport(redis, { channel, externalLifecycle, logger, subscribeTimeoutMs, publishTimeoutMs })` | `@classytic/arc/events/redis` | Pub/Sub, fire-and-forget, live fan-out; Redis down: subscribe returns after 2 s (queued), publish rejects after 5 s then at once until ready |
118
118
  | `RedisStreamTransport(redis, opts)` | `@classytic/arc/events/redis-stream` | Persistent, consumer groups, replay, DLQ stream |
119
119
 
120
120
  Streams options: `stream` ('arc:events'), `group` ('default'), `consumer`, `blockTimeMs` (5000), `batchSize` (10), `processingConcurrency` (1, keeps order), `maxRetries` (5), `claimTimeoutMs` (30000), `deadLetterStream` ('arc:events:dlq' or `false`), `maxLen` (0), `groupStart` ('latest' | 'beginning'), `maxPayloadBytes` (1 MB), `externalLifecycle`.
@@ -84,6 +84,10 @@ createApp({
84
84
 
85
85
  Pre-auth paths see the public scope and key by IP: exempt them with `skipPaths`. Per-resource budgets: `defineResource({ rateLimit })`.
86
86
 
87
+ Shared store down (`redis`/`store`): every call is bounded (`storeFallback.timeoutMs`, 250) and an error or timeout is answered from per-instance memory counters (still limited, never hangs or 500s); one warning per outage, probed every `retryAfterMs` (5000), resumes on its first answer; `storeFallback.onStatus` reports each switch for a health/metrics signal. `storeFallback: false` = the plugin's own behaviour.
88
+
89
+ A route's raw `config: { rateLimit: { max, timeWindow, keyGenerator, groupId, allowList } }` runs on arc's resource limiter (same headers, same 429 `arc.rate_limited`). `keyGenerator(req)` replaces the scope/IP key (per device behind one NAT address); `allowList` (keys or `(req, key) => boolean`) skips the limit; `groupId` shares one budget across routes and resources (one group, one `max`/`timeWindow`). Any other option refuses to register.
90
+
87
91
  ## Bulk preset
88
92
 
89
93
  ```typescript
@@ -26,6 +26,7 @@ await app.listen({ port: 3000, host: '0.0.0.0' });
26
26
  | `trustProxy` | `true`, CIDR string/array, or `'loopback'`. Unset behind a proxy makes `request.ip` the proxy |
27
27
  | `keepAliveTimeout` | Default 72000; keep above the LB idle timeout or you get intermittent 502 |
28
28
  | `requestTimeout`, `connectionTimeout`, `bodyLimit`, `maxParamLength` | Fastify pass-through (body 1 MiB, param 400) |
29
+ | `http` | Node server options pass-through: `highWaterMark`, `maxHeaderSize`, `requireHostHeader`, `joinDuplicateHeaders`, `noDelay`, `keepAlive*` |
29
30
  | `underPressure` | Production preset sets `maxEventLoopDelay: 3000`; override `{ maxEventLoopDelay: 500 }`, disable `false` |
30
31
  | `strictResourceDir`, `strictResources` | Throw on empty discovery or duplicate resource names; turn on in production |
31
32
  | `resourceDir: import.meta.url` | Works from `src/` and `dist/`; a path string resolves against `process.cwd()` |
@@ -62,6 +63,7 @@ export default { fetch: toFetchHandler(app) };
62
63
 
63
64
  ## CORS
64
65
 
66
+ - Unset `methods` → arc's verbs (`GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS`), not `@fastify/cors`'s `GET,HEAD,POST`, when `origin` is an explicit allow-list (string, array, RegExp). `origin: true` or a function keeps `GET,HEAD,POST` (boot warning with `credentials: true`). Any resolved list that omits a verb your routes use (e.g. `origin: true` without credentials vs CRUD `PATCH`/`DELETE`) logs one `onReady` warning naming the verbs.
65
67
  - Production without `cors.origin` warns. `origin: '*'` with `credentials: true` throws at boot; use an allow-list.
66
68
  - Arc merges its headers (`x-organization-id`, `x-arc-scope`, `x-request-id`) into a declared `allowedHeaders` list and always exposes its own response headers.
67
69
  - Mobile webviews (Capacitor, Ionic): add webview origins and expose the Better Auth bearer header.
@@ -74,7 +74,7 @@ repository: new Repository(IdempotencyModel, [methodRegistryPlugin(), batchOpera
74
74
 
75
75
  ## IdempotencyStore contract
76
76
 
77
- Required: `name`, `get`, `set`, `tryLock`, `unlock`, `isLocked`, `delete`, `deleteByPrefix`, `findByPrefix`. Optional: `acquire` (atomic check-and-lock), `setIfLocked` (fenced completion), `supportsFencedCompletion`, `completionReleasesLock`, `close`. A custom store without fencing needs `allowUnfencedCompletion: true`.
77
+ Required: `name`, `get`, `set`, `tryLock`, `unlock`, `isLocked`, `delete`, `deleteByPrefix`, `findByPrefix`. Optional: `acquire` (atomic check-and-lock), `setIfLocked` (fenced completion), `supportsFencedCompletion`, `completionReleasesLock`, `close`. A custom store without fencing needs `allowUnfencedCompletion: true`. `unlock` after a non-2xx must leave no claim behind (the repository store deletes a result-less row it locks).
78
78
 
79
79
  ## Gotchas
80
80
 
@@ -22,7 +22,7 @@ const app = await createApp({
22
22
  - `GET /realtime/:resource` (resource name) and multiplexed `GET /realtime?resources=a,b,c` (max 20).
23
23
  - Gated by the resource's own `list` permission; per-event row filtering, tenant guard, field masking.
24
24
  - Client: plain `EventSource` with `?token=` (`tokenQueryParam`, default `token`, `null` disables).
25
- - No replay: on reconnect, refetch the list.
25
+ - No replay: on reconnect, refetch the list. For a resumable stream use `createReplayHub` (below).
26
26
  - Permission filters are snapshotted at connect. The feed closes at token `exp` and at `maxConnectionMs` (default 30 min) to bound staleness.
27
27
 
28
28
  ## SSE plugin
@@ -46,7 +46,33 @@ const app = await createApp({
46
46
 
47
47
  - Events without `organizationId` reach every caller. An elevated admin with no active org sees all tenants.
48
48
  - `orgScoped: false` only for a deliberately cross-tenant stream; keep `requireAuth` and add a `filter`.
49
- - `fastify.sseStats()` returns `{ connections, keys }`.
49
+ - `fastify.sseStats()` returns `{ connections, keys }`, summed over ssePlugin, realtime feeds, replay hubs and `createSseConnectionGauge(app)` (custom routes call `gauge.track(stream)`). Register at boot: `decorate` after ready throws.
50
+
51
+ ## Resumable custom stream (replay over a ChangeLogStore)
52
+
53
+ ```typescript
54
+ import { createReplayHub, lastEventIdOf, openSseStream } from '@classytic/arc/utils';
55
+
56
+ const hub = createReplayHub(app, { // at boot, before ready
57
+ store, // repo-core ChangeLogStore (mongokit createChangeLogStore, MemoryChangeLogStore)
58
+ readScope: (ctx) => ({ tenantId: ctx.orgId, scopes: ['alerts'] }), // tail partition + since() filter
59
+ toFrame: (entry, ctx) => (canSee(ctx, entry) ? { event: 'alert', data: entry.doc } : null),
60
+ isValidCursor: (c) => /^\d{16}$/.test(c),
61
+ compareCursors: (a, b) => (a < b ? -1 : a > b ? 1 : 0),
62
+ revalidate: { everyMs: 15_000, check: (ctx, { memo }) => stillAllowed(ctx, memo), maxConsecutiveFailures: 3 }, // null/undefined/false → revoked; { close: 'revoke' | 'retry', reason }
63
+ identify: (ctx) => ({ userId: ctx.userId, sessionId: ctx.sessionId }),
64
+ revokeVia: { secret: env.REALTIME_REVOKE_SECRET }, // hub.revoke() reaches every replica, sealed (AES-GCM)
65
+ });
66
+ await app.events.subscribe('alert.*', () => hub.notify()); // the bus only WAKES the tail
67
+ // route, after every gate:
68
+ await hub.attach(openSseStream(req, reply), ctx, lastEventIdOf(req));
69
+ ```
70
+
71
+ - Frames: `ready {cursor, resumed}` first, then the replay or one `resync {cursor, reason}`, then live (`id:` = cursor). `revoked {reason}` then close (final). `retry {reason}` then close (not final: reconnect now). Names: `STREAM_FRAMES` from `@classytic/repo-core/sync` (the contract owner; `@classytic/arc-next/sse` reads the same one).
72
+ - `openSseStream` waits for `drain` (`maxBufferedBytes` 1 MiB, `drainTimeoutMs` 10 s; `0` bytes = old fail-fast); the hub paces a replay on `needsDrain`/`drain()`, so a large resume is not cut.
73
+ - A live entry the replay already sent goes out once. Entries hidden by `toFrame` are followed by an id-only frame, so the client cursor keeps up.
74
+ - Gap over `maxReplay` (500) → `gap_too_large`; `CursorExpiredError` → `cursor_expired`; invalid or ahead → `cursor_invalid`. Other store errors close with no frame.
75
+ - mongokit `compactSuperseded` keeps only the latest entry per doc, so replay yields latest state; a foreign cursor throws there, so set `isValidCursor`.
50
76
 
51
77
  ## Streaming custom routes
52
78
 
@@ -38,6 +38,7 @@ routes: [{
38
38
 
39
39
  - A failed parse is `400 arc.validation_error` with `details[]` (`path`, `message`), the same wire as an AJV failure.
40
40
  - A plain JSON Schema slot is AJV-only (no preHandler is added for it).
41
+ - AJV coerces querystring, params and headers only. JSON bodies are validated as sent (`"5"` for a number is a 400; `false` under `anyOf [number, boolean]` stays `false`). `createApp({ ajv: { coerceBody: true } })` opts back in.
41
42
  - `parsed(schema, value)` is a typing helper: it does not parse again.
42
43
  - `headers` and `response` are schema-only.
43
44
 
@@ -72,6 +73,8 @@ actions: {
72
73
 
73
74
  `noPayloadSchema` is plain JSON Schema (`additionalProperties: false`): any stray field is a 400.
74
75
 
76
+ Arc owns `action`: `data` never carries it. A schema may still declare it (a contracts union branch, `z.strictObject({ action: z.literal('close'), ... })`): arc keeps its own discriminator for AJV, OpenAPI and MCP, and `parse: true` parses with `action` put back, then drops it from `data`.
77
+
75
78
  ## The wrapper pitfall
76
79
 
77
80
  An action's `schema` IS the body schema. `schema: { body: X }` has no `type` or `properties`, arc reads it as empty, and the action accepts anything with no error.
@@ -88,4 +91,5 @@ schema: z.object({ note: z.string() }) // right
88
91
  - `customSchemas` parts replace generated parts; untouched parts keep auto-generation. Model-required fields the server fills: `schemaOptions.fieldRules: { f: { systemManaged: true } }`.
89
92
  - Unconvertible zod in a validation slot (`z.date()`, `z.bigint()`, custom checks) fails boot: use the wire form (`z.iso.datetime()`, `z.string()`) and convert in the handler.
90
93
  - A `.refine()` is not enforced by AJV: it needs `routeInput` / `parse: true`, or do it in the handler.
94
+ - Your own error code for a refinement: tag the issue (`ctx.addIssue({ ..., params: { code } })`) and pass `routeInput(slots, { mapIssues })` / `crudInput({ ..., mapIssues })`, returning an `ArcError` (or `undefined` for the default 400).
91
95
  - A thrown raw `ZodError` from your own `.parse()` is not mapped to a 400 by arc; use `routeInput` or throw `ValidationError`.
@@ -21,6 +21,7 @@ defineResource({
21
21
  - Retry belongs to the kit (`transactionRetry`); arc never stacks a second policy.
22
22
  - Boot fails without `withTransaction`, and at registration when `capabilities.transactions !== true` (standalone Mongo, D1).
23
23
  - `ctx.uow.session` is empty on connection-bound backends (SQLite): use the tx-bound repository.
24
+ - With `concurrency` set, a stale `If-Match` is 412 before `writes.update` runs. The verb gets `ctx.expectedVersion` (`ctx.expectedVersionSource`: `'if-match'` or `'loaded'`) and must CAS with it, e.g. mongokit `repo.claimVersion(id, { from: ctx.expectedVersion }, update, session)`; on a miss throw `VersionConflictError` (412 under If-Match, else 409). A conflict whose `id` names another document stays 409.
24
25
 
25
26
  ## Hooks
26
27
 
@@ -1,108 +0,0 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { o as toJsonSchema } from "./schemaConverter-CIwB5wPO.mjs";
3
- // src/core/schemaIR.ts
4
- /**
5
- * Schema IR — one canonical representation, two adapters.
6
- *
7
- * arc's action-schema handling used to live in two parallel translators:
8
- * `normalizeActionSchema()` in [createActionRouter.ts](./createActionRouter.ts)
9
- * produced JSON Schema for AJV, and `convertActionSchemaToZod()` in
10
- * [../integrations/mcp/action-tools.ts](../integrations/mcp/action-tools.ts)
11
- * produced Zod shapes for MCP. Same input shape, two implementations — the
12
- * exact drift pattern routerShared exists to eliminate.
13
- *
14
- * This module is the single source of truth: every caller normalizes to
15
- * `SchemaIR` first, then emits whichever surface they need. If a future
16
- * refactor adds a field to the IR (e.g. `propertyOrder`, `examples`),
17
- * both adapters pick it up automatically.
18
- *
19
- * **The IR preserves `additionalProperties`.** The previous implementation
20
- * dropped the flag during normalization, so `additionalProperties: false`
21
- * silently no-opped even though [createActionRouter.ts:425-428](./createActionRouter.ts#L425-L428)
22
- * documented it as the opt-in escape hatch for strict validation. The IR
23
- * carries the flag verbatim; both adapters honor it.
24
- */
25
- /**
26
- * Normalize anything the author handed us (Zod schema, plain JSON Schema,
27
- * or `undefined`) into a canonical `SchemaIR`.
28
- *
29
- * Accepts:
30
- * - `undefined` / non-object → empty IR (no properties, no required)
31
- * - Zod v4 object schema — converted via `toJsonSchema` from the shared utility
32
- * - Plain JSON Schema with `type: 'object'` or `properties`
33
- *
34
- * Anything that can't be read as an object schema collapses to an empty IR
35
- * (no throw — the caller decides whether that's a validation error).
36
- *
37
- * @example
38
- * ```ts
39
- * normalizeSchemaIR({
40
- * type: 'object',
41
- * properties: { carrier: { type: 'string' } },
42
- * required: ['carrier'],
43
- * additionalProperties: false,
44
- * });
45
- * // → { properties: { carrier: { type: 'string' } }, required: ['carrier'], additionalProperties: false }
46
- * ```
47
- */
48
- function normalizeSchemaIR(raw) {
49
- if (!raw || typeof raw !== "object") return {
50
- properties: {},
51
- required: []
52
- };
53
- const converted = toJsonSchema(raw, "draft-7", "throw");
54
- if (!converted || typeof converted !== "object" || converted.type !== "object" && !("properties" in converted)) return {
55
- properties: {},
56
- required: []
57
- };
58
- const properties = converted.properties ?? {};
59
- const required = (Array.isArray(converted.required) ? converted.required : []).filter((field) => !("default" in (properties[field] ?? {})));
60
- const additionalProperties = converted.additionalProperties;
61
- return {
62
- properties,
63
- required,
64
- ...additionalProperties !== void 0 ? { additionalProperties } : {}
65
- };
66
- }
67
- /**
68
- * Emit a JSON Schema branch from the IR, with optional extra properties
69
- * merged in (e.g. the `action: { const: 'approve' }` discriminator added
70
- * by `buildActionBodySchema`).
71
- *
72
- * Preserves `additionalProperties` verbatim — strict schemas (`false`)
73
- * reach AJV intact, so HTTP validation rejects unknown fields before the
74
- * handler runs. This closes the bug where the documented strict-mode
75
- * escape hatch silently no-opped because normalization dropped the flag.
76
- *
77
- * `default` is stripped from each property schema. Zod v4's `z.toJSONSchema()`
78
- * emits `default` for `.default()` fields, but AJV with `useDefaults: true`
79
- * cannot apply defaults inside `oneOf` branches and throws a strict-mode error
80
- * (`strict mode: default is ignored for: <path>`). Runtime defaults are applied
81
- * by Zod parsing at the handler layer anyway, so the keyword is a no-op for AJV.
82
- * The OpenAPI doc path uses a separate `openapi-3.0` target and is unaffected.
83
- */
84
- function schemaIRToJsonSchemaBranch(ir, extras = {}) {
85
- const mergedProperties = {};
86
- for (const [key, prop] of Object.entries({
87
- ...extras.properties ?? {},
88
- ...ir.properties
89
- })) if (typeof prop === "object" && prop !== null && "default" in prop) {
90
- const { default: _dropped, ...rest } = prop;
91
- mergedProperties[key] = rest;
92
- } else mergedProperties[key] = prop;
93
- return {
94
- type: "object",
95
- properties: mergedProperties,
96
- required: [...extras.required ?? [], ...ir.required.filter((f) => !(extras.required ?? []).includes(f))],
97
- ...ir.additionalProperties !== void 0 ? { additionalProperties: ir.additionalProperties } : {}
98
- };
99
- }
100
- /**
101
- * Returns `true` when the IR declares `additionalProperties: false`. MCP
102
- * tool handlers should reject inputs with unknown keys when this is true,
103
- * matching HTTP's AJV-level strict enforcement.
104
- */
105
- function shouldRejectAdditionalProperties(ir) {
106
- return ir.additionalProperties === false;
107
- }
108
- export { schemaIRToJsonSchemaBranch as n, shouldRejectAdditionalProperties as r, normalizeSchemaIR as t };
@@ -1,57 +0,0 @@
1
- /*! @classytic/arc v2.48.0 | MIT | https://classytic.com */
2
- import { n as forwardedStreamHeaders } from "./streaming-CPChx3A7.mjs";
3
- // src/utils/sseStream.ts
4
- /**
5
- * Take over the reply socket and open an SSE stream. Call ONLY after every
6
- * gate (auth, permissions, validation) has passed — after `hijack()` no
7
- * JSON error can be sent.
8
- */
9
- function openSseStream(request, reply, options = {}) {
10
- const { heartbeatMs = 3e4, retryMs } = options;
11
- reply.hijack();
12
- reply.raw.writeHead(200, {
13
- "content-type": "text/event-stream",
14
- "cache-control": "no-cache",
15
- connection: "keep-alive",
16
- "x-accel-buffering": "no",
17
- ...forwardedStreamHeaders(reply)
18
- });
19
- reply.raw.flushHeaders();
20
- if (retryMs !== void 0) reply.raw.write(`retry: ${retryMs}\n\n`);
21
- const cleanups = [];
22
- let closed = false;
23
- const close = () => {
24
- if (closed) return;
25
- closed = true;
26
- clearInterval(heartbeatTimer);
27
- for (const fn of cleanups) try {
28
- fn();
29
- } catch {}
30
- if (!reply.raw.writableEnded) reply.raw.end();
31
- };
32
- const destroyOnBackpressure = (context) => {
33
- request.raw.destroy(/* @__PURE__ */ new Error(`SSE connection terminated: ${context} backpressure`));
34
- close();
35
- };
36
- const heartbeatTimer = setInterval(() => {
37
- if (closed) return;
38
- if (!reply.raw.write(": heartbeat\n\n")) destroyOnBackpressure("heartbeat");
39
- }, heartbeatMs);
40
- request.raw.on("close", close);
41
- return {
42
- write(eventName, data, id) {
43
- if (closed) return false;
44
- const idField = id !== void 0 ? `id: ${id}\n` : "";
45
- if (!reply.raw.write(`${idField}event: ${eventName}\ndata: ${data}\n\n`)) {
46
- destroyOnBackpressure("slow client");
47
- return false;
48
- }
49
- return true;
50
- },
51
- close,
52
- onCleanup(fn) {
53
- cleanups.push(fn);
54
- }
55
- };
56
- }
57
- export { openSseStream as t };