@classytic/arc 2.10.8 → 2.11.1

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 (136) hide show
  1. package/dist/{BaseController-DVNKvoX4.mjs → BaseController-JNV08qOT.mjs} +480 -442
  2. package/dist/{queryCachePlugin-Dumka73q.d.mts → QueryCache-DOBNHBE0.d.mts} +2 -32
  3. package/dist/adapters/index.d.mts +2 -2
  4. package/dist/adapters/index.mjs +1 -1
  5. package/dist/{adapters-BXY4i-hw.mjs → adapters-D0tT2Tyo.mjs} +54 -0
  6. package/dist/audit/index.d.mts +1 -1
  7. package/dist/auth/index.d.mts +1 -1
  8. package/dist/auth/index.mjs +5 -5
  9. package/dist/{betterAuthOpenApi--rdY15Ld.mjs → betterAuthOpenApi-DwxtK3uG.mjs} +1 -1
  10. package/dist/cache/index.d.mts +3 -2
  11. package/dist/cache/index.mjs +3 -3
  12. package/dist/cli/commands/docs.mjs +2 -2
  13. package/dist/cli/commands/generate.mjs +37 -27
  14. package/dist/cli/commands/init.mjs +46 -33
  15. package/dist/cli/commands/introspect.mjs +1 -1
  16. package/dist/context/index.mjs +1 -1
  17. package/dist/core/index.d.mts +3 -3
  18. package/dist/core/index.mjs +4 -3
  19. package/dist/core-DXdSSFW-.mjs +1037 -0
  20. package/dist/createActionRouter-BwaSM0No.mjs +166 -0
  21. package/dist/{createApp-BwnEAO2h.mjs → createApp-P1d6rjPy.mjs} +75 -27
  22. package/dist/docs/index.d.mts +1 -1
  23. package/dist/docs/index.mjs +2 -2
  24. package/dist/{elevation-Dci0AYLT.mjs → elevation-DOFoxoDs.mjs} +1 -1
  25. package/dist/{errorHandler-CSxe7KIM.mjs → errorHandler-BQm8ZxTK.mjs} +1 -1
  26. package/dist/{eventPlugin-ByU4Cv0e.mjs → eventPlugin--5HIkdPU.mjs} +1 -1
  27. package/dist/events/index.d.mts +3 -3
  28. package/dist/events/index.mjs +2 -2
  29. package/dist/events/transports/redis-stream-entry.d.mts +1 -1
  30. package/dist/factory/index.d.mts +2 -2
  31. package/dist/factory/index.mjs +2 -2
  32. package/dist/hooks/index.d.mts +1 -1
  33. package/dist/hooks/index.mjs +1 -1
  34. package/dist/idempotency/index.d.mts +3 -3
  35. package/dist/idempotency/index.mjs +1 -1
  36. package/dist/idempotency/redis.d.mts +1 -1
  37. package/dist/{index-C_Noptz-.d.mts → index-BYCqHCVu.d.mts} +2 -2
  38. package/dist/{index-BGbpGVyM.d.mts → index-C_bgx9o4.d.mts} +712 -500
  39. package/dist/{index-BziRPS4H.d.mts → index-CvM1e09j.d.mts} +29 -10
  40. package/dist/{index-EqQN6p0W.d.mts → index-pUczGjO0.d.mts} +11 -8
  41. package/dist/index-smCAoA5W.d.mts +1179 -0
  42. package/dist/index.d.mts +6 -38
  43. package/dist/index.mjs +9 -9
  44. package/dist/integrations/event-gateway.d.mts +1 -1
  45. package/dist/integrations/event-gateway.mjs +1 -1
  46. package/dist/integrations/index.d.mts +2 -2
  47. package/dist/integrations/mcp/index.d.mts +2 -2
  48. package/dist/integrations/mcp/index.mjs +1 -1
  49. package/dist/integrations/mcp/testing.d.mts +1 -1
  50. package/dist/integrations/mcp/testing.mjs +1 -1
  51. package/dist/integrations/streamline.d.mts +46 -5
  52. package/dist/integrations/streamline.mjs +50 -21
  53. package/dist/integrations/websocket-redis.d.mts +1 -1
  54. package/dist/integrations/websocket.d.mts +2 -154
  55. package/dist/integrations/websocket.mjs +292 -224
  56. package/dist/{keys-nWQGUTu1.mjs → keys-CARyUjiR.mjs} +2 -0
  57. package/dist/{loadResources-Bksk8ydA.mjs → loadResources-CPpkyKfM.mjs} +32 -8
  58. package/dist/middleware/index.d.mts +1 -1
  59. package/dist/middleware/index.mjs +1 -1
  60. package/dist/{openapi-DpNpqBmo.mjs → openapi-C0L9ar7m.mjs} +4 -4
  61. package/dist/org/index.d.mts +1 -1
  62. package/dist/permissions/index.d.mts +1 -1
  63. package/dist/permissions/index.mjs +2 -4
  64. package/dist/{permissions-wkqRwicB.mjs → permissions-B4vU9L0Q.mjs} +221 -3
  65. package/dist/{pipe-CGJxqDGx.mjs → pipe-DVoIheVC.mjs} +1 -1
  66. package/dist/pipeline/index.d.mts +1 -1
  67. package/dist/pipeline/index.mjs +1 -1
  68. package/dist/plugins/index.d.mts +4 -4
  69. package/dist/plugins/index.mjs +10 -10
  70. package/dist/plugins/response-cache.mjs +1 -1
  71. package/dist/plugins/tracing-entry.d.mts +1 -1
  72. package/dist/plugins/tracing-entry.mjs +42 -24
  73. package/dist/presets/filesUpload.d.mts +1 -1
  74. package/dist/presets/filesUpload.mjs +3 -3
  75. package/dist/presets/index.d.mts +1 -1
  76. package/dist/presets/index.mjs +1 -1
  77. package/dist/presets/multiTenant.d.mts +1 -1
  78. package/dist/presets/multiTenant.mjs +6 -0
  79. package/dist/presets/search.d.mts +1 -1
  80. package/dist/presets/search.mjs +1 -1
  81. package/dist/{presets-CrwOvuXI.mjs → presets-k604Lj99.mjs} +1 -1
  82. package/dist/queryCachePlugin-BUXBSm4F.d.mts +34 -0
  83. package/dist/{queryCachePlugin-ChLNZvFT.mjs → queryCachePlugin-Bq6bO6vc.mjs} +3 -3
  84. package/dist/{redis-MXLp1oOf.d.mts → redis-Cm1gnRDf.d.mts} +1 -1
  85. package/dist/registry/index.d.mts +1 -1
  86. package/dist/registry/index.mjs +2 -2
  87. package/dist/{resourceToTools-BhF3JV5p.mjs → resourceToTools--okX6QBr.mjs} +534 -420
  88. package/dist/routerShared-DeESFp4a.mjs +515 -0
  89. package/dist/schemaIR-BlG9bY7v.mjs +137 -0
  90. package/dist/scope/index.mjs +2 -2
  91. package/dist/testing/index.d.mts +367 -711
  92. package/dist/testing/index.mjs +637 -1434
  93. package/dist/{tracing-xqXzWeaf.d.mts → tracing-DokiEsuz.d.mts} +9 -4
  94. package/dist/types/index.d.mts +3 -3
  95. package/dist/types/index.mjs +1 -3
  96. package/dist/{types-CVdgPXBW.d.mts → types-BdA4uMBV.d.mts} +191 -28
  97. package/dist/{types-CVKBssX5.d.mts → types-Bh_gEJBi.d.mts} +1 -1
  98. package/dist/utils/index.d.mts +2 -968
  99. package/dist/utils/index.mjs +5 -6
  100. package/dist/utils-D3Yxnrwr.mjs +1639 -0
  101. package/dist/websocket-CyJ1VIFI.d.mts +186 -0
  102. package/package.json +7 -5
  103. package/skills/arc/SKILL.md +124 -39
  104. package/skills/arc/references/testing.md +212 -183
  105. package/dist/applyPermissionResult-QhV1Pa-g.mjs +0 -37
  106. package/dist/core-3MWJosCH.mjs +0 -1459
  107. package/dist/createActionRouter-C8UUB3Px.mjs +0 -249
  108. package/dist/errors-BI8kEKsO.d.mts +0 -140
  109. package/dist/fields-CTMWOUDt.mjs +0 -126
  110. package/dist/queryParser-NR__Qiju.mjs +0 -419
  111. package/dist/types-CDnTEpga.mjs +0 -27
  112. package/dist/utils-LMwVidKy.mjs +0 -947
  113. /package/dist/{HookSystem-BjFu7zf1.mjs → HookSystem-CGsMd6oK.mjs} +0 -0
  114. /package/dist/{ResourceRegistry-CcN2LVrc.mjs → ResourceRegistry-DkAeAuTX.mjs} +0 -0
  115. /package/dist/{actionPermissions-TUVR3uiZ.mjs → actionPermissions-C8YYU92K.mjs} +0 -0
  116. /package/dist/{caching-3h93rkJM.mjs → caching-CheW3m-S.mjs} +0 -0
  117. /package/dist/{errorHandler-2ii4RIYr.d.mts → errorHandler-Co3lnVmJ.d.mts} +0 -0
  118. /package/dist/{errors-BqdUDja_.mjs → errors-D5c-5BJL.mjs} +0 -0
  119. /package/dist/{eventPlugin-D1ThQ1Pp.d.mts → eventPlugin-CUNjYYRY.d.mts} +0 -0
  120. /package/dist/{interface-B-pe8fhj.d.mts → interface-CkkWm5uR.d.mts} +0 -0
  121. /package/dist/{interface-yhyb_pLY.d.mts → interface-Da0r7Lna.d.mts} +0 -0
  122. /package/dist/{memory-DqI-449b.mjs → memory-DikHSvWa.mjs} +0 -0
  123. /package/dist/{metrics-TuOmguhi.mjs → metrics-Csh4nsvv.mjs} +0 -0
  124. /package/dist/{multipartBody-CUQGVlM_.mjs → multipartBody-CvTR1Un6.mjs} +0 -0
  125. /package/dist/{pluralize-CWP6MB39.mjs → pluralize-BneOJkpi.mjs} +0 -0
  126. /package/dist/{redis-stream-bkO88VHx.d.mts → redis-stream-CM8TXTix.d.mts} +0 -0
  127. /package/dist/{registry-B0Wl7uVV.mjs → registry-D63ee7fl.mjs} +0 -0
  128. /package/dist/{replyHelpers-BLojtuvR.mjs → replyHelpers-ByllIXXV.mjs} +0 -0
  129. /package/dist/{requestContext-C38GskNt.mjs → requestContext-CfRkaxwf.mjs} +0 -0
  130. /package/dist/{schemaConverter-BxFDdtXu.mjs → schemaConverter-B0oKLuqI.mjs} +0 -0
  131. /package/dist/{sse-D8UeDwis.mjs → sse-V7aXc3bW.mjs} +0 -0
  132. /package/dist/{store-helpers-DYYUQbQN.mjs → store-helpers-BhrzxvyQ.mjs} +0 -0
  133. /package/dist/{typeGuards-Cj5Rgvlg.mjs → typeGuards-CcFZXgU7.mjs} +0 -0
  134. /package/dist/{types-D57iXYb8.mjs → types-DV9WDfeg.mjs} +0 -0
  135. /package/dist/{versioning-B6mimogM.mjs → versioning-CGPjkqAg.mjs} +0 -0
  136. /package/dist/{versioning-CeUXHfjw.d.mts → versioning-M9lNLhO8.d.mts} +0 -0
@@ -1,8 +1,226 @@
1
1
  import { t as __exportAll } from "./chunk-BpYLSNr0.mjs";
2
2
  import { _ as isElevated, b as isService, c as getRequestScope, d as getServiceScopes, f as getTeamId, h as hasOrgAccess, l as getScopeContext, p as getUserId, u as getScopeContextMap, v as isMember, y as isOrgInScope } from "./types-AOD8fxIw.mjs";
3
- import { t as getUserRoles } from "./types-D57iXYb8.mjs";
4
- import { t as MemoryCacheStore } from "./memory-DqI-449b.mjs";
3
+ import { t as getUserRoles } from "./types-DV9WDfeg.mjs";
4
+ import { t as MemoryCacheStore } from "./memory-DikHSvWa.mjs";
5
5
  import { randomUUID } from "node:crypto";
6
+ //#region src/permissions/fields.ts
7
+ /**
8
+ * Field-Level Permissions
9
+ *
10
+ * Control field visibility and writability per role.
11
+ * Integrated into the response path (read) and sanitization path (write).
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * import { fields, defineResource } from '@classytic/arc';
16
+ *
17
+ * const userResource = defineResource({
18
+ * name: 'user',
19
+ * adapter: userAdapter,
20
+ * fields: {
21
+ * salary: fields.visibleTo(['admin', 'hr']),
22
+ * internalNotes: fields.writableBy(['admin']),
23
+ * email: fields.redactFor(['viewer']),
24
+ * password: fields.hidden(),
25
+ * },
26
+ * });
27
+ * ```
28
+ */
29
+ /** Type guard for Mongoose-like documents with toObject() */
30
+ function isMongooseDoc(obj) {
31
+ return !!obj && typeof obj === "object" && "toObject" in obj && typeof obj.toObject === "function";
32
+ }
33
+ const fields = {
34
+ hidden() {
35
+ return { _type: "hidden" };
36
+ },
37
+ visibleTo(roles) {
38
+ return {
39
+ _type: "visibleTo",
40
+ roles
41
+ };
42
+ },
43
+ writableBy(roles) {
44
+ return {
45
+ _type: "writableBy",
46
+ roles
47
+ };
48
+ },
49
+ redactFor(roles, redactValue = "***") {
50
+ return {
51
+ _type: "redactFor",
52
+ roles,
53
+ redactValue
54
+ };
55
+ }
56
+ };
57
+ /**
58
+ * Apply field-level READ permissions to a response object.
59
+ * Strips hidden fields, enforces visibility, and applies redaction.
60
+ *
61
+ * @param data - The response object (mutated in place for performance)
62
+ * @param fieldPermissions - Field permission map from resource config
63
+ * @param userRoles - Current user's roles (empty array for unauthenticated)
64
+ * @returns The filtered object
65
+ */
66
+ function applyFieldReadPermissions(data, fieldPermissions, userRoles) {
67
+ if (!data || typeof data !== "object") return data;
68
+ const result = { ...isMongooseDoc(data) ? data.toObject() : data };
69
+ for (const [field, perm] of Object.entries(fieldPermissions)) switch (perm._type) {
70
+ case "hidden":
71
+ delete result[field];
72
+ break;
73
+ case "visibleTo":
74
+ if (!perm.roles?.some((r) => userRoles.includes(r))) delete result[field];
75
+ break;
76
+ case "redactFor":
77
+ if (perm.roles?.some((r) => userRoles.includes(r))) result[field] = perm.redactValue ?? "***";
78
+ break;
79
+ case "writableBy": break;
80
+ }
81
+ return result;
82
+ }
83
+ /**
84
+ * Apply field-level WRITE permissions to request body.
85
+ *
86
+ * Returns both the filtered body and the list of denied fields. Callers are
87
+ * expected to reject the request when `deniedFields.length > 0` — silently
88
+ * stripping fields hides misconfigurations and real attacks. See
89
+ * `BodySanitizer` for the default policy.
90
+ *
91
+ * @param body - The request body (returns a new filtered copy)
92
+ * @param fieldPermissions - Field permission map from resource config
93
+ * @param userRoles - Current user's roles
94
+ */
95
+ function applyFieldWritePermissions(body, fieldPermissions, userRoles) {
96
+ const result = { ...body };
97
+ const deniedFields = [];
98
+ for (const [field, perm] of Object.entries(fieldPermissions)) switch (perm._type) {
99
+ case "hidden":
100
+ if (field in result) {
101
+ deniedFields.push(field);
102
+ delete result[field];
103
+ }
104
+ break;
105
+ case "writableBy":
106
+ if (field in result && !perm.roles?.some((r) => userRoles.includes(r))) {
107
+ deniedFields.push(field);
108
+ delete result[field];
109
+ }
110
+ break;
111
+ }
112
+ return {
113
+ body: result,
114
+ deniedFields
115
+ };
116
+ }
117
+ /**
118
+ * Resolve effective roles by merging global user roles with org-level roles.
119
+ *
120
+ * Global roles come from `req.user.role` (normalized via getUserRoles()).
121
+ * Org roles come from `req.context.orgRoles` (set by BA adapter's org bridge).
122
+ *
123
+ * When no org context exists, returns global roles only — backward compatible.
124
+ */
125
+ function resolveEffectiveRoles(userRoles, orgRoles) {
126
+ if (orgRoles.length === 0) return [...userRoles];
127
+ if (userRoles.length === 0) return [...orgRoles];
128
+ return [...new Set([...userRoles, ...orgRoles])];
129
+ }
130
+ //#endregion
131
+ //#region src/permissions/applyPermissionResult.ts
132
+ /**
133
+ * Normalize a permission check return value (`boolean | PermissionResult`)
134
+ * into a concrete `PermissionResult`. This is the only place in Arc that
135
+ * promotes booleans to results — keeps the type narrowing honest everywhere.
136
+ */
137
+ function normalizePermissionResult(result) {
138
+ if (typeof result === "boolean") return { granted: result };
139
+ return result;
140
+ }
141
+ /**
142
+ * Apply a granted `PermissionResult` to a Fastify request — merges row-level
143
+ * filters into `_policyFilters` and conditionally installs the scope.
144
+ *
145
+ * **Scope install rule:** only writes `scope` when the current request scope
146
+ * is absent or `public`. This prevents downgrading an already-authenticated
147
+ * request (e.g. Better Auth set `member`, then a permission check returns a
148
+ * narrower `service` scope — the original `member` wins because it came from
149
+ * a more authoritative source).
150
+ *
151
+ * Safe to call with a non-granted result — it simply no-ops. Callers should
152
+ * still check `result.granted` and send an error response before reaching here,
153
+ * but this function tolerates the misuse defensively.
154
+ */
155
+ function applyPermissionResult(result, request) {
156
+ if (!result.granted) return;
157
+ if (result.filters) request._policyFilters = {
158
+ ...request._policyFilters ?? {},
159
+ ...result.filters
160
+ };
161
+ if (result.scope) {
162
+ const current = request.scope;
163
+ if (!current || current.kind === "public") request.scope = result.scope;
164
+ }
165
+ }
166
+ /**
167
+ * Max length of a `PermissionResult.reason` string before we fall back to the
168
+ * generic default message. Upstream checks can return arbitrary strings; we
169
+ * clamp to prevent accidental leakage of internal diagnostics or oversized
170
+ * payloads via the 4xx response body.
171
+ */
172
+ const MAX_DENIAL_REASON_LENGTH = 100;
173
+ /**
174
+ * End-to-end evaluator: runs the permission check, catches throws, normalizes
175
+ * the result, sends a 401/403 response on denial, and applies side-effects on
176
+ * grant. Returns `true` if the caller should continue, `false` if a response
177
+ * has been sent and the caller should return.
178
+ *
179
+ * This is the single source of truth for the 5-step sequence shared by the
180
+ * CRUD router, action router, and MCP tool handlers:
181
+ *
182
+ * 1. `try { await check(ctx) } catch { reply 403 }`
183
+ * 2. `normalizePermissionResult(result)`
184
+ * 3. If denied → 401 (no user) or 403 (user) with clamped reason
185
+ * 4. If granted → `applyPermissionResult` (filters + scope)
186
+ * 5. Return true/false so the caller knows whether to keep going
187
+ *
188
+ * Context construction, pre-check auth gating, and success-path handler
189
+ * invocation stay at the callsite — those are genuinely different per router
190
+ * and don't belong here.
191
+ *
192
+ * @returns `true` if authorized (caller continues), `false` if a response was sent
193
+ */
194
+ async function evaluateAndApplyPermission(check, context, request, reply, opts) {
195
+ let result;
196
+ try {
197
+ result = await check(context);
198
+ } catch (err) {
199
+ request.log?.warn?.({
200
+ err,
201
+ resource: context.resource,
202
+ action: context.action
203
+ }, "Permission check threw");
204
+ reply.code(403).send({
205
+ success: false,
206
+ error: "Permission denied"
207
+ });
208
+ return false;
209
+ }
210
+ const permResult = normalizePermissionResult(result);
211
+ if (!permResult.granted) {
212
+ const defaultMsg = opts?.defaultDenialMessage?.(context.user) ?? (context.user ? "Permission denied" : "Authentication required");
213
+ const reason = permResult.reason && permResult.reason.length <= MAX_DENIAL_REASON_LENGTH ? permResult.reason : defaultMsg;
214
+ reply.code(context.user ? 403 : 401).send({
215
+ success: false,
216
+ error: reason
217
+ });
218
+ return false;
219
+ }
220
+ applyPermissionResult(permResult, request);
221
+ return true;
222
+ }
223
+ //#endregion
6
224
  //#region src/permissions/core.ts
7
225
  /**
8
226
  * Normalize a `string | [readonly string[]]` rest-args tuple into a single
@@ -1002,4 +1220,4 @@ function readOnly(overrides) {
1002
1220
  }, overrides);
1003
1221
  }
1004
1222
  //#endregion
1005
- export { requireAuth as C, when as D, roles as E, not as S, requireRoles as T, requireTeamMembership as _, presets_exports as a, anyOf as b, readOnly as c, createOrgPermissions as d, requireOrgInScope as f, requireServiceScope as g, requireScopeContext as h, ownerWithAdminBypass as i, createRoleHierarchy as l, requireOrgRole as m, authenticated as n, publicRead as o, requireOrgMembership as p, fullPublic as r, publicReadAdminWrite as s, adminOnly as t, createDynamicPermissionMatrix as u, allOf as v, requireOwnership as w, denyAll as x, allowPublic as y };
1223
+ export { normalizePermissionResult as A, requireAuth as C, when as D, roles as E, applyFieldWritePermissions as M, fields as N, applyPermissionResult as O, resolveEffectiveRoles as P, not as S, requireRoles as T, requireTeamMembership as _, presets_exports as a, anyOf as b, readOnly as c, createOrgPermissions as d, requireOrgInScope as f, requireServiceScope as g, requireScopeContext as h, ownerWithAdminBypass as i, applyFieldReadPermissions as j, evaluateAndApplyPermission as k, createRoleHierarchy as l, requireOrgRole as m, authenticated as n, publicRead as o, requireOrgMembership as p, fullPublic as r, publicReadAdminWrite as s, adminOnly as t, createDynamicPermissionMatrix as u, allOf as v, requireOwnership as w, denyAll as x, allowPublic as y };
@@ -1,4 +1,4 @@
1
- import { r as ForbiddenError } from "./errors-BqdUDja_.mjs";
1
+ import { r as ForbiddenError } from "./errors-D5c-5BJL.mjs";
2
2
  //#region src/pipeline/pipe.ts
3
3
  /**
4
4
  * Compose pipeline steps into an ordered array.
@@ -1,4 +1,4 @@
1
- import { Bt as PipelineContext, Ft as Guard, Ht as Transform, It as Interceptor, Lt as NextFunction, Mt as IControllerResponse, Rt as OperationFilter, Vt as PipelineStep, zt as PipelineConfig } from "../index-BGbpGVyM.mjs";
1
+ import { Ct as OperationFilter, Dt as Transform, Et as PipelineStep, St as NextFunction, Tt as PipelineContext, _t as IControllerResponse, bt as Guard, wt as PipelineConfig, xt as Interceptor } from "../index-C_bgx9o4.mjs";
2
2
 
3
3
  //#region src/pipeline/guard.d.ts
4
4
  interface GuardOptions {
@@ -1,4 +1,4 @@
1
- import { n as pipe, t as executePipeline } from "../pipe-CGJxqDGx.mjs";
1
+ import { n as pipe, t as executePipeline } from "../pipe-DVoIheVC.mjs";
2
2
  //#region src/pipeline/guard.ts
3
3
  /**
4
4
  * Create a named guard.
@@ -1,8 +1,8 @@
1
- import { Dt as RouteSchemaOptions, J as HookSystem, Yt as AnyRecord, gt as PresetHook, pt as MiddlewareConfig, wt as RouteDefinition, z as ResourceRegistry } from "../index-BGbpGVyM.mjs";
1
+ import { Pt as AnyRecord, Q as MiddlewareConfig, ft as RouteSchemaOptions, gn as HookSystem, lt as RouteDefinition, tt as PresetHook, z as ResourceRegistry } from "../index-C_bgx9o4.mjs";
2
2
  import { t as ExternalOpenApiPaths } from "../externalPaths-Bapitwvd.mjs";
3
- import { a as MetricsCollector, c as metricsPlugin, d as ssePlugin, f as CachingOptions, h as cachingPlugin, i as MetricEntry, l as SSEOptions, m as _default$1, n as _default$7, o as MetricsOptions, p as CachingRule, r as versioningPlugin, s as _default$4, t as VersioningOptions, u as _default$6 } from "../versioning-CeUXHfjw.mjs";
4
- import { i as errorHandlerPlugin, n as ErrorMapper, r as defaultIsDuplicateKeyError, t as ErrorHandlerOptions } from "../errorHandler-2ii4RIYr.mjs";
5
- import { t as TracingOptions } from "../tracing-xqXzWeaf.mjs";
3
+ import { a as MetricsCollector, c as metricsPlugin, d as ssePlugin, f as CachingOptions, h as cachingPlugin, i as MetricEntry, l as SSEOptions, m as _default$1, n as _default$7, o as MetricsOptions, p as CachingRule, r as versioningPlugin, s as _default$4, t as VersioningOptions, u as _default$6 } from "../versioning-M9lNLhO8.mjs";
4
+ import { i as errorHandlerPlugin, n as ErrorMapper, r as defaultIsDuplicateKeyError, t as ErrorHandlerOptions } from "../errorHandler-Co3lnVmJ.mjs";
5
+ import { t as TracingOptions } from "../tracing-DokiEsuz.mjs";
6
6
  import { FastifyInstance, FastifyPluginAsync } from "fastify";
7
7
  import * as _$node_stream0 from "node:stream";
8
8
 
@@ -1,15 +1,15 @@
1
1
  import { p as MUTATION_OPERATIONS } from "../constants-BhY1OHoH.mjs";
2
2
  import { o as getOrgId } from "../types-AOD8fxIw.mjs";
3
- import { t as requestContext } from "../requestContext-C38GskNt.mjs";
4
- import { t as hasEvents } from "../typeGuards-Cj5Rgvlg.mjs";
5
- import { t as HookSystem } from "../HookSystem-BjFu7zf1.mjs";
6
- import { t as ResourceRegistry } from "../ResourceRegistry-CcN2LVrc.mjs";
7
- import { n as caching_default, t as cachingPlugin } from "../caching-3h93rkJM.mjs";
8
- import { n as errorHandlerPlugin, t as defaultIsDuplicateKeyError } from "../errorHandler-CSxe7KIM.mjs";
9
- import { n as metrics_default, t as metricsPlugin } from "../metrics-TuOmguhi.mjs";
10
- import { t as replyHelpersPlugin } from "../replyHelpers-BLojtuvR.mjs";
11
- import { n as sse_default, t as ssePlugin } from "../sse-D8UeDwis.mjs";
12
- import { n as versioning_default, t as versioningPlugin } from "../versioning-B6mimogM.mjs";
3
+ import { t as requestContext } from "../requestContext-CfRkaxwf.mjs";
4
+ import { t as hasEvents } from "../typeGuards-CcFZXgU7.mjs";
5
+ import { t as HookSystem } from "../HookSystem-CGsMd6oK.mjs";
6
+ import { t as ResourceRegistry } from "../ResourceRegistry-DkAeAuTX.mjs";
7
+ import { n as caching_default, t as cachingPlugin } from "../caching-CheW3m-S.mjs";
8
+ import { n as errorHandlerPlugin, t as defaultIsDuplicateKeyError } from "../errorHandler-BQm8ZxTK.mjs";
9
+ import { n as metrics_default, t as metricsPlugin } from "../metrics-Csh4nsvv.mjs";
10
+ import { t as replyHelpersPlugin } from "../replyHelpers-ByllIXXV.mjs";
11
+ import { n as sse_default, t as ssePlugin } from "../sse-V7aXc3bW.mjs";
12
+ import { n as versioning_default, t as versioningPlugin } from "../versioning-CGPjkqAg.mjs";
13
13
  import { randomUUID } from "node:crypto";
14
14
  import fp from "fastify-plugin";
15
15
  //#region src/core/arcCorePlugin.ts
@@ -1,4 +1,4 @@
1
- import { t as hasEvents } from "../typeGuards-Cj5Rgvlg.mjs";
1
+ import { t as hasEvents } from "../typeGuards-CcFZXgU7.mjs";
2
2
  import fp from "fastify-plugin";
3
3
  //#region src/plugins/response-cache.ts
4
4
  /**
@@ -1,2 +1,2 @@
1
- import { a as traced, i as isTracingAvailable, n as _default, r as createSpan, t as TracingOptions } from "../tracing-xqXzWeaf.mjs";
1
+ import { a as traced, i as isTracingAvailable, n as _default, r as createSpan, t as TracingOptions } from "../tracing-DokiEsuz.mjs";
2
2
  export { type TracingOptions, createSpan, isTracingAvailable, traced, _default as tracingPlugin };
@@ -14,6 +14,20 @@ import fp from "fastify-plugin";
14
14
  * serviceName: 'my-api',
15
15
  * exporterUrl: 'http://localhost:4318/v1/traces', // OTLP endpoint
16
16
  * });
17
+ *
18
+ * ## Type strategy
19
+ *
20
+ * `@opentelemetry/api` is the stable surface — its types are type-only
21
+ * imported here so hook handlers, `createSpan`, and `traced` don't hand
22
+ * out `any` for Tracer / Span. Only the runtime-loaded module BODIES
23
+ * (`trace.getTracer`, `context.with`, etc.) go through the optional-require
24
+ * path; everything downstream keeps its shape through the plugin.
25
+ *
26
+ * The SDK-side factories (`NodeTracerProvider`, `BatchSpanProcessor`,
27
+ * `OTLPTraceExporter`) aren't in @classytic/arc's devDeps and aren't
28
+ * type-importable without adding install weight, so those retain
29
+ * minimal constructor-style `unknown`-valued boxes. If a future refactor
30
+ * moves SDK types into devDependencies we can tighten further.
17
31
  */
18
32
  const require = createRequire(import.meta.url);
19
33
  let trace;
@@ -33,8 +47,8 @@ try {
33
47
  NodeTracerProvider = sdkNode.NodeTracerProvider;
34
48
  BatchSpanProcessor = sdkNode.BatchSpanProcessor;
35
49
  OTLPTraceExporter = require("@opentelemetry/exporter-trace-otlp-http").OTLPTraceExporter;
36
- require("@opentelemetry/instrumentation-http").HttpInstrumentation;
37
- require("@opentelemetry/instrumentation-mongodb").MongoDBInstrumentation;
50
+ require("@opentelemetry/instrumentation-http");
51
+ require("@opentelemetry/instrumentation-mongodb");
38
52
  getNodeAutoInstrumentations = require("@opentelemetry/auto-instrumentations-node").getNodeAutoInstrumentations;
39
53
  isAvailable = true;
40
54
  } catch (_e) {}
@@ -42,9 +56,9 @@ try {
42
56
  * Create a tracer provider
43
57
  */
44
58
  function createTracerProvider(options) {
45
- if (!isAvailable) return null;
59
+ if (!isAvailable || !NodeTracerProvider || !BatchSpanProcessor || !OTLPTraceExporter) return null;
46
60
  const { serviceName = "@classytic/arc", serviceVersion, exporterUrl = "http://localhost:4318/v1/traces" } = options;
47
- const resolvedVersion = serviceVersion ?? "2.10.8";
61
+ const resolvedVersion = serviceVersion ?? "2.11.1";
48
62
  const exporter = new OTLPTraceExporter({ url: exporterUrl });
49
63
  const provider = new NodeTracerProvider({ resource: { attributes: {
50
64
  "service.name": serviceName,
@@ -59,11 +73,14 @@ function createTracerProvider(options) {
59
73
  */
60
74
  async function tracingPlugin(fastify, options = {}) {
61
75
  const { serviceName = "@classytic/arc", autoInstrumentation = true, sampleRate = 1 } = options;
62
- if (!isAvailable) {
76
+ if (!isAvailable || !trace || !context || !SpanStatusCode) {
63
77
  fastify.log.warn("OpenTelemetry not installed. Tracing disabled.");
64
78
  fastify.log.warn("Install: npm install @opentelemetry/api @opentelemetry/sdk-node");
65
79
  return;
66
80
  }
81
+ const otelTrace = trace;
82
+ const otelContext = context;
83
+ const otelStatus = SpanStatusCode;
67
84
  if (!createTracerProvider(options)) return;
68
85
  if (autoInstrumentation && getNodeAutoInstrumentations) {
69
86
  const instrumentations = getNodeAutoInstrumentations({
@@ -73,7 +90,7 @@ async function tracingPlugin(fastify, options = {}) {
73
90
  for (const instrumentation of instrumentations) instrumentation.enable();
74
91
  fastify.log.debug("OpenTelemetry auto-instrumentation enabled");
75
92
  }
76
- const tracer = trace.getTracer(serviceName);
93
+ const tracer = otelTrace.getTracer(serviceName);
77
94
  fastify.decorateRequest("tracer", void 0);
78
95
  fastify.addHook("onRequest", async (request, _reply) => {
79
96
  if (Math.random() > sampleRate) return;
@@ -92,7 +109,7 @@ async function tracingPlugin(fastify, options = {}) {
92
109
  tracer,
93
110
  currentSpan: span
94
111
  };
95
- context.with(trace.setSpan(context.active(), span), () => {});
112
+ otelContext.with(otelTrace.setSpan(otelContext.active(), span), () => {});
96
113
  });
97
114
  fastify.addHook("onResponse", async (request, reply) => {
98
115
  if (!request.tracer?.currentSpan) return;
@@ -101,11 +118,11 @@ async function tracingPlugin(fastify, options = {}) {
101
118
  "http.status_code": reply.statusCode,
102
119
  "http.response_content_length": reply.getHeader("content-length")
103
120
  });
104
- if (reply.statusCode >= 500) span.setStatus({
105
- code: SpanStatusCode.ERROR,
121
+ const status = reply.statusCode >= 500 ? {
122
+ code: otelStatus.ERROR,
106
123
  message: `HTTP ${reply.statusCode}`
107
- });
108
- else span.setStatus({ code: SpanStatusCode.OK });
124
+ } : { code: otelStatus.OK };
125
+ span.setStatus(status);
109
126
  span.end();
110
127
  });
111
128
  fastify.addHook("onError", async (request, _reply, error) => {
@@ -113,7 +130,7 @@ async function tracingPlugin(fastify, options = {}) {
113
130
  const span = request.tracer.currentSpan;
114
131
  span.recordException(error);
115
132
  span.setStatus({
116
- code: SpanStatusCode.ERROR,
133
+ code: otelStatus.ERROR,
117
134
  message: error.message
118
135
  });
119
136
  });
@@ -133,22 +150,23 @@ async function tracingPlugin(fastify, options = {}) {
133
150
  * }
134
151
  */
135
152
  function createSpan(request, name, fn, attributes) {
136
- if (!request.tracer) return fn(null);
153
+ if (!request.tracer || !trace || !context || !SpanStatusCode) return fn(null);
154
+ const otelTrace = trace;
155
+ const otelContext = context;
156
+ const otelStatus = SpanStatusCode;
137
157
  const { tracer, currentSpan } = request.tracer;
138
- const span = tracer.startSpan(name, {
139
- parent: currentSpan,
140
- attributes: attributes || {}
141
- }, trace.setSpan(context.active(), currentSpan));
142
- return context.with(trace.setSpan(context.active(), span), async () => {
158
+ const span = tracer.startSpan(name, { attributes: attributes ?? {} }, otelTrace.setSpan(otelContext.active(), currentSpan));
159
+ return otelContext.with(otelTrace.setSpan(otelContext.active(), span), async () => {
143
160
  try {
144
161
  const result = await fn(span);
145
- span.setStatus({ code: SpanStatusCode.OK });
162
+ span.setStatus({ code: otelStatus.OK });
146
163
  return result;
147
164
  } catch (error) {
148
- span.recordException(error);
165
+ const err = error;
166
+ span.recordException(err);
149
167
  span.setStatus({
150
- code: SpanStatusCode.ERROR,
151
- message: error.message
168
+ code: otelStatus.ERROR,
169
+ message: err.message
152
170
  });
153
171
  throw error;
154
172
  } finally {
@@ -171,9 +189,9 @@ function traced(spanName) {
171
189
  return (target, propertyKey, descriptor) => {
172
190
  const originalMethod = descriptor.value;
173
191
  descriptor.value = async function(...args) {
174
- const request = args.find((arg) => arg?.tracer);
192
+ const request = args.find((arg) => !!(arg && typeof arg === "object" && "tracer" in arg && arg.tracer));
175
193
  if (!request?.tracer) return originalMethod.apply(this, args);
176
- return createSpan(request, spanName || `${target.constructor.name}.${propertyKey}`, async (span) => {
194
+ return createSpan(request, spanName ?? `${target.constructor.name}.${propertyKey}`, async (span) => {
177
195
  if (span) {
178
196
  span.setAttribute("db.operation", propertyKey);
179
197
  span.setAttribute("db.system", "mongodb");
@@ -1,4 +1,4 @@
1
- import { _t as PresetResult } from "../index-BGbpGVyM.mjs";
1
+ import { nt as PresetResult } from "../index-C_bgx9o4.mjs";
2
2
  import { r as RequestScope } from "../types-tgR4Pt8F.mjs";
3
3
  import { c as PermissionCheck } from "../fields-C8Y0XLAu.mjs";
4
4
  import { a as StorageReadResult, i as StorageReadRange, n as StorageContext, o as StorageUploadInput, r as StorageFile, t as Storage } from "../storage-BwGQXUpd.mjs";
@@ -1,7 +1,7 @@
1
1
  import { o as getOrgId, p as getUserId } from "../types-AOD8fxIw.mjs";
2
- import { i as NotFoundError, u as ValidationError } from "../errors-BqdUDja_.mjs";
3
- import { C as requireAuth, y as allowPublic } from "../permissions-wkqRwicB.mjs";
4
- import { t as multipartBody } from "../multipartBody-CUQGVlM_.mjs";
2
+ import { C as requireAuth, y as allowPublic } from "../permissions-B4vU9L0Q.mjs";
3
+ import { i as NotFoundError, u as ValidationError } from "../errors-D5c-5BJL.mjs";
4
+ import { t as multipartBody } from "../multipartBody-CvTR1Un6.mjs";
5
5
  //#region src/presets/filesUpload.ts
6
6
  const DEFAULT_FIELD_NAME = "file";
7
7
  const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;
@@ -1,4 +1,4 @@
1
- import { Mt as IControllerResponse, Nt as IRequestContext, Yt as AnyRecord, _t as PresetResult, bt as ResourceConfig, d as PaginationResult } from "../index-BGbpGVyM.mjs";
1
+ import { Pt as AnyRecord, _t as IControllerResponse, at as ResourceConfig, d as PaginationResult, nt as PresetResult, vt as IRequestContext } from "../index-C_bgx9o4.mjs";
2
2
  import { FilesUploadPresetOptions, FilesUploadPresetPermissions, FilesUploadPresetRoutes, filesUploadPreset } from "./filesUpload.mjs";
3
3
  import { MultiTenantOptions, TenantFieldSpec, multiTenantPreset } from "./multiTenant.mjs";
4
4
  import { SearchHandler, SearchPresetOptions, SearchRouteConfig, searchPreset } from "./search.mjs";
@@ -1,5 +1,5 @@
1
1
  import { multiTenantPreset } from "./multiTenant.mjs";
2
- import { a as registerPreset, c as auditedPreset, d as ownedByUserPreset, i as getPreset, l as softDeletePreset, n as flexibleMultiTenantPreset, o as treePreset, r as getAvailablePresets, s as bulkPreset, t as applyPresets, u as slugLookupPreset } from "../presets-CrwOvuXI.mjs";
2
+ import { a as registerPreset, c as auditedPreset, d as ownedByUserPreset, i as getPreset, l as softDeletePreset, n as flexibleMultiTenantPreset, o as treePreset, r as getAvailablePresets, s as bulkPreset, t as applyPresets, u as slugLookupPreset } from "../presets-k604Lj99.mjs";
3
3
  import { filesUploadPreset } from "./filesUpload.mjs";
4
4
  import { searchPreset } from "./search.mjs";
5
5
  export { applyPresets, auditedPreset, bulkPreset, filesUploadPreset, flexibleMultiTenantPreset, getAvailablePresets, getPreset, multiTenantPreset, ownedByUserPreset, registerPreset, searchPreset, slugLookupPreset, softDeletePreset, treePreset };
@@ -1,4 +1,4 @@
1
- import { _t as PresetResult, lt as CrudRouteKey } from "../index-BGbpGVyM.mjs";
1
+ import { J as CrudRouteKey, nt as PresetResult } from "../index-C_bgx9o4.mjs";
2
2
 
3
3
  //#region src/presets/multiTenant.d.ts
4
4
  /**
@@ -172,8 +172,14 @@ function multiTenantPreset(options = {}) {
172
172
  const flexibleTenantFilter = createFlexibleTenantFilter(specs);
173
173
  const tenantInjection = createTenantInjection(specs);
174
174
  const getFilter = (route) => allowPublic.includes(route) ? flexibleTenantFilter : strictTenantFilter;
175
+ const fieldRules = {};
176
+ for (const spec of specs) fieldRules[spec.field] = {
177
+ systemManaged: true,
178
+ preserveForElevated: true
179
+ };
175
180
  return {
176
181
  name: "multiTenant",
182
+ schemaOptions: { fieldRules },
177
183
  middlewares: {
178
184
  list: [getFilter("list")],
179
185
  get: [getFilter("get")],
@@ -1,4 +1,4 @@
1
- import { Ot as ControllerHandler, Tt as RouteMcpConfig, _t as PresetResult, wt as RouteDefinition } from "../index-BGbpGVyM.mjs";
1
+ import { lt as RouteDefinition, nt as PresetResult, pt as ControllerHandler, ut as RouteMcpConfig } from "../index-C_bgx9o4.mjs";
2
2
  import { c as PermissionCheck } from "../fields-C8Y0XLAu.mjs";
3
3
 
4
4
  //#region src/presets/search.d.ts
@@ -1,4 +1,4 @@
1
- import { C as requireAuth, y as allowPublic } from "../permissions-wkqRwicB.mjs";
1
+ import { C as requireAuth, y as allowPublic } from "../permissions-B4vU9L0Q.mjs";
2
2
  //#region src/presets/search.ts
3
3
  const BUILTINS = [
4
4
  {
@@ -1,6 +1,6 @@
1
1
  import { _ as isElevated, n as PUBLIC_SCOPE } from "./types-AOD8fxIw.mjs";
2
+ import { C as requireAuth, T as requireRoles, y as allowPublic } from "./permissions-B4vU9L0Q.mjs";
2
3
  import { multiTenantPreset } from "./presets/multiTenant.mjs";
3
- import { C as requireAuth, T as requireRoles, y as allowPublic } from "./permissions-wkqRwicB.mjs";
4
4
  //#region src/presets/ownedByUser.ts
5
5
  /**
6
6
  * Create ownership check middleware.
@@ -0,0 +1,34 @@
1
+ import { r as CacheStore } from "./interface-Da0r7Lna.mjs";
2
+ import { i as QueryCache } from "./QueryCache-DOBNHBE0.mjs";
3
+ import { FastifyPluginAsync } from "fastify";
4
+
5
+ //#region src/cache/queryCachePlugin.d.ts
6
+ interface QueryCachePluginOptions {
7
+ /** CacheStore instance. Default: MemoryCacheStore with default options. */
8
+ store?: CacheStore;
9
+ /** Global defaults for staleTime/gcTime (seconds) */
10
+ defaults?: {
11
+ staleTime?: number;
12
+ gcTime?: number;
13
+ };
14
+ }
15
+ interface QueryCacheDefaults {
16
+ staleTime: number;
17
+ gcTime: number;
18
+ }
19
+ /** Cross-resource invalidation rules collected from resource configs */
20
+ interface CrossResourceRule {
21
+ pattern: string;
22
+ tags: string[];
23
+ }
24
+ declare module "fastify" {
25
+ interface FastifyInstance {
26
+ queryCache: QueryCache;
27
+ queryCacheConfig: QueryCacheDefaults;
28
+ /** Register cross-resource invalidation rules (called by defineResource) */
29
+ registerCacheInvalidationRule?(rule: CrossResourceRule): void;
30
+ }
31
+ }
32
+ declare const queryCachePlugin: FastifyPluginAsync<QueryCachePluginOptions>;
33
+ //#endregion
34
+ export { queryCachePlugin as i, QueryCacheDefaults as n, QueryCachePluginOptions as r, CrossResourceRule as t };
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./chunk-BpYLSNr0.mjs";
2
- import { i as versionKey, r as tagVersionKey } from "./keys-nWQGUTu1.mjs";
3
- import { t as hasEvents } from "./typeGuards-Cj5Rgvlg.mjs";
4
- import { t as MemoryCacheStore } from "./memory-DqI-449b.mjs";
2
+ import { i as versionKey, r as tagVersionKey } from "./keys-CARyUjiR.mjs";
3
+ import { t as MemoryCacheStore } from "./memory-DikHSvWa.mjs";
4
+ import { t as hasEvents } from "./typeGuards-CcFZXgU7.mjs";
5
5
  import fp from "fastify-plugin";
6
6
  //#region src/cache/QueryCache.ts
7
7
  var QueryCache = class {
@@ -1,4 +1,4 @@
1
- import { n as IdempotencyResult, r as IdempotencyStore } from "./interface-B-pe8fhj.mjs";
1
+ import { n as IdempotencyResult, r as IdempotencyStore } from "./interface-CkkWm5uR.mjs";
2
2
 
3
3
  //#region src/idempotency/stores/redis.d.ts
4
4
  interface RedisClient {
@@ -1,4 +1,4 @@
1
- import { R as RegisterOptions, k as IntrospectionPluginOptions, z as ResourceRegistry } from "../index-BGbpGVyM.mjs";
1
+ import { R as RegisterOptions, k as IntrospectionPluginOptions, z as ResourceRegistry } from "../index-C_bgx9o4.mjs";
2
2
  import { FastifyPluginAsync } from "fastify";
3
3
 
4
4
  //#region src/registry/introspectionPlugin.d.ts
@@ -1,3 +1,3 @@
1
- import { n as introspectionPlugin_default, t as introspectionPlugin } from "../registry-B0Wl7uVV.mjs";
2
- import { t as ResourceRegistry } from "../ResourceRegistry-CcN2LVrc.mjs";
1
+ import { n as introspectionPlugin_default, t as introspectionPlugin } from "../registry-D63ee7fl.mjs";
2
+ import { t as ResourceRegistry } from "../ResourceRegistry-DkAeAuTX.mjs";
3
3
  export { ResourceRegistry, introspectionPlugin_default as introspectionPlugin, introspectionPlugin as introspectionPluginFn };