@classytic/arc 2.48.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.
- package/dist/{EventTransport-BWwg5YAU.mjs → EventTransport-DbHZK230.mjs} +2 -2
- package/dist/{HookSystem-B9x-Y_k7.mjs → HookSystem-DMoeJ6Do.mjs} +2 -2
- package/dist/{QueryCache-DdvrGG8Q.d.mts → QueryCache-BE47tmlO.d.mts} +36 -1
- package/dist/{ResourceRegistry-BcvEJoZd.mjs → ResourceRegistry-CP-iTcKy.mjs} +2 -2
- package/dist/{acquire-D2yj6Zzl.mjs → acquire-CB0va87C.mjs} +1 -1
- package/dist/audit/index.d.mts +1 -1
- package/dist/audit/index.mjs +4 -4
- package/dist/auth/audit.mjs +1 -1
- package/dist/auth/index.d.mts +2 -2
- package/dist/auth/index.mjs +53 -15
- package/dist/auth/redis-session.mjs +1 -1
- package/dist/{authorizationDecision-BZSJcPNE.mjs → authorizationDecision-DHO94aV2.mjs} +4 -4
- package/dist/{boundedMap-o2KZDCWy.mjs → boundedMap-C51EUUOm.mjs} +1 -1
- package/dist/{buildHandler-G3k59KY2.mjs → buildHandler-9DuwEKvr.mjs} +23 -16
- package/dist/cache/index.d.mts +2 -2
- package/dist/cache/index.mjs +4 -4
- package/dist/{caching-CJIDPZOv.mjs → caching-COTX3sDa.mjs} +3 -6
- package/dist/{claimed-D0A43wjT.mjs → claimed-C7T1nHlo.mjs} +1 -1
- package/dist/cleanup/index.d.mts +2 -2
- package/dist/cleanup/index.mjs +4 -4
- package/dist/cli/commands/describe.d.mts +1 -1
- package/dist/cli/commands/describe.mjs +3 -3
- package/dist/cli/commands/docs.mjs +3 -3
- package/dist/cli/commands/doctor.mjs +1 -1
- package/dist/cli/commands/generate.mjs +2 -2
- package/dist/cli/commands/init.mjs +2 -2
- package/dist/cli/commands/introspect.mjs +2 -2
- package/dist/cli/index.mjs +3 -3
- package/dist/{constants-D-faL5SX.mjs → constants-DOnfMd7i.mjs} +1 -1
- package/dist/context/index.mjs +5 -5
- package/dist/core/index.d.mts +3 -3
- package/dist/core/index.mjs +7 -7
- package/dist/{core-NSu1peyq.mjs → core-BoEdFDDw.mjs} +3 -3
- package/dist/{createActionRouter-DTSVv1VK.mjs → createActionRouter-CpTn15dm.mjs} +54 -18
- package/dist/{createAggregationRouter-zEasm-ax.mjs → createAggregationRouter-CD_Hydp0.mjs} +13 -11
- package/dist/{createApp-CjqhkX1x.mjs → createApp-Be6XTGD9.mjs} +332 -40
- package/dist/{createMcpServer-hSFeqRUb.d.mts → createMcpServer-CS2KOVP6.d.mts} +1 -1
- package/dist/{defineAggregation-DH2L6_v9.mjs → defineAggregation-BI5pRb8c.mjs} +1 -1
- package/dist/{defineResource-zYCrhNaN.mjs → defineResource-BAzNu5Um.mjs} +8 -8
- package/dist/discovery/index.mjs +1 -1
- package/dist/docs/index.d.mts +1 -1
- package/dist/docs/index.mjs +3 -3
- package/dist/{elevation-z--rFcZ5.mjs → elevation-DupGuM41.mjs} +6 -9
- package/dist/encryption/index.mjs +3 -3
- package/dist/{errorHandler-3_3oN-Uc.mjs → errorHandler-DA03vRqp.mjs} +4 -7
- package/dist/{errors-DyY48oRi.mjs → errors-BpYV859Y.mjs} +1 -1
- package/dist/{eventPlugin-Co9sABCg.mjs → eventPlugin-D7LYtYzL.mjs} +9 -13
- package/dist/{eventTypes-HmAFyJmJ.mjs → eventTypes-BqA-N-Uz.mjs} +2 -2
- package/dist/events/index.d.mts +18 -5
- package/dist/events/index.mjs +8 -8
- package/dist/events/transports/redis-stream-entry.mjs +4 -4
- package/dist/events/transports/redis.d.mts +35 -0
- package/dist/events/transports/redis.mjs +87 -11
- package/dist/factory/index.d.mts +4 -4
- package/dist/factory/index.mjs +6 -6
- package/dist/{fastify-augmentation-bzkWPt1f.d.mts → fastify-augmentation-baQc3MaO.d.mts} +2 -2
- package/dist/fieldTypes-EFWxCkZ5.mjs +80 -0
- package/dist/{fields-rfsl26Ov.mjs → fields-CT1Erg7o.mjs} +1 -1
- package/dist/{filter-merge-8glLr7Dk.mjs → filter-merge-B1eJ1pMx.mjs} +1 -1
- package/dist/{generate-BOfBueRt.mjs → generate-Cr0ULavs.mjs} +2 -2
- package/dist/{headers-CHSOqpcY.mjs → headers-D4bncIOf.mjs} +2 -2
- package/dist/{health-ezwTHQh2.mjs → health-BoFxrkJE.mjs} +1 -1
- package/dist/{health-DHvAIVmM.mjs → health-DN_pUVMX.mjs} +1 -1
- package/dist/hooks/index.d.mts +1 -1
- package/dist/hooks/index.mjs +2 -2
- package/dist/http-cache/index.d.mts +2 -2
- package/dist/http-cache/index.mjs +4 -4
- package/dist/http-cache/purgers/cloudflare.mjs +2 -2
- package/dist/http-cache/purgers/fastly.mjs +2 -2
- package/dist/http-cache/testing/index.mjs +1 -1
- package/dist/idempotency/index.d.mts +1 -1
- package/dist/idempotency/index.mjs +10 -8
- package/dist/idempotency/redis.mjs +2 -2
- package/dist/{index-B5i9-vuP.d.mts → index-CMNpMBtW.d.mts} +1 -1
- package/dist/{index-BxZS-8So.d.mts → index-DKM2p5w5.d.mts} +48 -23
- package/dist/{index-Cy2-QffW.d.mts → index-DLCcLUQT.d.mts} +69 -6
- package/dist/{index-DFCCQ9AE.d.mts → index-DexdFs1a.d.mts} +1 -1
- package/dist/{index-D1X_C_qz.d.mts → index-Dhrks-hM.d.mts} +60 -10
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +11 -11
- package/dist/{init-MoE3eZNR.mjs → init-C4a24wD2.mjs} +1 -1
- package/dist/integrations/event-gateway.mjs +2 -2
- package/dist/integrations/index.d.mts +2 -2
- package/dist/integrations/index.mjs +1 -1
- package/dist/integrations/jobs/index.mjs +3 -3
- package/dist/integrations/mcp/index.d.mts +5 -5
- package/dist/integrations/mcp/index.mjs +2 -2
- package/dist/integrations/mcp/testing.d.mts +2 -2
- package/dist/integrations/mcp/testing.mjs +2 -2
- package/dist/integrations/streamline.mjs +3 -3
- package/dist/integrations/webhooks.d.mts +1 -1
- package/dist/integrations/webhooks.mjs +4 -4
- package/dist/integrations/websocket-pushref-redis.mjs +1 -1
- package/dist/integrations/websocket-redis.mjs +1 -1
- package/dist/integrations/websocket.mjs +2 -2
- package/dist/{jsonBody-DZGiCawf.mjs → jsonBody-DoTt5BS6.mjs} +2 -2
- package/dist/{keys-CrMOZuk6.mjs → keys--l9n7aOC.mjs} +1 -1
- package/dist/{loadResources-CVQvYUhN.mjs → loadResources-rygByIQA.mjs} +3 -3
- package/dist/{loadResourcesFromEntry-D0naccV2.mjs → loadResourcesFromEntry-ItNBIQ5w.mjs} +2 -2
- package/dist/logger/index.mjs +2 -2
- package/dist/{logger-VyMcSmVG.mjs → logger-UbknHqHy.mjs} +1 -1
- package/dist/{mcpPlugin-DQACaqVu.mjs → mcpPlugin-CTkk4RP8.mjs} +29 -26
- package/dist/{memory-Lpfu8Hga.mjs → memory-C47xVsjX.mjs} +3 -3
- package/dist/{metrics-DjVj1sg5.mjs → metrics-TJyAb1Xk.mjs} +4 -7
- package/dist/middleware/index.d.mts +1 -1
- package/dist/middleware/index.mjs +3 -3
- package/dist/migrations/index.mjs +2 -2
- package/dist/{module-BqPJpZ_L.mjs → module-CWiqsXnh.mjs} +1 -1
- package/dist/{multiTenant-KZj8j1uJ.d.mts → multiTenant-QtDzxx_K.d.mts} +1 -1
- package/dist/{multipartBody-BNgNv7r0.mjs → multipartBody-BdG1qbn1.mjs} +1 -1
- package/dist/{observeSend-BKJHibJz.mjs → observeSend-DrA3ADFN.mjs} +1 -1
- package/dist/{openapi-T90KrPR6.mjs → openapi-D6MAbYpv.mjs} +7 -7
- package/dist/outbox-admin/index.d.mts +1 -1
- package/dist/outbox-admin/index.mjs +5 -5
- package/dist/{outbox-module-C874VgBr.mjs → outbox-module-D5QABFQW.mjs} +197 -28
- package/dist/{outbox-module-5Mnwcycy.d.mts → outbox-module-DzW6zwWJ.d.mts} +103 -10
- package/dist/permissions/index.d.mts +2 -2
- package/dist/permissions/index.mjs +7 -7
- package/dist/{permissions-R9T2G1PH.mjs → permissions-CFsmdYUt.mjs} +9 -9
- package/dist/{pipe-DzqbsZy-.mjs → pipe-B_05AgGt.mjs} +2 -2
- package/dist/pipeline/index.d.mts +1 -1
- package/dist/pipeline/index.mjs +2 -2
- package/dist/{plan-C0gkeABY.mjs → plan-BnlNJhrj.mjs} +1 -1
- package/dist/{plugin-BJcVOX5r.mjs → plugin-CrMPYbdj.mjs} +94 -50
- package/dist/plugins/index.d.mts +6 -5
- package/dist/plugins/index.mjs +19 -18
- package/dist/plugins/response-cache.mjs +4 -4
- package/dist/plugins/tracing-entry.mjs +2 -2
- package/dist/{pluralize-CrCpyoZs.mjs → pluralize-oVIxJ4CY.mjs} +1 -1
- package/dist/presets/filesUpload.d.mts +1 -1
- package/dist/presets/filesUpload.mjs +5 -5
- package/dist/presets/index.d.mts +2 -2
- package/dist/presets/index.mjs +2 -2
- package/dist/presets/multiTenant.d.mts +1 -1
- package/dist/presets/multiTenant.mjs +5 -5
- package/dist/presets/search.d.mts +1 -1
- package/dist/presets/search.mjs +2 -2
- package/dist/{presets-CNDvNYsz.mjs → presets-CUd3L7v6.mjs} +4 -4
- package/dist/{projection-CIUe8b59.mjs → projection-DowJlIto.mjs} +2 -2
- package/dist/{purger.types-f83fTzGy.mjs → purger.types-BjKy8869.mjs} +1 -1
- package/dist/{queryCachePlugin-B2jpwFcv.mjs → queryCachePlugin-BvB3k_Fh.mjs} +114 -14
- package/dist/{queryCachePlugin-DYQUyeJ9.d.mts → queryCachePlugin-DrQNnGws.d.mts} +1 -1
- package/dist/{rateLimitKey-BWx-qep0.mjs → rateLimitKey-56nH1cWN.mjs} +1 -1
- package/dist/{realtime-D2tqi3d2.mjs → realtime-DXGBPtYK.mjs} +19 -22
- package/dist/registry/index.d.mts +2 -2
- package/dist/registry/index.mjs +3 -3
- package/dist/{registry-Dl0k6UXy.mjs → registry-Biz-6sEZ.mjs} +2 -2
- package/dist/{relay-ZYvS4xyW.mjs → relay-DEIoMntZ.mjs} +200 -99
- package/dist/{renewingLease-DT4yLb29.mjs → renewingLease-BCJpW9-u.mjs} +1 -1
- package/dist/{replyHelpers-BJFN5AW7.mjs → replyHelpers-DliJNb0-.mjs} +2 -2
- package/dist/{requestContext-Ct5la-SA.mjs → requestContext-tUgLt9Ky.mjs} +1 -1
- package/dist/{requirement-CxDxjB6V.mjs → requirement-0l2DApiQ.mjs} +1 -1
- package/dist/{resourceRateLimit-DCWglD7V.d.mts → resourceRateLimit-BPiESPtG.d.mts} +4 -0
- package/dist/{resourceRateLimit-D1oH2obv.mjs → resourceRateLimit-iSXF8rLH.mjs} +19 -4
- package/dist/{rolldown-runtime-BdTN42uL.mjs → rolldown-runtime-gKJR3o-6.mjs} +1 -1
- package/dist/{routeValidator-DclDl5WJ.mjs → routeValidator-xNYA4rr1.mjs} +47 -5
- package/dist/{runtimeCapabilities-ClWr60El.mjs → runtimeCapabilities-BQK-GrYe.mjs} +1 -1
- package/dist/{schedules-gVkRcs-9.mjs → schedules-D9iMVFhF.mjs} +6 -9
- package/dist/{schemaConverter-CIwB5wPO.mjs → schemaConverter-cIh4oX9a.mjs} +2 -2
- package/dist/{actionPermissions-Dha8sAz2.mjs → schemaIR-BsY4y9VP.mjs} +184 -16
- package/dist/schemas/index.mjs +1 -1
- package/dist/scim/index.mjs +2 -2
- package/dist/scope/index.d.mts +1 -1
- package/dist/scope/index.mjs +5 -5
- package/dist/{scope-VMZhdkbT.mjs → scope-QyhM9w8z.mjs} +4 -4
- package/dist/{shutdown-Bi19vH0z.mjs → shutdown-BM7Q0h4B.mjs} +1 -1
- package/dist/{sse-BqM359f1.mjs → sse-ofvlcTQQ.mjs} +9 -35
- package/dist/sseStats-DQqNN385.d.mts +112 -0
- package/dist/sseStream-BxQW7hPq.mjs +166 -0
- package/dist/{store-helpers-rx-F2ZGR.mjs → store-helpers-_FRhHDyv.mjs} +1 -1
- package/dist/{simpleEqualityMatcher-CaCS09fh.mjs → streamFrames-B3ZJfI02.mjs} +19 -2
- package/dist/{streaming-CPChx3A7.mjs → streaming-HZr63UiM.mjs} +1 -1
- package/dist/{subscriberIdentity-CYNYw8p_.mjs → subscriberIdentity-DSgnoT_D.mjs} +1 -1
- package/dist/{tenancy-BoWImS3K.mjs → tenancy-_ukT0oBt.mjs} +2 -2
- package/dist/{tenantPreparation-oqKCZQZM.mjs → tenantPreparation-DSlQI53c.mjs} +4 -4
- package/dist/testing/cleanupStoreContract.mjs +1 -1
- package/dist/testing/index.d.mts +4 -4
- package/dist/testing/index.mjs +324 -17
- package/dist/testing/outboxStoreContract.mjs +2 -2
- package/dist/testing/requiredPorts.mjs +2 -2
- package/dist/testing/storageContract.mjs +1 -1
- package/dist/{timing-Dsteq59c.mjs → timing-Z8p-Zlw1.mjs} +1 -1
- package/dist/{transactionContext-C1OgH-hW.mjs → transactionContext-DBbSTfY3.mjs} +1 -1
- package/dist/{typeGuards-DNlpASzd.mjs → typeGuards-_6nNQqgq.mjs} +1 -1
- package/dist/types/index.d.mts +1 -1
- package/dist/types/index.mjs +1 -1
- package/dist/types/storage.mjs +1 -1
- package/dist/{types-DduBiYaI.d.mts → types-B4E0sc6D.d.mts} +2 -2
- package/dist/{types-HFFSwF_K.mjs → types-CrOlZ4rY.mjs} +4 -4
- package/dist/usage/index.d.mts +1 -1
- package/dist/usage/index.mjs +7 -7
- package/dist/{userHelpers-N-k-8dNF.mjs → userHelpers-CBKx3XJN.mjs} +1 -1
- package/dist/utils/index.d.mts +239 -34
- package/dist/utils/index.mjs +13 -13
- package/dist/{utils-C7w_RVlx.mjs → utils--HE8R8sH.mjs} +761 -8
- package/dist/{validate-Brr4b_fH.mjs → validate-BUeE2MLR.mjs} +3 -3
- package/dist/{versioning-S18y2-0C.d.mts → versioning-B07RgD27.d.mts} +2 -13
- package/dist/{versioning-CE5kdWOY.mjs → versioning-qYgqwOhL.mjs} +4 -7
- package/dist/{workScope-A3XBpYTa.mjs → workScope-C-1QHNmV.mjs} +2 -2
- package/llms.txt +2 -2
- package/package.json +34 -34
- package/skills/arc/references/api-reference.md +2 -2
- package/skills/arc/references/auth-better-auth.md +1 -0
- package/skills/arc/references/events-outbox.md +7 -4
- package/skills/arc/references/events.md +2 -2
- package/skills/arc/references/production-api.md +4 -0
- package/skills/arc/references/production-boot.md +2 -0
- package/skills/arc/references/production-idempotency.md +1 -1
- package/skills/arc/references/production-realtime.md +28 -2
- package/skills/arc/references/validation.md +4 -0
- package/skills/arc/references/writes-hooks-errors.md +1 -0
- package/dist/schemaIR-A0IoD05P.mjs +0 -108
- package/dist/sseStream-qSa-F2Qm.mjs +0 -57
|
@@ -1,16 +1,17 @@
|
|
|
1
|
-
/*! @classytic/arc v2.
|
|
2
|
-
import { f as createError } from "./errors-
|
|
3
|
-
import { n as getUserRoles } from "./userHelpers-
|
|
4
|
-
import { b as isElevated, n as PUBLIC_SCOPE, u as getRequestScope, x as isMember } from "./types-
|
|
5
|
-
import { a as resolveEffectiveRoles, r as deriveHiddenFieldPermissions, t as applyFieldReadPermissions } from "./fields-
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import { n as
|
|
9
|
-
import { n as
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
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
|
-
|
|
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 };
|
package/dist/schemas/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! @classytic/arc v2.
|
|
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
|
package/dist/scim/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! @classytic/arc v2.
|
|
2
|
-
import { t as parseJsonBody } from "../jsonBody-
|
|
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 {
|
package/dist/scope/index.d.mts
CHANGED
|
@@ -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;
|
package/dist/scope/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
/*! @classytic/arc v2.
|
|
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-
|
|
3
|
-
import { t as createTenantKeyGenerator } from "../rateLimitKey-
|
|
4
|
-
import { t as elevation_default } from "../elevation-
|
|
5
|
-
import { t as resolveOrgFromHeader } from "../scope-
|
|
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.
|
|
2
|
-
import { a as OrgAccessDeniedError, l as UnauthorizedError } from "./errors-
|
|
3
|
-
import { n as requireSingleHeaderValue } from "./headers-
|
|
4
|
-
import { n as getUserRoles } from "./userHelpers-
|
|
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.
|
|
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.
|
|
2
|
-
import { t as __exportAll } from "./rolldown-runtime-
|
|
3
|
-
import { t as
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { a as
|
|
7
|
-
import {
|
|
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
|
-
|
|
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 };
|