@classytic/arc 2.2.5 → 2.4.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.
- package/README.md +187 -18
- package/bin/arc.js +11 -3
- package/dist/BaseController-CkM5dUh_.mjs +1031 -0
- package/dist/{EventTransport-BkUDYZEb.d.mts → EventTransport-wc5hSLik.d.mts} +1 -1
- package/dist/{HookSystem-BsGV-j2l.mjs → HookSystem-COkyWztM.mjs} +2 -3
- package/dist/{ResourceRegistry-7Ic20ZMw.mjs → ResourceRegistry-DeCIFlix.mjs} +8 -5
- package/dist/adapters/index.d.mts +3 -5
- package/dist/adapters/index.mjs +2 -3
- package/dist/{prisma-DJbMt3yf.mjs → adapters-DTC4Ug66.mjs} +45 -12
- package/dist/audit/index.d.mts +4 -7
- package/dist/audit/index.mjs +2 -29
- package/dist/audit/mongodb.d.mts +1 -4
- package/dist/audit/mongodb.mjs +2 -3
- package/dist/auth/index.d.mts +7 -9
- package/dist/auth/index.mjs +65 -63
- package/dist/auth/redis-session.d.mts +1 -1
- package/dist/auth/redis-session.mjs +1 -2
- package/dist/{betterAuthOpenApi-DjWDddNc.mjs → betterAuthOpenApi-lz0IRbXJ.mjs} +4 -6
- package/dist/cache/index.d.mts +23 -23
- package/dist/cache/index.mjs +4 -6
- package/dist/{caching-GSDJcA6-.mjs → caching-BSXB-Xr7.mjs} +2 -24
- package/dist/chunk-BpYLSNr0.mjs +14 -0
- package/dist/circuitBreaker-BOBOpN2w.mjs +284 -0
- package/dist/circuitBreaker-JP2GdJ4b.d.mts +206 -0
- package/dist/cli/commands/describe.mjs +24 -7
- package/dist/cli/commands/docs.mjs +6 -7
- package/dist/cli/commands/doctor.d.mts +10 -0
- package/dist/cli/commands/doctor.mjs +156 -0
- package/dist/cli/commands/generate.mjs +66 -17
- package/dist/cli/commands/init.mjs +315 -45
- package/dist/cli/commands/introspect.mjs +2 -4
- package/dist/cli/index.d.mts +1 -10
- package/dist/cli/index.mjs +4 -153
- package/dist/{constants-DdXFXQtN.mjs → constants-Cxde4rpC.mjs} +1 -2
- package/dist/core/index.d.mts +3 -5
- package/dist/core/index.mjs +5 -4
- package/dist/core-C1XCMtqM.mjs +185 -0
- package/dist/{createApp-BKHSl2nT.mjs → createApp-ByWNRsZj.mjs} +65 -36
- package/dist/{defineResource-DO9ONe_D.mjs → defineResource-D9aY5Cy6.mjs} +154 -1165
- package/dist/discovery/index.mjs +37 -5
- package/dist/docs/index.d.mts +6 -9
- package/dist/docs/index.mjs +3 -21
- package/dist/dynamic/index.d.mts +93 -0
- package/dist/dynamic/index.mjs +122 -0
- package/dist/{elevation-DSTbVvYj.mjs → elevation-BEdACOLB.mjs} +5 -36
- package/dist/{elevation-DGo5shaX.d.mts → elevation-Ca_yveIO.d.mts} +41 -7
- package/dist/{errorHandler-C3GY3_ow.mjs → errorHandler--zp54tGc.mjs} +3 -5
- package/dist/errorHandler-Do4vVQ1f.d.mts +139 -0
- package/dist/{errors-DBANPbGr.mjs → errors-rxhfP7Hf.mjs} +1 -2
- package/dist/{eventPlugin-BEOvaDqo.mjs → eventPlugin-Ba00swHF.mjs} +25 -27
- package/dist/{eventPlugin-H6wDDjGO.d.mts → eventPlugin-iGrSEmwJ.d.mts} +105 -5
- package/dist/events/index.d.mts +72 -7
- package/dist/events/index.mjs +216 -4
- package/dist/events/transports/redis-stream-entry.d.mts +1 -1
- package/dist/events/transports/redis-stream-entry.mjs +19 -7
- package/dist/events/transports/redis.d.mts +1 -1
- package/dist/events/transports/redis.mjs +3 -4
- package/dist/factory/index.d.mts +23 -9
- package/dist/factory/index.mjs +48 -3
- package/dist/{fields-Bi_AVKSo.d.mts → fields-DFwdaWCq.d.mts} +1 -1
- package/dist/{fields-CTd_CrKr.mjs → fields-ipsbIRPK.mjs} +1 -2
- package/dist/hooks/index.d.mts +1 -3
- package/dist/hooks/index.mjs +2 -3
- package/dist/idempotency/index.d.mts +5 -5
- package/dist/idempotency/index.mjs +3 -7
- package/dist/idempotency/mongodb.d.mts +1 -1
- package/dist/idempotency/mongodb.mjs +4 -5
- package/dist/idempotency/redis.d.mts +1 -1
- package/dist/idempotency/redis.mjs +2 -5
- package/dist/{fastifyAdapter-CyAA2zlB.d.mts → index-BL8CaQih.d.mts} +56 -57
- package/dist/index-Diqcm14c.d.mts +369 -0
- package/dist/{prisma-xjhMEq_S.d.mts → index-yhxyjqNb.d.mts} +4 -5
- package/dist/index.d.mts +100 -105
- package/dist/index.mjs +85 -58
- package/dist/integrations/event-gateway.d.mts +1 -1
- package/dist/integrations/event-gateway.mjs +8 -4
- package/dist/integrations/index.d.mts +4 -2
- package/dist/integrations/index.mjs +1 -1
- package/dist/integrations/jobs.d.mts +2 -2
- package/dist/integrations/jobs.mjs +63 -14
- package/dist/integrations/mcp/index.d.mts +219 -0
- package/dist/integrations/mcp/index.mjs +572 -0
- package/dist/integrations/mcp/testing.d.mts +53 -0
- package/dist/integrations/mcp/testing.mjs +104 -0
- package/dist/integrations/streamline.mjs +39 -19
- package/dist/integrations/webhooks.d.mts +56 -0
- package/dist/integrations/webhooks.mjs +139 -0
- package/dist/integrations/websocket-redis.d.mts +46 -0
- package/dist/integrations/websocket-redis.mjs +50 -0
- package/dist/integrations/websocket.d.mts +68 -2
- package/dist/integrations/websocket.mjs +96 -13
- package/dist/{interface-CSNjltAc.d.mts → interface-B4awm1RJ.d.mts} +2 -2
- package/dist/interface-DGmPxakH.d.mts +2213 -0
- package/dist/{keys-DhqDRxv3.mjs → keys-qcD-TVJl.mjs} +3 -4
- package/dist/{logger-ByrvQWZO.mjs → logger-Dz3j1ItV.mjs} +2 -4
- package/dist/{memory-B2v7KrCB.mjs → memory-Cb_7iy9e.mjs} +2 -4
- package/dist/metrics-Csh4nsvv.mjs +224 -0
- package/dist/migrations/index.mjs +3 -7
- package/dist/{mongodb-DNKEExbf.mjs → mongodb-BuQ7fNTg.mjs} +1 -4
- package/dist/{mongodb-ClykrfGo.d.mts → mongodb-CUpYfxfD.d.mts} +2 -3
- package/dist/{mongodb-Dg8O_gvd.d.mts → mongodb-bga9AbkD.d.mts} +2 -2
- package/dist/{openapi-9nB_kiuR.mjs → openapi-CBmZ6EQN.mjs} +4 -21
- package/dist/org/index.d.mts +12 -14
- package/dist/org/index.mjs +92 -119
- package/dist/org/types.d.mts +2 -2
- package/dist/org/types.mjs +1 -1
- package/dist/permissions/index.d.mts +4 -278
- package/dist/permissions/index.mjs +4 -579
- package/dist/permissions-CA5zg0yK.mjs +751 -0
- package/dist/plugins/index.d.mts +104 -107
- package/dist/plugins/index.mjs +203 -313
- package/dist/plugins/response-cache.mjs +4 -69
- package/dist/plugins/tracing-entry.d.mts +1 -1
- package/dist/plugins/tracing-entry.mjs +24 -11
- package/dist/{pluralize-CM-jZg7p.mjs → pluralize-CcT6qF0a.mjs} +12 -13
- package/dist/policies/index.d.mts +2 -2
- package/dist/policies/index.mjs +80 -83
- package/dist/presets/index.d.mts +26 -19
- package/dist/presets/index.mjs +2 -142
- package/dist/presets/multiTenant.d.mts +1 -4
- package/dist/presets/multiTenant.mjs +4 -6
- package/dist/presets-C9QXJV1u.mjs +422 -0
- package/dist/{queryCachePlugin-B6R0d4av.mjs → queryCachePlugin-ClosZdNS.mjs} +6 -27
- package/dist/{queryCachePlugin-Q6SYuHZ6.d.mts → queryCachePlugin-DcmETvcB.d.mts} +3 -3
- package/dist/queryParser-CgCtsjti.mjs +352 -0
- package/dist/{redis-UwjEp8Ea.d.mts → redis-CQ5YxMC5.d.mts} +2 -2
- package/dist/{redis-stream-CBg0upHI.d.mts → redis-stream-BW9UKLZM.d.mts} +9 -2
- package/dist/registry/index.d.mts +1 -4
- package/dist/registry/index.mjs +3 -4
- package/dist/{introspectionPlugin-B3JkrjwU.mjs → registry-I-ogLgL9.mjs} +1 -8
- package/dist/{requestContext-xi6OKBL-.mjs → requestContext-DYtmNpm5.mjs} +1 -3
- package/dist/resourceToTools-B6ZN9Ing.mjs +489 -0
- package/dist/rpc/index.d.mts +90 -0
- package/dist/rpc/index.mjs +248 -0
- package/dist/{schemaConverter-Dtg0Kt9T.mjs → schemaConverter-DjzHpFam.mjs} +1 -2
- package/dist/schemas/index.d.mts +30 -30
- package/dist/schemas/index.mjs +4 -6
- package/dist/scope/index.d.mts +13 -2
- package/dist/scope/index.mjs +18 -5
- package/dist/{sessionManager-D_iEHjQl.d.mts → sessionManager-wbkYj2HL.d.mts} +2 -2
- package/dist/{sse-DkqQ1uxb.mjs → sse-BkViJPlT.mjs} +4 -25
- package/dist/testing/index.d.mts +551 -567
- package/dist/testing/index.mjs +1744 -1799
- package/dist/{tracing-8CEbhF0w.d.mts → tracing-bz_U4EM1.d.mts} +6 -1
- package/dist/{typeGuards-DwxA1t_L.mjs → typeGuards-Cj5Rgvlg.mjs} +1 -2
- package/dist/types/index.d.mts +4 -946
- package/dist/types/index.mjs +2 -4
- package/dist/types-BJmgxNbF.d.mts +275 -0
- package/dist/{types-RLkFVgaw.d.mts → types-BNUccdcf.d.mts} +2 -2
- package/dist/{types-Beqn1Un7.mjs → types-C6TQjtdi.mjs} +30 -2
- package/dist/{types-DMSBMkaZ.d.mts → types-Dt0-AI6E.d.mts} +85 -27
- package/dist/{types-DelU6kln.mjs → types-ZUu_h0jp.mjs} +1 -2
- package/dist/utils/index.d.mts +255 -352
- package/dist/utils/index.mjs +7 -6
- package/dist/utils-Dc0WhlIl.mjs +594 -0
- package/dist/versioning-BzfeHmhj.mjs +37 -0
- package/package.json +46 -12
- package/skills/arc/SKILL.md +506 -0
- package/skills/arc/references/auth.md +250 -0
- package/skills/arc/references/events.md +272 -0
- package/skills/arc/references/integrations.md +385 -0
- package/skills/arc/references/mcp.md +386 -0
- package/skills/arc/references/production.md +610 -0
- package/skills/arc/references/testing.md +183 -0
- package/dist/audited-CGdLiSlE.mjs +0 -140
- package/dist/chunk-C7Uep-_p.mjs +0 -20
- package/dist/circuitBreaker-DYhWBW_D.mjs +0 -1096
- package/dist/errorHandler-CW3OOeYq.d.mts +0 -72
- package/dist/interface-DZYNK9bb.d.mts +0 -1112
- package/dist/presets-BTeYbw7h.d.mts +0 -57
- package/dist/presets-CeFtfDR8.mjs +0 -119
- /package/dist/{errors-DAWRdiYP.d.mts → errors-CPpvPHT0.d.mts} +0 -0
- /package/dist/{externalPaths-SyPF2tgK.d.mts → externalPaths-DpO-s7r8.d.mts} +0 -0
- /package/dist/{interface-DTbsvIWe.d.mts → interface-D_BWALyZ.d.mts} +0 -0
|
@@ -1,1096 +0,0 @@
|
|
|
1
|
-
import { d as MAX_REGEX_LENGTH, f as MAX_SEARCH_LENGTH, i as DEFAULT_MAX_LIMIT, m as RESERVED_QUERY_PARAMS, r as DEFAULT_LIMIT, u as MAX_FILTER_DEPTH } from "./constants-DdXFXQtN.mjs";
|
|
2
|
-
|
|
3
|
-
//#region src/utils/queryParser.ts
|
|
4
|
-
/**
|
|
5
|
-
* Regex patterns that can cause catastrophic backtracking (ReDoS attacks)
|
|
6
|
-
* Detects:
|
|
7
|
-
* - Quantifiers: {n,m}
|
|
8
|
-
* - Possessive quantifiers: *+, ++, ?+
|
|
9
|
-
* - Nested quantifiers: (a+)+, (a*)*
|
|
10
|
-
* - Backreferences: \1, \2, etc.
|
|
11
|
-
*/
|
|
12
|
-
const DANGEROUS_REGEX_PATTERNS = /(\{[0-9,]+\}|\*\+|\+\+|\?\+|(\(.+\))\+|\(\?\:|\\[0-9]|(\[.+\]).+(\[.+\]))/;
|
|
13
|
-
/**
|
|
14
|
-
* Arc's default query parser
|
|
15
|
-
*
|
|
16
|
-
* Converts URL query parameters to a structured query format:
|
|
17
|
-
* - Pagination: ?page=1&limit=20
|
|
18
|
-
* - Sorting: ?sort=-createdAt,name (- prefix = descending)
|
|
19
|
-
* - Filtering: ?status=active&price[gte]=100&price[lte]=500
|
|
20
|
-
* - Search: ?search=keyword
|
|
21
|
-
* - Populate: ?populate=author,category
|
|
22
|
-
* - Field selection: ?select=name,price,status
|
|
23
|
-
* - Keyset pagination: ?after=cursor_value
|
|
24
|
-
*
|
|
25
|
-
* For advanced MongoDB features ($lookup, aggregations), use MongoKit's QueryParser.
|
|
26
|
-
*/
|
|
27
|
-
var ArcQueryParser = class {
|
|
28
|
-
maxLimit;
|
|
29
|
-
defaultLimit;
|
|
30
|
-
maxRegexLength;
|
|
31
|
-
maxSearchLength;
|
|
32
|
-
maxFilterDepth;
|
|
33
|
-
/** Supported filter operators */
|
|
34
|
-
operators = {
|
|
35
|
-
eq: "$eq",
|
|
36
|
-
ne: "$ne",
|
|
37
|
-
gt: "$gt",
|
|
38
|
-
gte: "$gte",
|
|
39
|
-
lt: "$lt",
|
|
40
|
-
lte: "$lte",
|
|
41
|
-
in: "$in",
|
|
42
|
-
nin: "$nin",
|
|
43
|
-
like: "$regex",
|
|
44
|
-
contains: "$regex",
|
|
45
|
-
regex: "$regex",
|
|
46
|
-
exists: "$exists"
|
|
47
|
-
};
|
|
48
|
-
constructor(options = {}) {
|
|
49
|
-
this.maxLimit = options.maxLimit ?? DEFAULT_MAX_LIMIT;
|
|
50
|
-
this.defaultLimit = options.defaultLimit ?? DEFAULT_LIMIT;
|
|
51
|
-
this.maxRegexLength = options.maxRegexLength ?? MAX_REGEX_LENGTH;
|
|
52
|
-
this.maxSearchLength = options.maxSearchLength ?? MAX_SEARCH_LENGTH;
|
|
53
|
-
this.maxFilterDepth = options.maxFilterDepth ?? MAX_FILTER_DEPTH;
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* Parse URL query parameters into structured query options
|
|
57
|
-
*/
|
|
58
|
-
parse(query) {
|
|
59
|
-
const q = query ?? {};
|
|
60
|
-
const page = this.parseNumber(q.page, 1);
|
|
61
|
-
const limit = Math.min(this.parseNumber(q.limit, this.defaultLimit), this.maxLimit);
|
|
62
|
-
const after = this.parseString(q.after ?? q.cursor);
|
|
63
|
-
const sort = this.parseSort(q.sort);
|
|
64
|
-
const { populate, populateOptions } = this.parsePopulate(q.populate);
|
|
65
|
-
const search = this.parseSearch(q.search);
|
|
66
|
-
const select = this.parseSelect(q.select);
|
|
67
|
-
return {
|
|
68
|
-
filters: this.parseFilters(q),
|
|
69
|
-
limit,
|
|
70
|
-
sort,
|
|
71
|
-
populate,
|
|
72
|
-
populateOptions,
|
|
73
|
-
search,
|
|
74
|
-
page: after ? void 0 : page,
|
|
75
|
-
after,
|
|
76
|
-
select
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
parseNumber(value, defaultValue) {
|
|
80
|
-
if (value === void 0 || value === null) return defaultValue;
|
|
81
|
-
const num = parseInt(String(value), 10);
|
|
82
|
-
return Number.isNaN(num) ? defaultValue : Math.max(1, num);
|
|
83
|
-
}
|
|
84
|
-
parseString(value) {
|
|
85
|
-
if (value === void 0 || value === null) return void 0;
|
|
86
|
-
const str = String(value).trim();
|
|
87
|
-
return str.length > 0 ? str : void 0;
|
|
88
|
-
}
|
|
89
|
-
/**
|
|
90
|
-
* Parse populate parameter — handles both simple string and bracket notation.
|
|
91
|
-
*
|
|
92
|
-
* Simple: ?populate=author,category → { populate: 'author,category' }
|
|
93
|
-
* Bracket: ?populate[author][select]=name,email → { populateOptions: [{ path: 'author', select: 'name email' }] }
|
|
94
|
-
*/
|
|
95
|
-
parsePopulate(value) {
|
|
96
|
-
if (value === void 0 || value === null) return {};
|
|
97
|
-
if (typeof value === "string") {
|
|
98
|
-
const trimmed = value.trim();
|
|
99
|
-
return trimmed.length > 0 ? { populate: trimmed } : {};
|
|
100
|
-
}
|
|
101
|
-
if (typeof value === "object" && !Array.isArray(value)) {
|
|
102
|
-
const obj = value;
|
|
103
|
-
const keys = Object.keys(obj);
|
|
104
|
-
if (keys.length === 0) return {};
|
|
105
|
-
const options = [];
|
|
106
|
-
for (const path of keys) {
|
|
107
|
-
if (!/^[a-zA-Z_][a-zA-Z0-9_.]*$/.test(path)) continue;
|
|
108
|
-
const config = obj[path];
|
|
109
|
-
if (typeof config === "object" && config !== null && !Array.isArray(config)) {
|
|
110
|
-
const cfg = config;
|
|
111
|
-
const option = { path };
|
|
112
|
-
if (typeof cfg.select === "string") option.select = cfg.select.split(",").map((s) => s.trim()).filter(Boolean).join(" ");
|
|
113
|
-
if (typeof cfg.match === "object" && cfg.match !== null) option.match = cfg.match;
|
|
114
|
-
options.push(option);
|
|
115
|
-
} else options.push({ path });
|
|
116
|
-
}
|
|
117
|
-
return options.length > 0 ? { populateOptions: options } : {};
|
|
118
|
-
}
|
|
119
|
-
return {};
|
|
120
|
-
}
|
|
121
|
-
parseSort(value) {
|
|
122
|
-
if (!value) return void 0;
|
|
123
|
-
const sortStr = String(value);
|
|
124
|
-
const result = {};
|
|
125
|
-
for (const field of sortStr.split(",")) {
|
|
126
|
-
const trimmed = field.trim();
|
|
127
|
-
if (!trimmed) continue;
|
|
128
|
-
if (!/^-?[a-zA-Z_][a-zA-Z0-9_.]*$/.test(trimmed)) continue;
|
|
129
|
-
if (trimmed.startsWith("-")) result[trimmed.slice(1)] = -1;
|
|
130
|
-
else result[trimmed] = 1;
|
|
131
|
-
}
|
|
132
|
-
return Object.keys(result).length > 0 ? result : void 0;
|
|
133
|
-
}
|
|
134
|
-
parseSearch(value) {
|
|
135
|
-
if (!value) return void 0;
|
|
136
|
-
const search = String(value).trim();
|
|
137
|
-
if (search.length === 0) return void 0;
|
|
138
|
-
if (search.length > this.maxSearchLength) return search.slice(0, this.maxSearchLength);
|
|
139
|
-
return search;
|
|
140
|
-
}
|
|
141
|
-
parseSelect(value) {
|
|
142
|
-
if (!value) return void 0;
|
|
143
|
-
const selectStr = String(value);
|
|
144
|
-
const result = {};
|
|
145
|
-
for (const field of selectStr.split(",")) {
|
|
146
|
-
const trimmed = field.trim();
|
|
147
|
-
if (!trimmed) continue;
|
|
148
|
-
if (!/^-?[a-zA-Z_][a-zA-Z0-9_.]*$/.test(trimmed)) continue;
|
|
149
|
-
if (trimmed.startsWith("-")) result[trimmed.slice(1)] = 0;
|
|
150
|
-
else result[trimmed] = 1;
|
|
151
|
-
}
|
|
152
|
-
return Object.keys(result).length > 0 ? result : void 0;
|
|
153
|
-
}
|
|
154
|
-
/**
|
|
155
|
-
* Check if a value exceeds the maximum nesting depth.
|
|
156
|
-
* Prevents filter bombs where deeply nested objects consume excessive memory/CPU.
|
|
157
|
-
*/
|
|
158
|
-
exceedsDepth(obj, currentDepth = 0) {
|
|
159
|
-
if (currentDepth > this.maxFilterDepth) return true;
|
|
160
|
-
if (obj === null || obj === void 0) return false;
|
|
161
|
-
if (Array.isArray(obj)) return obj.some((v) => this.exceedsDepth(v, currentDepth));
|
|
162
|
-
if (typeof obj !== "object") return false;
|
|
163
|
-
return Object.values(obj).some((v) => this.exceedsDepth(v, currentDepth + 1));
|
|
164
|
-
}
|
|
165
|
-
parseFilters(query) {
|
|
166
|
-
const filters = {};
|
|
167
|
-
for (const [key, value] of Object.entries(query)) {
|
|
168
|
-
if (RESERVED_QUERY_PARAMS.has(key)) continue;
|
|
169
|
-
if (value === void 0 || value === null) continue;
|
|
170
|
-
if (!/^[a-zA-Z_][a-zA-Z0-9_.]*$/.test(key)) continue;
|
|
171
|
-
if (this.exceedsDepth(value)) continue;
|
|
172
|
-
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
173
|
-
const operatorObj = value;
|
|
174
|
-
const operatorKeys = Object.keys(operatorObj);
|
|
175
|
-
if (operatorKeys.every((op) => this.operators[op]) && operatorKeys.length > 0) {
|
|
176
|
-
const mongoFilters = {};
|
|
177
|
-
for (const [op, opValue] of Object.entries(operatorObj)) {
|
|
178
|
-
const mongoOp = this.operators[op];
|
|
179
|
-
if (mongoOp) mongoFilters[mongoOp] = this.parseFilterValue(opValue, op);
|
|
180
|
-
}
|
|
181
|
-
filters[key] = mongoFilters;
|
|
182
|
-
continue;
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
const match = key.match(/^([a-zA-Z_][a-zA-Z0-9_.]*)(?:\[([a-z]+)\])?$/);
|
|
186
|
-
if (!match) continue;
|
|
187
|
-
const [, fieldName, operator] = match;
|
|
188
|
-
if (!fieldName) continue;
|
|
189
|
-
if (operator && this.operators[operator]) {
|
|
190
|
-
const mongoOp = this.operators[operator];
|
|
191
|
-
const parsedValue = this.parseFilterValue(value, operator);
|
|
192
|
-
if (!filters[fieldName]) filters[fieldName] = {};
|
|
193
|
-
filters[fieldName][mongoOp] = parsedValue;
|
|
194
|
-
} else if (!operator) filters[fieldName] = this.parseFilterValue(value);
|
|
195
|
-
}
|
|
196
|
-
return filters;
|
|
197
|
-
}
|
|
198
|
-
parseFilterValue(value, operator) {
|
|
199
|
-
if (operator === "in" || operator === "nin") {
|
|
200
|
-
if (Array.isArray(value)) return value.map((v) => this.coerceValue(v));
|
|
201
|
-
if (typeof value === "string" && value.includes(",")) return value.split(",").map((v) => this.coerceValue(v.trim()));
|
|
202
|
-
return [this.coerceValue(value)];
|
|
203
|
-
}
|
|
204
|
-
if (operator === "like" || operator === "contains" || operator === "regex") return this.sanitizeRegex(String(value));
|
|
205
|
-
if (operator === "exists") {
|
|
206
|
-
const str = String(value).toLowerCase();
|
|
207
|
-
return str === "true" || str === "1";
|
|
208
|
-
}
|
|
209
|
-
return this.coerceValue(value);
|
|
210
|
-
}
|
|
211
|
-
coerceValue(value) {
|
|
212
|
-
if (value === "true") return true;
|
|
213
|
-
if (value === "false") return false;
|
|
214
|
-
if (value === "null") return null;
|
|
215
|
-
if (typeof value === "string") {
|
|
216
|
-
const num = Number(value);
|
|
217
|
-
if (!Number.isNaN(num) && value.trim() !== "") return num;
|
|
218
|
-
}
|
|
219
|
-
return value;
|
|
220
|
-
}
|
|
221
|
-
/**
|
|
222
|
-
* Generate OpenAPI-compatible JSON Schema for query parameters.
|
|
223
|
-
* Arc's defineResource() auto-detects this method and uses it
|
|
224
|
-
* to document list endpoint query parameters in OpenAPI/Swagger.
|
|
225
|
-
*/
|
|
226
|
-
getQuerySchema() {
|
|
227
|
-
const operatorLines = Object.entries(this.operators).map(([op, mongoOp]) => {
|
|
228
|
-
return ` ${op} → ${mongoOp}: ${{
|
|
229
|
-
eq: "Equal (default when no operator specified)",
|
|
230
|
-
ne: "Not equal",
|
|
231
|
-
gt: "Greater than",
|
|
232
|
-
gte: "Greater than or equal",
|
|
233
|
-
lt: "Less than",
|
|
234
|
-
lte: "Less than or equal",
|
|
235
|
-
in: "In list (comma-separated values)",
|
|
236
|
-
nin: "Not in list",
|
|
237
|
-
like: "Pattern match (case-insensitive)",
|
|
238
|
-
contains: "Contains substring (case-insensitive)",
|
|
239
|
-
regex: "Regex pattern",
|
|
240
|
-
exists: "Field exists (true/false)"
|
|
241
|
-
}[op] || op}`;
|
|
242
|
-
});
|
|
243
|
-
return {
|
|
244
|
-
type: "object",
|
|
245
|
-
properties: {
|
|
246
|
-
page: {
|
|
247
|
-
type: "integer",
|
|
248
|
-
description: "Page number for offset pagination",
|
|
249
|
-
default: 1,
|
|
250
|
-
minimum: 1
|
|
251
|
-
},
|
|
252
|
-
limit: {
|
|
253
|
-
type: "integer",
|
|
254
|
-
description: "Number of items per page",
|
|
255
|
-
default: this.defaultLimit,
|
|
256
|
-
minimum: 1,
|
|
257
|
-
maximum: this.maxLimit
|
|
258
|
-
},
|
|
259
|
-
sort: {
|
|
260
|
-
type: "string",
|
|
261
|
-
description: "Sort fields (comma-separated). Prefix with - for descending. Example: -createdAt,name"
|
|
262
|
-
},
|
|
263
|
-
search: {
|
|
264
|
-
type: "string",
|
|
265
|
-
description: "Full-text search query",
|
|
266
|
-
maxLength: this.maxSearchLength
|
|
267
|
-
},
|
|
268
|
-
select: {
|
|
269
|
-
type: "string",
|
|
270
|
-
description: "Fields to include/exclude (comma-separated). Prefix with - to exclude. Example: name,email,-password"
|
|
271
|
-
},
|
|
272
|
-
populate: {
|
|
273
|
-
type: "string",
|
|
274
|
-
description: "Fields to populate/join (comma-separated). Example: author,category"
|
|
275
|
-
},
|
|
276
|
-
after: {
|
|
277
|
-
type: "string",
|
|
278
|
-
description: "Cursor value for keyset pagination"
|
|
279
|
-
},
|
|
280
|
-
_filterOperators: {
|
|
281
|
-
type: "string",
|
|
282
|
-
description: ["Available filter operators (use as field[operator]=value):", ...operatorLines].join("\n"),
|
|
283
|
-
"x-internal": true
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
};
|
|
287
|
-
}
|
|
288
|
-
sanitizeRegex(pattern) {
|
|
289
|
-
let sanitized = pattern.slice(0, this.maxRegexLength);
|
|
290
|
-
if (DANGEROUS_REGEX_PATTERNS.test(sanitized)) sanitized = sanitized.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
291
|
-
return sanitized;
|
|
292
|
-
}
|
|
293
|
-
};
|
|
294
|
-
/**
|
|
295
|
-
* Create a new ArcQueryParser instance
|
|
296
|
-
*/
|
|
297
|
-
function createQueryParser(options) {
|
|
298
|
-
return new ArcQueryParser(options);
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
//#endregion
|
|
302
|
-
//#region src/utils/responseSchemas.ts
|
|
303
|
-
/**
|
|
304
|
-
* Base success response schema
|
|
305
|
-
*/
|
|
306
|
-
const successResponseSchema = {
|
|
307
|
-
type: "object",
|
|
308
|
-
properties: { success: {
|
|
309
|
-
type: "boolean",
|
|
310
|
-
example: true
|
|
311
|
-
} },
|
|
312
|
-
required: ["success"]
|
|
313
|
-
};
|
|
314
|
-
/**
|
|
315
|
-
* Error response schema
|
|
316
|
-
*/
|
|
317
|
-
const errorResponseSchema = {
|
|
318
|
-
type: "object",
|
|
319
|
-
properties: {
|
|
320
|
-
success: {
|
|
321
|
-
type: "boolean",
|
|
322
|
-
example: false
|
|
323
|
-
},
|
|
324
|
-
error: {
|
|
325
|
-
type: "string",
|
|
326
|
-
description: "Error message"
|
|
327
|
-
},
|
|
328
|
-
code: {
|
|
329
|
-
type: "string",
|
|
330
|
-
description: "Error code"
|
|
331
|
-
},
|
|
332
|
-
message: {
|
|
333
|
-
type: "string",
|
|
334
|
-
description: "Detailed message"
|
|
335
|
-
}
|
|
336
|
-
},
|
|
337
|
-
required: ["success", "error"]
|
|
338
|
-
};
|
|
339
|
-
/**
|
|
340
|
-
* Pagination schema - matches MongoKit/Arc runtime format
|
|
341
|
-
*
|
|
342
|
-
* Runtime format (flat fields):
|
|
343
|
-
* { page, limit, total, pages, hasNext, hasPrev }
|
|
344
|
-
*/
|
|
345
|
-
const paginationSchema = {
|
|
346
|
-
type: "object",
|
|
347
|
-
properties: {
|
|
348
|
-
page: {
|
|
349
|
-
type: "integer",
|
|
350
|
-
example: 1
|
|
351
|
-
},
|
|
352
|
-
limit: {
|
|
353
|
-
type: "integer",
|
|
354
|
-
example: 20
|
|
355
|
-
},
|
|
356
|
-
total: {
|
|
357
|
-
type: "integer",
|
|
358
|
-
example: 100
|
|
359
|
-
},
|
|
360
|
-
pages: {
|
|
361
|
-
type: "integer",
|
|
362
|
-
example: 5
|
|
363
|
-
},
|
|
364
|
-
hasNext: {
|
|
365
|
-
type: "boolean",
|
|
366
|
-
example: true
|
|
367
|
-
},
|
|
368
|
-
hasPrev: {
|
|
369
|
-
type: "boolean",
|
|
370
|
-
example: false
|
|
371
|
-
}
|
|
372
|
-
},
|
|
373
|
-
required: [
|
|
374
|
-
"page",
|
|
375
|
-
"limit",
|
|
376
|
-
"total",
|
|
377
|
-
"pages",
|
|
378
|
-
"hasNext",
|
|
379
|
-
"hasPrev"
|
|
380
|
-
]
|
|
381
|
-
};
|
|
382
|
-
/**
|
|
383
|
-
* Wrap a data schema in a success response
|
|
384
|
-
*/
|
|
385
|
-
function wrapResponse(dataSchema) {
|
|
386
|
-
return {
|
|
387
|
-
type: "object",
|
|
388
|
-
properties: {
|
|
389
|
-
success: {
|
|
390
|
-
type: "boolean",
|
|
391
|
-
example: true
|
|
392
|
-
},
|
|
393
|
-
data: dataSchema
|
|
394
|
-
},
|
|
395
|
-
required: ["success", "data"],
|
|
396
|
-
additionalProperties: true
|
|
397
|
-
};
|
|
398
|
-
}
|
|
399
|
-
/**
|
|
400
|
-
* Create a list response schema with pagination - matches MongoKit/Arc runtime format
|
|
401
|
-
*
|
|
402
|
-
* Runtime format:
|
|
403
|
-
* { success, docs: [...], page, limit, total, pages, hasNext, hasPrev }
|
|
404
|
-
*
|
|
405
|
-
* Note: Uses 'docs' array (not 'data') with flat pagination fields
|
|
406
|
-
*/
|
|
407
|
-
function listResponse(itemSchema) {
|
|
408
|
-
return {
|
|
409
|
-
type: "object",
|
|
410
|
-
properties: {
|
|
411
|
-
success: {
|
|
412
|
-
type: "boolean",
|
|
413
|
-
example: true
|
|
414
|
-
},
|
|
415
|
-
docs: {
|
|
416
|
-
type: "array",
|
|
417
|
-
items: itemSchema
|
|
418
|
-
},
|
|
419
|
-
page: {
|
|
420
|
-
type: "integer",
|
|
421
|
-
example: 1
|
|
422
|
-
},
|
|
423
|
-
limit: {
|
|
424
|
-
type: "integer",
|
|
425
|
-
example: 20
|
|
426
|
-
},
|
|
427
|
-
total: {
|
|
428
|
-
type: "integer",
|
|
429
|
-
example: 100
|
|
430
|
-
},
|
|
431
|
-
pages: {
|
|
432
|
-
type: "integer",
|
|
433
|
-
example: 5
|
|
434
|
-
},
|
|
435
|
-
hasNext: {
|
|
436
|
-
type: "boolean",
|
|
437
|
-
example: false
|
|
438
|
-
},
|
|
439
|
-
hasPrev: {
|
|
440
|
-
type: "boolean",
|
|
441
|
-
example: false
|
|
442
|
-
}
|
|
443
|
-
},
|
|
444
|
-
required: ["success", "docs"],
|
|
445
|
-
additionalProperties: true
|
|
446
|
-
};
|
|
447
|
-
}
|
|
448
|
-
/**
|
|
449
|
-
* Alias for listResponse - matches local responseSchemas.js naming
|
|
450
|
-
*/
|
|
451
|
-
const paginateWrapper = listResponse;
|
|
452
|
-
/**
|
|
453
|
-
* Create a single item response schema
|
|
454
|
-
*
|
|
455
|
-
* Runtime format: { success, data: {...} }
|
|
456
|
-
*/
|
|
457
|
-
function itemResponse(itemSchema) {
|
|
458
|
-
return wrapResponse(itemSchema);
|
|
459
|
-
}
|
|
460
|
-
/**
|
|
461
|
-
* Alias for itemResponse - matches local responseSchemas.js naming
|
|
462
|
-
*/
|
|
463
|
-
const itemWrapper = itemResponse;
|
|
464
|
-
/**
|
|
465
|
-
* Create a create/update response schema
|
|
466
|
-
*/
|
|
467
|
-
function mutationResponse(itemSchema) {
|
|
468
|
-
return {
|
|
469
|
-
type: "object",
|
|
470
|
-
properties: {
|
|
471
|
-
success: {
|
|
472
|
-
type: "boolean",
|
|
473
|
-
example: true
|
|
474
|
-
},
|
|
475
|
-
data: itemSchema,
|
|
476
|
-
message: {
|
|
477
|
-
type: "string",
|
|
478
|
-
example: "Created successfully"
|
|
479
|
-
}
|
|
480
|
-
},
|
|
481
|
-
required: ["success", "data"],
|
|
482
|
-
additionalProperties: true
|
|
483
|
-
};
|
|
484
|
-
}
|
|
485
|
-
/**
|
|
486
|
-
* Create a delete response schema
|
|
487
|
-
*
|
|
488
|
-
* Runtime format: { success, message }
|
|
489
|
-
*/
|
|
490
|
-
function deleteResponse() {
|
|
491
|
-
return {
|
|
492
|
-
type: "object",
|
|
493
|
-
properties: {
|
|
494
|
-
success: {
|
|
495
|
-
type: "boolean",
|
|
496
|
-
example: true
|
|
497
|
-
},
|
|
498
|
-
message: {
|
|
499
|
-
type: "string",
|
|
500
|
-
example: "Deleted successfully"
|
|
501
|
-
}
|
|
502
|
-
},
|
|
503
|
-
required: ["success"],
|
|
504
|
-
additionalProperties: true
|
|
505
|
-
};
|
|
506
|
-
}
|
|
507
|
-
/**
|
|
508
|
-
* Alias for deleteResponse - matches local responseSchemas.js naming
|
|
509
|
-
*/
|
|
510
|
-
const messageWrapper = deleteResponse;
|
|
511
|
-
const responses = {
|
|
512
|
-
200: (schema) => ({
|
|
513
|
-
description: "Successful response",
|
|
514
|
-
content: { "application/json": { schema } }
|
|
515
|
-
}),
|
|
516
|
-
201: (schema) => ({
|
|
517
|
-
description: "Created successfully",
|
|
518
|
-
content: { "application/json": { schema: mutationResponse(schema) } }
|
|
519
|
-
}),
|
|
520
|
-
400: {
|
|
521
|
-
description: "Bad Request",
|
|
522
|
-
content: { "application/json": { schema: {
|
|
523
|
-
...errorResponseSchema,
|
|
524
|
-
properties: {
|
|
525
|
-
...errorResponseSchema.properties,
|
|
526
|
-
code: {
|
|
527
|
-
type: "string",
|
|
528
|
-
example: "VALIDATION_ERROR"
|
|
529
|
-
},
|
|
530
|
-
details: {
|
|
531
|
-
type: "object",
|
|
532
|
-
properties: { errors: {
|
|
533
|
-
type: "array",
|
|
534
|
-
items: {
|
|
535
|
-
type: "object",
|
|
536
|
-
properties: {
|
|
537
|
-
field: { type: "string" },
|
|
538
|
-
message: { type: "string" }
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
} }
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
} } }
|
|
545
|
-
},
|
|
546
|
-
401: {
|
|
547
|
-
description: "Unauthorized",
|
|
548
|
-
content: { "application/json": { schema: {
|
|
549
|
-
...errorResponseSchema,
|
|
550
|
-
properties: {
|
|
551
|
-
...errorResponseSchema.properties,
|
|
552
|
-
code: {
|
|
553
|
-
type: "string",
|
|
554
|
-
example: "UNAUTHORIZED"
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
} } }
|
|
558
|
-
},
|
|
559
|
-
403: {
|
|
560
|
-
description: "Forbidden",
|
|
561
|
-
content: { "application/json": { schema: {
|
|
562
|
-
...errorResponseSchema,
|
|
563
|
-
properties: {
|
|
564
|
-
...errorResponseSchema.properties,
|
|
565
|
-
code: {
|
|
566
|
-
type: "string",
|
|
567
|
-
example: "FORBIDDEN"
|
|
568
|
-
}
|
|
569
|
-
}
|
|
570
|
-
} } }
|
|
571
|
-
},
|
|
572
|
-
404: {
|
|
573
|
-
description: "Not Found",
|
|
574
|
-
content: { "application/json": { schema: {
|
|
575
|
-
...errorResponseSchema,
|
|
576
|
-
properties: {
|
|
577
|
-
...errorResponseSchema.properties,
|
|
578
|
-
code: {
|
|
579
|
-
type: "string",
|
|
580
|
-
example: "NOT_FOUND"
|
|
581
|
-
}
|
|
582
|
-
}
|
|
583
|
-
} } }
|
|
584
|
-
},
|
|
585
|
-
409: {
|
|
586
|
-
description: "Conflict",
|
|
587
|
-
content: { "application/json": { schema: {
|
|
588
|
-
...errorResponseSchema,
|
|
589
|
-
properties: {
|
|
590
|
-
...errorResponseSchema.properties,
|
|
591
|
-
code: {
|
|
592
|
-
type: "string",
|
|
593
|
-
example: "CONFLICT"
|
|
594
|
-
}
|
|
595
|
-
}
|
|
596
|
-
} } }
|
|
597
|
-
},
|
|
598
|
-
500: {
|
|
599
|
-
description: "Internal Server Error",
|
|
600
|
-
content: { "application/json": { schema: {
|
|
601
|
-
...errorResponseSchema,
|
|
602
|
-
properties: {
|
|
603
|
-
...errorResponseSchema.properties,
|
|
604
|
-
code: {
|
|
605
|
-
type: "string",
|
|
606
|
-
example: "INTERNAL_ERROR"
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
} } }
|
|
610
|
-
}
|
|
611
|
-
};
|
|
612
|
-
const queryParams = {
|
|
613
|
-
pagination: {
|
|
614
|
-
page: {
|
|
615
|
-
type: "integer",
|
|
616
|
-
minimum: 1,
|
|
617
|
-
default: 1,
|
|
618
|
-
description: "Page number"
|
|
619
|
-
},
|
|
620
|
-
limit: {
|
|
621
|
-
type: "integer",
|
|
622
|
-
minimum: 1,
|
|
623
|
-
maximum: 100,
|
|
624
|
-
default: 20,
|
|
625
|
-
description: "Items per page"
|
|
626
|
-
}
|
|
627
|
-
},
|
|
628
|
-
sorting: { sort: {
|
|
629
|
-
type: "string",
|
|
630
|
-
description: "Sort field (prefix with - for descending)",
|
|
631
|
-
example: "-createdAt"
|
|
632
|
-
} },
|
|
633
|
-
filtering: {
|
|
634
|
-
select: {
|
|
635
|
-
description: "Fields to include (space-separated or object)",
|
|
636
|
-
example: "name email createdAt"
|
|
637
|
-
},
|
|
638
|
-
populate: {
|
|
639
|
-
description: "Relations to populate (comma-separated string or bracket-notation object)",
|
|
640
|
-
example: "author,category"
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
};
|
|
644
|
-
/**
|
|
645
|
-
* Get standard list query parameters schema
|
|
646
|
-
*/
|
|
647
|
-
function getListQueryParams() {
|
|
648
|
-
return {
|
|
649
|
-
type: "object",
|
|
650
|
-
properties: {
|
|
651
|
-
...queryParams.pagination,
|
|
652
|
-
...queryParams.sorting,
|
|
653
|
-
...queryParams.filtering
|
|
654
|
-
},
|
|
655
|
-
additionalProperties: true
|
|
656
|
-
};
|
|
657
|
-
}
|
|
658
|
-
/**
|
|
659
|
-
* Generic item schema that allows any properties.
|
|
660
|
-
* Used as default when no user schema is provided.
|
|
661
|
-
* Enables fast-json-stringify while still passing through all fields.
|
|
662
|
-
*/
|
|
663
|
-
const genericItemSchema = {
|
|
664
|
-
type: "object",
|
|
665
|
-
additionalProperties: true
|
|
666
|
-
};
|
|
667
|
-
/**
|
|
668
|
-
* Recursively strip `example` keys from a schema object.
|
|
669
|
-
* The `example` keyword is OpenAPI metadata — not standard JSON Schema —
|
|
670
|
-
* and triggers Ajv strict mode errors when used on routes without the
|
|
671
|
-
* `keywords: ['example']` AJV config (e.g., raw Fastify without createApp).
|
|
672
|
-
*/
|
|
673
|
-
function stripExamples(schema) {
|
|
674
|
-
if (schema === null || typeof schema !== "object") return schema;
|
|
675
|
-
if (Array.isArray(schema)) return schema.map(stripExamples);
|
|
676
|
-
const result = {};
|
|
677
|
-
for (const [key, value] of Object.entries(schema)) {
|
|
678
|
-
if (key === "example") continue;
|
|
679
|
-
result[key] = stripExamples(value);
|
|
680
|
-
}
|
|
681
|
-
return result;
|
|
682
|
-
}
|
|
683
|
-
/**
|
|
684
|
-
* Get default response schemas for all CRUD operations.
|
|
685
|
-
*
|
|
686
|
-
* When routes have response schemas, Fastify compiles them with
|
|
687
|
-
* fast-json-stringify for 2-3x faster serialization and prevents
|
|
688
|
-
* accidental field disclosure.
|
|
689
|
-
*
|
|
690
|
-
* These defaults use `additionalProperties: true` so all fields pass through.
|
|
691
|
-
* Override with specific schemas for full serialization performance + safety.
|
|
692
|
-
*
|
|
693
|
-
* Note: `example` properties are stripped from defaults so they work with
|
|
694
|
-
* any Fastify instance (not just createApp which adds `keywords: ['example']`).
|
|
695
|
-
*/
|
|
696
|
-
function getDefaultCrudSchemas() {
|
|
697
|
-
return stripExamples({
|
|
698
|
-
list: {
|
|
699
|
-
querystring: getListQueryParams(),
|
|
700
|
-
response: { 200: listResponse(genericItemSchema) }
|
|
701
|
-
},
|
|
702
|
-
get: { response: { 200: itemResponse(genericItemSchema) } },
|
|
703
|
-
create: { response: { 201: mutationResponse(genericItemSchema) } },
|
|
704
|
-
update: { response: { 200: itemResponse(genericItemSchema) } },
|
|
705
|
-
delete: { response: { 200: deleteResponse() } }
|
|
706
|
-
});
|
|
707
|
-
}
|
|
708
|
-
|
|
709
|
-
//#endregion
|
|
710
|
-
//#region src/utils/stateMachine.ts
|
|
711
|
-
/**
|
|
712
|
-
* Create a state machine for validating transitions
|
|
713
|
-
*
|
|
714
|
-
* @param name - Name of the state machine (used in error messages)
|
|
715
|
-
* @param transitions - Map of actions to allowed source statuses
|
|
716
|
-
* @param options - Additional options (history, guards, actions)
|
|
717
|
-
* @returns State machine with can() and assert() methods
|
|
718
|
-
*
|
|
719
|
-
* @example
|
|
720
|
-
* // Basic usage
|
|
721
|
-
* const transferState = createStateMachine('Transfer', {
|
|
722
|
-
* approve: ['draft'],
|
|
723
|
-
* dispatch: ['approved'],
|
|
724
|
-
* receive: ['dispatched', 'in_transit'],
|
|
725
|
-
* cancel: ['draft', 'approved'],
|
|
726
|
-
* });
|
|
727
|
-
*
|
|
728
|
-
* @example
|
|
729
|
-
* // With guards and actions
|
|
730
|
-
* const orderState = createStateMachine('Order', {
|
|
731
|
-
* approve: {
|
|
732
|
-
* from: ['pending'],
|
|
733
|
-
* to: 'approved',
|
|
734
|
-
* guard: ({ data }) => data.paymentConfirmed,
|
|
735
|
-
* before: ({ from, to }) => console.log(`Approving order from ${from} to ${to}`),
|
|
736
|
-
* after: ({ data }) => sendApprovalEmail(data.customerId),
|
|
737
|
-
* },
|
|
738
|
-
* }, { trackHistory: true });
|
|
739
|
-
*/
|
|
740
|
-
function createStateMachine(name, transitions = {}, options = {}) {
|
|
741
|
-
const normalized = /* @__PURE__ */ new Map();
|
|
742
|
-
const history = options.trackHistory ? [] : void 0;
|
|
743
|
-
Object.entries(transitions).forEach(([action, allowed]) => {
|
|
744
|
-
if (Array.isArray(allowed)) normalized.set(action, { from: new Set(allowed) });
|
|
745
|
-
else if (typeof allowed === "object" && "from" in allowed) normalized.set(action, {
|
|
746
|
-
from: new Set(Array.isArray(allowed.from) ? allowed.from : [allowed.from]),
|
|
747
|
-
to: allowed.to,
|
|
748
|
-
guard: allowed.guard,
|
|
749
|
-
before: allowed.before,
|
|
750
|
-
after: allowed.after
|
|
751
|
-
});
|
|
752
|
-
});
|
|
753
|
-
const can = (action, status) => {
|
|
754
|
-
const transition = normalized.get(action);
|
|
755
|
-
if (!transition || !status) return false;
|
|
756
|
-
return transition.from.has(status);
|
|
757
|
-
};
|
|
758
|
-
const canAsync = async (action, status, context) => {
|
|
759
|
-
const transition = normalized.get(action);
|
|
760
|
-
if (!transition || !status) return false;
|
|
761
|
-
if (!transition.from.has(status)) return false;
|
|
762
|
-
if (transition.guard) try {
|
|
763
|
-
return await transition.guard({
|
|
764
|
-
from: status,
|
|
765
|
-
to: transition.to || "",
|
|
766
|
-
action,
|
|
767
|
-
data: context
|
|
768
|
-
});
|
|
769
|
-
} catch {
|
|
770
|
-
return false;
|
|
771
|
-
}
|
|
772
|
-
return true;
|
|
773
|
-
};
|
|
774
|
-
const assert = (action, status, errorFactory, message) => {
|
|
775
|
-
if (can(action, status)) return;
|
|
776
|
-
const errorMessage = message || `${name} cannot '${action}' when status is '${status || "unknown"}'`;
|
|
777
|
-
if (typeof errorFactory === "function") throw errorFactory(errorMessage);
|
|
778
|
-
throw new Error(errorMessage);
|
|
779
|
-
};
|
|
780
|
-
const recordTransition = (from, to, action, metadata) => {
|
|
781
|
-
if (history) history.push({
|
|
782
|
-
from,
|
|
783
|
-
to,
|
|
784
|
-
action,
|
|
785
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
786
|
-
metadata
|
|
787
|
-
});
|
|
788
|
-
};
|
|
789
|
-
const getHistory = () => {
|
|
790
|
-
return history ? [...history] : [];
|
|
791
|
-
};
|
|
792
|
-
const clearHistory = () => {
|
|
793
|
-
if (history) history.length = 0;
|
|
794
|
-
};
|
|
795
|
-
const getAvailableActions = (status) => {
|
|
796
|
-
const actions = [];
|
|
797
|
-
for (const [action, transition] of normalized.entries()) if (transition.from.has(status)) actions.push(action);
|
|
798
|
-
return actions;
|
|
799
|
-
};
|
|
800
|
-
return {
|
|
801
|
-
can,
|
|
802
|
-
canAsync,
|
|
803
|
-
assert,
|
|
804
|
-
recordTransition,
|
|
805
|
-
getHistory,
|
|
806
|
-
clearHistory,
|
|
807
|
-
getAvailableActions
|
|
808
|
-
};
|
|
809
|
-
}
|
|
810
|
-
|
|
811
|
-
//#endregion
|
|
812
|
-
//#region src/utils/circuitBreaker.ts
|
|
813
|
-
/**
|
|
814
|
-
* Circuit Breaker Pattern
|
|
815
|
-
*
|
|
816
|
-
* Wraps external service calls with failure protection.
|
|
817
|
-
* Prevents cascading failures by "opening" the circuit when
|
|
818
|
-
* a service is failing, allowing it time to recover.
|
|
819
|
-
*
|
|
820
|
-
* States:
|
|
821
|
-
* - CLOSED: Normal operation, requests pass through
|
|
822
|
-
* - OPEN: Too many failures, all requests fail fast
|
|
823
|
-
* - HALF_OPEN: Testing if service recovered, limited requests
|
|
824
|
-
*
|
|
825
|
-
* @example
|
|
826
|
-
* import { CircuitBreaker } from '@classytic/arc/utils';
|
|
827
|
-
*
|
|
828
|
-
* const paymentBreaker = new CircuitBreaker(async (amount) => {
|
|
829
|
-
* return await stripe.charges.create({ amount });
|
|
830
|
-
* }, {
|
|
831
|
-
* failureThreshold: 5,
|
|
832
|
-
* resetTimeout: 30000,
|
|
833
|
-
* timeout: 5000,
|
|
834
|
-
* });
|
|
835
|
-
*
|
|
836
|
-
* try {
|
|
837
|
-
* const result = await paymentBreaker.call(100);
|
|
838
|
-
* } catch (error) {
|
|
839
|
-
* // Handle failure or circuit open
|
|
840
|
-
* }
|
|
841
|
-
*/
|
|
842
|
-
const CircuitState = {
|
|
843
|
-
CLOSED: "CLOSED",
|
|
844
|
-
OPEN: "OPEN",
|
|
845
|
-
HALF_OPEN: "HALF_OPEN"
|
|
846
|
-
};
|
|
847
|
-
var CircuitBreakerError = class extends Error {
|
|
848
|
-
state;
|
|
849
|
-
constructor(message, state) {
|
|
850
|
-
super(message);
|
|
851
|
-
this.name = "CircuitBreakerError";
|
|
852
|
-
this.state = state;
|
|
853
|
-
}
|
|
854
|
-
};
|
|
855
|
-
var CircuitBreaker = class {
|
|
856
|
-
state = CircuitState.CLOSED;
|
|
857
|
-
failures = 0;
|
|
858
|
-
successes = 0;
|
|
859
|
-
totalCalls = 0;
|
|
860
|
-
nextAttempt = 0;
|
|
861
|
-
lastCallAt = null;
|
|
862
|
-
openedAt = null;
|
|
863
|
-
failureThreshold;
|
|
864
|
-
resetTimeout;
|
|
865
|
-
timeout;
|
|
866
|
-
successThreshold;
|
|
867
|
-
fallback;
|
|
868
|
-
onStateChange;
|
|
869
|
-
onError;
|
|
870
|
-
name;
|
|
871
|
-
fn;
|
|
872
|
-
constructor(fn, options = {}) {
|
|
873
|
-
this.fn = fn;
|
|
874
|
-
this.failureThreshold = options.failureThreshold ?? 5;
|
|
875
|
-
this.resetTimeout = options.resetTimeout ?? 6e4;
|
|
876
|
-
this.timeout = options.timeout ?? 1e4;
|
|
877
|
-
this.successThreshold = options.successThreshold ?? 1;
|
|
878
|
-
this.fallback = options.fallback;
|
|
879
|
-
this.onStateChange = options.onStateChange;
|
|
880
|
-
this.onError = options.onError;
|
|
881
|
-
this.name = options.name ?? "CircuitBreaker";
|
|
882
|
-
}
|
|
883
|
-
/**
|
|
884
|
-
* Call the wrapped function with circuit breaker protection
|
|
885
|
-
*/
|
|
886
|
-
async call(...args) {
|
|
887
|
-
this.totalCalls++;
|
|
888
|
-
this.lastCallAt = Date.now();
|
|
889
|
-
if (this.state === CircuitState.OPEN) {
|
|
890
|
-
if (Date.now() < this.nextAttempt) {
|
|
891
|
-
const error = new CircuitBreakerError(`Circuit breaker is OPEN for ${this.name}`, CircuitState.OPEN);
|
|
892
|
-
if (this.fallback) return this.fallback(...args);
|
|
893
|
-
throw error;
|
|
894
|
-
}
|
|
895
|
-
this.setState(CircuitState.HALF_OPEN);
|
|
896
|
-
}
|
|
897
|
-
try {
|
|
898
|
-
const result = await this.executeWithTimeout(args);
|
|
899
|
-
this.onSuccess();
|
|
900
|
-
return result;
|
|
901
|
-
} catch (error) {
|
|
902
|
-
this.onFailure(error);
|
|
903
|
-
throw error;
|
|
904
|
-
}
|
|
905
|
-
}
|
|
906
|
-
/**
|
|
907
|
-
* Execute function with timeout
|
|
908
|
-
*/
|
|
909
|
-
async executeWithTimeout(args) {
|
|
910
|
-
return new Promise((resolve, reject) => {
|
|
911
|
-
const timeoutId = setTimeout(() => {
|
|
912
|
-
reject(/* @__PURE__ */ new Error(`Request timeout after ${this.timeout}ms`));
|
|
913
|
-
}, this.timeout);
|
|
914
|
-
this.fn(...args).then((result) => {
|
|
915
|
-
clearTimeout(timeoutId);
|
|
916
|
-
resolve(result);
|
|
917
|
-
}).catch((error) => {
|
|
918
|
-
clearTimeout(timeoutId);
|
|
919
|
-
reject(error);
|
|
920
|
-
});
|
|
921
|
-
});
|
|
922
|
-
}
|
|
923
|
-
/**
|
|
924
|
-
* Handle successful call
|
|
925
|
-
*/
|
|
926
|
-
onSuccess() {
|
|
927
|
-
this.failures = 0;
|
|
928
|
-
this.successes++;
|
|
929
|
-
if (this.state === CircuitState.HALF_OPEN) {
|
|
930
|
-
if (this.successes >= this.successThreshold) {
|
|
931
|
-
this.setState(CircuitState.CLOSED);
|
|
932
|
-
this.successes = 0;
|
|
933
|
-
}
|
|
934
|
-
}
|
|
935
|
-
}
|
|
936
|
-
/**
|
|
937
|
-
* Handle failed call
|
|
938
|
-
*/
|
|
939
|
-
onFailure(error) {
|
|
940
|
-
this.failures++;
|
|
941
|
-
this.successes = 0;
|
|
942
|
-
if (this.onError) this.onError(error);
|
|
943
|
-
if (this.state === CircuitState.HALF_OPEN || this.failures >= this.failureThreshold) {
|
|
944
|
-
this.setState(CircuitState.OPEN);
|
|
945
|
-
this.nextAttempt = Date.now() + this.resetTimeout;
|
|
946
|
-
this.openedAt = Date.now();
|
|
947
|
-
}
|
|
948
|
-
}
|
|
949
|
-
/**
|
|
950
|
-
* Change circuit state
|
|
951
|
-
*/
|
|
952
|
-
setState(newState) {
|
|
953
|
-
const oldState = this.state;
|
|
954
|
-
if (oldState !== newState) {
|
|
955
|
-
this.state = newState;
|
|
956
|
-
if (this.onStateChange) this.onStateChange(oldState, newState);
|
|
957
|
-
}
|
|
958
|
-
}
|
|
959
|
-
/**
|
|
960
|
-
* Manually open the circuit
|
|
961
|
-
*/
|
|
962
|
-
open() {
|
|
963
|
-
this.setState(CircuitState.OPEN);
|
|
964
|
-
this.nextAttempt = Date.now() + this.resetTimeout;
|
|
965
|
-
this.openedAt = Date.now();
|
|
966
|
-
}
|
|
967
|
-
/**
|
|
968
|
-
* Manually close the circuit
|
|
969
|
-
*/
|
|
970
|
-
close() {
|
|
971
|
-
this.failures = 0;
|
|
972
|
-
this.successes = 0;
|
|
973
|
-
this.setState(CircuitState.CLOSED);
|
|
974
|
-
this.openedAt = null;
|
|
975
|
-
}
|
|
976
|
-
/**
|
|
977
|
-
* Get current statistics
|
|
978
|
-
*/
|
|
979
|
-
getStats() {
|
|
980
|
-
return {
|
|
981
|
-
name: this.name,
|
|
982
|
-
state: this.state,
|
|
983
|
-
failures: this.failures,
|
|
984
|
-
successes: this.successes,
|
|
985
|
-
totalCalls: this.totalCalls,
|
|
986
|
-
openedAt: this.openedAt,
|
|
987
|
-
lastCallAt: this.lastCallAt
|
|
988
|
-
};
|
|
989
|
-
}
|
|
990
|
-
/**
|
|
991
|
-
* Get current state
|
|
992
|
-
*/
|
|
993
|
-
getState() {
|
|
994
|
-
return this.state;
|
|
995
|
-
}
|
|
996
|
-
/**
|
|
997
|
-
* Check if circuit is open
|
|
998
|
-
*/
|
|
999
|
-
isOpen() {
|
|
1000
|
-
return this.state === CircuitState.OPEN;
|
|
1001
|
-
}
|
|
1002
|
-
/**
|
|
1003
|
-
* Check if circuit is closed
|
|
1004
|
-
*/
|
|
1005
|
-
isClosed() {
|
|
1006
|
-
return this.state === CircuitState.CLOSED;
|
|
1007
|
-
}
|
|
1008
|
-
/**
|
|
1009
|
-
* Reset statistics
|
|
1010
|
-
*/
|
|
1011
|
-
reset() {
|
|
1012
|
-
this.failures = 0;
|
|
1013
|
-
this.successes = 0;
|
|
1014
|
-
this.totalCalls = 0;
|
|
1015
|
-
this.lastCallAt = null;
|
|
1016
|
-
this.openedAt = null;
|
|
1017
|
-
this.setState(CircuitState.CLOSED);
|
|
1018
|
-
}
|
|
1019
|
-
};
|
|
1020
|
-
/**
|
|
1021
|
-
* Create a circuit breaker with sensible defaults
|
|
1022
|
-
*
|
|
1023
|
-
* @example
|
|
1024
|
-
* const emailBreaker = createCircuitBreaker(
|
|
1025
|
-
* async (to, subject, body) => sendEmail(to, subject, body),
|
|
1026
|
-
* { name: 'email-service' }
|
|
1027
|
-
* );
|
|
1028
|
-
*/
|
|
1029
|
-
function createCircuitBreaker(fn, options) {
|
|
1030
|
-
return new CircuitBreaker(fn, options);
|
|
1031
|
-
}
|
|
1032
|
-
/**
|
|
1033
|
-
* Circuit breaker registry for managing multiple breakers
|
|
1034
|
-
*/
|
|
1035
|
-
var CircuitBreakerRegistry = class {
|
|
1036
|
-
breakers = /* @__PURE__ */ new Map();
|
|
1037
|
-
/**
|
|
1038
|
-
* Register a circuit breaker
|
|
1039
|
-
*/
|
|
1040
|
-
register(name, fn, options) {
|
|
1041
|
-
const breaker = new CircuitBreaker(fn, {
|
|
1042
|
-
...options,
|
|
1043
|
-
name
|
|
1044
|
-
});
|
|
1045
|
-
this.breakers.set(name, breaker);
|
|
1046
|
-
return breaker;
|
|
1047
|
-
}
|
|
1048
|
-
/**
|
|
1049
|
-
* Get a circuit breaker by name
|
|
1050
|
-
*/
|
|
1051
|
-
get(name) {
|
|
1052
|
-
return this.breakers.get(name);
|
|
1053
|
-
}
|
|
1054
|
-
/**
|
|
1055
|
-
* Get all breakers
|
|
1056
|
-
*/
|
|
1057
|
-
getAll() {
|
|
1058
|
-
return this.breakers;
|
|
1059
|
-
}
|
|
1060
|
-
/**
|
|
1061
|
-
* Get statistics for all breakers
|
|
1062
|
-
*/
|
|
1063
|
-
getAllStats() {
|
|
1064
|
-
const stats = {};
|
|
1065
|
-
for (const [name, breaker] of this.breakers.entries()) stats[name] = breaker.getStats();
|
|
1066
|
-
return stats;
|
|
1067
|
-
}
|
|
1068
|
-
/**
|
|
1069
|
-
* Reset all breakers
|
|
1070
|
-
*/
|
|
1071
|
-
resetAll() {
|
|
1072
|
-
for (const breaker of this.breakers.values()) breaker.reset();
|
|
1073
|
-
}
|
|
1074
|
-
/**
|
|
1075
|
-
* Open all breakers
|
|
1076
|
-
*/
|
|
1077
|
-
openAll() {
|
|
1078
|
-
for (const breaker of this.breakers.values()) breaker.open();
|
|
1079
|
-
}
|
|
1080
|
-
/**
|
|
1081
|
-
* Close all breakers
|
|
1082
|
-
*/
|
|
1083
|
-
closeAll() {
|
|
1084
|
-
for (const breaker of this.breakers.values()) breaker.close();
|
|
1085
|
-
}
|
|
1086
|
-
};
|
|
1087
|
-
/**
|
|
1088
|
-
* Create a new CircuitBreakerRegistry instance.
|
|
1089
|
-
* Use this instead of a global singleton — attach to fastify.arc or pass explicitly.
|
|
1090
|
-
*/
|
|
1091
|
-
function createCircuitBreakerRegistry() {
|
|
1092
|
-
return new CircuitBreakerRegistry();
|
|
1093
|
-
}
|
|
1094
|
-
|
|
1095
|
-
//#endregion
|
|
1096
|
-
export { ArcQueryParser as C, wrapResponse as S, paginateWrapper as _, createCircuitBreaker as a, responses as b, deleteResponse as c, getListQueryParams as d, itemResponse as f, mutationResponse as g, messageWrapper as h, CircuitState as i, errorResponseSchema as l, listResponse as m, CircuitBreakerError as n, createCircuitBreakerRegistry as o, itemWrapper as p, CircuitBreakerRegistry as r, createStateMachine as s, CircuitBreaker as t, getDefaultCrudSchemas as u, paginationSchema as v, createQueryParser as w, successResponseSchema as x, queryParams as y };
|