@classytic/arc 2.25.0 → 2.30.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/README.md +2 -0
- package/dist/{BaseController--M8EMzt0.mjs → BaseController-B5DwufbB.mjs} +15 -11
- package/dist/EventTransport-C6YA8xY9.mjs +103 -0
- package/dist/{HookSystem-C1vB_Gc9.mjs → HookSystem-WkIougo6.mjs} +15 -35
- package/dist/applyPermissionResult-Cf6zUCvb.mjs +257 -0
- package/dist/audit/index.d.mts +2 -2
- package/dist/audit/index.mjs +1 -1
- package/dist/auth/index.d.mts +2 -2
- package/dist/auth/index.mjs +1 -1
- package/dist/{buildHandler-Dtwd8fdz.mjs → buildHandler-BYS3Vkfz.mjs} +32 -6
- package/dist/cleanup/index.d.mts +313 -0
- package/dist/cleanup/index.mjs +1267 -0
- package/dist/cli/commands/describe.d.mts +1 -1
- package/dist/cli/commands/docs.mjs +1 -1
- package/dist/core/index.d.mts +2 -2
- package/dist/core/index.mjs +5 -3
- package/dist/core-poalJLvp.mjs +175 -0
- package/dist/{createActionRouter-B6GvAuAX.mjs → createActionRouter-BxuywVRB.mjs} +2 -2
- package/dist/{createAggregationRouter-wzwFa_dW.mjs → createAggregationRouter-BiY-lGdY.mjs} +7 -20
- package/dist/{preloadResources-DfyngIN9.mjs → createApp-CXrKFciH.mjs} +25 -76
- package/dist/defineAggregation-ufWjUwml.mjs +47 -0
- package/dist/{core-EUNu0u07.mjs → defineResource-CxWqDCAy.mjs} +36 -261
- package/dist/docs/index.d.mts +1 -1
- package/dist/docs/index.mjs +1 -1
- package/dist/{eventPlugin-DrQ_FesK.mjs → eventPlugin-D2NNR4py.mjs} +2 -103
- package/dist/events/index.d.mts +28 -2
- package/dist/events/index.mjs +24 -343
- package/dist/factory/index.d.mts +4 -3
- package/dist/factory/index.mjs +3 -1
- package/dist/{fastify-augmentation-dPNBVeIj.d.mts → fastify-augmentation-0WhPnUH7.d.mts} +3 -2
- package/dist/{applyPermissionResult-Tw4iXtlf.mjs → fields-CQ_7KQWw.mjs} +1 -97
- package/dist/hooks/index.d.mts +1 -1
- package/dist/hooks/index.mjs +1 -1
- package/dist/idempotency/index.mjs +1 -1
- package/dist/index-CCzVR-N3.d.mts +107 -0
- package/dist/{index-BMnbzvtO.d.mts → index-Ch16aAah.d.mts} +201 -21
- package/dist/{index-f4PTrk3B.d.mts → index-Cx7bro4R.d.mts} +4 -4
- package/dist/{index-DPRH0Cme.d.mts → index-Q5gzEIWY.d.mts} +97 -66
- package/dist/index.d.mts +6 -6
- package/dist/index.mjs +8 -6
- package/dist/integrations/index.d.mts +1 -1
- package/dist/integrations/mcp/index.d.mts +6 -6
- package/dist/integrations/mcp/index.mjs +1 -1
- package/dist/integrations/mcp/testing.d.mts +1 -1
- package/dist/integrations/mcp/testing.mjs +1 -1
- package/dist/{mcpPlugin-Cb7olw0j.mjs → mcpPlugin-nRzm5g2s.mjs} +36 -43
- package/dist/middleware/index.d.mts +1 -1
- package/dist/migrations/index.d.mts +0 -3
- package/dist/migrations/index.mjs +0 -3
- package/dist/module-_-M7C5ES.mjs +29 -0
- package/dist/{openapi-DrLtog_B.mjs → openapi-B8Vkbxbn.mjs} +1 -1
- package/dist/permissions/index.d.mts +3 -3
- package/dist/permissions/index.mjs +4 -3
- package/dist/{permissions-BrtiBKGs.mjs → permissions-Bfu_8y1U.mjs} +318 -289
- package/dist/pipeline/index.d.mts +1 -1
- package/dist/{pipeline-BN5G05rd.mjs → pipeline-BJnpkY9i.mjs} +4 -18
- package/dist/plugins/index.d.mts +4 -4
- package/dist/plugins/index.mjs +2 -2
- package/dist/plugins/tracing-entry.mjs +1 -1
- package/dist/{preloadResources-0oe-JSSS.d.mts → preloadResources-DCfa2egz.d.mts} +3 -2
- package/dist/preloadResources-DSY5HGpS.mjs +45 -0
- package/dist/presets/filesUpload.d.mts +2 -2
- package/dist/presets/filesUpload.mjs +1 -1
- package/dist/presets/index.d.mts +14 -2
- package/dist/presets/index.mjs +1 -1
- package/dist/presets/multiTenant.d.mts +1 -1
- package/dist/presets/search.d.mts +2 -2
- package/dist/presets/search.mjs +1 -1
- package/dist/{presets-DwFDVKP0.mjs → presets-CJOEXLuk.mjs} +25 -9
- package/dist/projection-UBDgfMwu.mjs +17 -0
- package/dist/{realtime-Cuw_deA-.mjs → realtime-B9nmIY5V.mjs} +2 -1
- package/dist/{registerRoute-v0Wb6Plt.mjs → registerRoute-JkxIEBJq.mjs} +3 -1
- package/dist/registry/index.d.mts +2 -2
- package/dist/registry/index.mjs +1 -1
- package/dist/{registry-vcOCtPij.mjs → registry-BYXUUg21.mjs} +16 -1
- package/dist/repositoryFilter-Dz8k3S4P.mjs +44 -0
- package/dist/subscribe-helpers-DfzsivM6.mjs +339 -0
- package/dist/testing/cleanupStoreContract.d.mts +10 -0
- package/dist/testing/cleanupStoreContract.mjs +375 -0
- package/dist/testing/index.d.mts +34 -5
- package/dist/testing/index.mjs +316 -211
- package/dist/testing/outboxStoreContract.d.mts +13 -0
- package/dist/testing/outboxStoreContract.mjs +247 -0
- package/dist/types/index.d.mts +3 -3
- package/dist/{types-QFGc3Cjv.d.mts → types-Bmmn-fO0.d.mts} +1 -1
- package/dist/types-C_ZZRcD6.d.mts +450 -0
- package/dist/{types-Dmw-6Qeo.d.mts → types-ChvvVNP8.d.mts} +93 -88
- package/dist/{index-KUoxjIq1.d.mts → types-D_n8L6VY.d.mts} +33 -106
- package/dist/usage/index.d.mts +1 -1
- package/dist/usage/index.mjs +0 -0
- package/dist/utils/index.d.mts +2 -5
- package/package.json +539 -524
package/dist/events/index.mjs
CHANGED
|
@@ -1,192 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t as MemoryEventTransport } from "../EventTransport-C6YA8xY9.mjs";
|
|
2
|
+
import { a as createEventRegistry, i as wrapWithSchema, n as subscribeWithSchema, o as defineEvent, r as wrapWithBoundary, t as subscribeWithBoundary } from "../subscribe-helpers-DfzsivM6.mjs";
|
|
3
|
+
import { i as withRetry, r as createDeadLetterPublisher, t as eventPlugin } from "../eventPlugin-D2NNR4py.mjs";
|
|
2
4
|
import { n as createSafeGetOne, t as createIsDuplicateKeyError } from "../store-helpers-DY6xq4sM.mjs";
|
|
3
|
-
import { InvalidOutboxEventError, OutboxOwnershipError } from "@classytic/primitives/outbox";
|
|
4
5
|
import { and, anyOf, eq, lte, ne, or } from "@classytic/repo-core/filter";
|
|
6
|
+
import { InvalidOutboxEventError, OutboxOwnershipError } from "@classytic/primitives/outbox";
|
|
5
7
|
import { update } from "@classytic/repo-core/update";
|
|
6
|
-
//#region src/events/defineEvent.ts
|
|
7
|
-
/**
|
|
8
|
-
* defineEvent — Typed Event Definitions with Optional Schema Validation
|
|
9
|
-
*
|
|
10
|
-
* Provides:
|
|
11
|
-
* 1. defineEvent() — declare an event with name, schema, version, description
|
|
12
|
-
* 2. EventRegistry — catalog of all known events + payload validation
|
|
13
|
-
* 3. .create() helper — build DomainEvent with auto-generated metadata
|
|
14
|
-
*
|
|
15
|
-
* The built-in validator checks: object type, required fields, and top-level
|
|
16
|
-
* property types. It does NOT recurse into nested objects, validate arrays,
|
|
17
|
-
* enums, patterns, formats, or $ref. This is intentional — it's a lightweight
|
|
18
|
-
* guard, not a full JSON Schema engine.
|
|
19
|
-
*
|
|
20
|
-
* For full validation, pass a custom `validate` function to `createEventRegistry()`:
|
|
21
|
-
*
|
|
22
|
-
* @example
|
|
23
|
-
* ```typescript
|
|
24
|
-
* import Ajv from 'ajv';
|
|
25
|
-
* const ajv = new Ajv();
|
|
26
|
-
*
|
|
27
|
-
* const registry = createEventRegistry({
|
|
28
|
-
* validate: (schema, payload) => {
|
|
29
|
-
* const valid = ajv.validate(schema, payload);
|
|
30
|
-
* return valid
|
|
31
|
-
* ? { valid: true }
|
|
32
|
-
* : { valid: false, errors: ajv.errorsText().split(', ') };
|
|
33
|
-
* },
|
|
34
|
-
* });
|
|
35
|
-
* ```
|
|
36
|
-
*
|
|
37
|
-
* @example
|
|
38
|
-
* ```typescript
|
|
39
|
-
* import { defineEvent, createEventRegistry } from '@classytic/arc/events';
|
|
40
|
-
*
|
|
41
|
-
* const OrderCreated = defineEvent({
|
|
42
|
-
* name: 'order.created',
|
|
43
|
-
* version: 1,
|
|
44
|
-
* schema: {
|
|
45
|
-
* type: 'object',
|
|
46
|
-
* properties: {
|
|
47
|
-
* orderId: { type: 'string' },
|
|
48
|
-
* total: { type: 'number' },
|
|
49
|
-
* },
|
|
50
|
-
* required: ['orderId', 'total'],
|
|
51
|
-
* },
|
|
52
|
-
* });
|
|
53
|
-
*
|
|
54
|
-
* // Type-safe event creation
|
|
55
|
-
* const event = OrderCreated.create({ orderId: 'o-1', total: 100 });
|
|
56
|
-
* await fastify.events.publish(event.type, event.payload, event.meta);
|
|
57
|
-
*
|
|
58
|
-
* // Registry for introspection + validation
|
|
59
|
-
* const registry = createEventRegistry();
|
|
60
|
-
* registry.register(OrderCreated);
|
|
61
|
-
* const result = registry.validate('order.created', payload);
|
|
62
|
-
* ```
|
|
63
|
-
*/
|
|
64
|
-
/**
|
|
65
|
-
* Define a typed event with optional schema validation.
|
|
66
|
-
*
|
|
67
|
-
* @example
|
|
68
|
-
* const OrderCreated = defineEvent({
|
|
69
|
-
* name: 'order.created',
|
|
70
|
-
* schema: { type: 'object', properties: { orderId: { type: 'string' } }, required: ['orderId'] },
|
|
71
|
-
* });
|
|
72
|
-
*
|
|
73
|
-
* const event = OrderCreated.create({ orderId: '123' });
|
|
74
|
-
*/
|
|
75
|
-
function defineEvent(input) {
|
|
76
|
-
const { name, schema, version = 1, description } = input;
|
|
77
|
-
return {
|
|
78
|
-
name,
|
|
79
|
-
schema,
|
|
80
|
-
version,
|
|
81
|
-
description,
|
|
82
|
-
create(payload, meta) {
|
|
83
|
-
return createEvent(name, payload, {
|
|
84
|
-
schemaVersion: version,
|
|
85
|
-
...meta
|
|
86
|
-
});
|
|
87
|
-
}
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
/**
|
|
91
|
-
* Create an event registry for cataloging and validating events.
|
|
92
|
-
*
|
|
93
|
-
* The registry is opt-in — unregistered events pass validation.
|
|
94
|
-
* This allows gradual adoption without breaking existing code.
|
|
95
|
-
*
|
|
96
|
-
* @param options.validate - Custom validator replacing the built-in minimal validator.
|
|
97
|
-
* The built-in validator only checks top-level object structure (type, required, property types).
|
|
98
|
-
* For nested objects, arrays, enums, patterns, or $ref, provide AJV or similar.
|
|
99
|
-
*/
|
|
100
|
-
function createEventRegistry(options) {
|
|
101
|
-
const customValidator = options?.validate;
|
|
102
|
-
const definitions = /* @__PURE__ */ new Map();
|
|
103
|
-
function registryKey(name, version) {
|
|
104
|
-
return `${name}:v${version}`;
|
|
105
|
-
}
|
|
106
|
-
return {
|
|
107
|
-
register(definition) {
|
|
108
|
-
const key = registryKey(definition.name, definition.version);
|
|
109
|
-
if (definitions.has(key)) throw new Error(`Event '${definition.name}' v${definition.version} is already registered. Use a different version number for schema evolution.`);
|
|
110
|
-
definitions.set(key, definition);
|
|
111
|
-
},
|
|
112
|
-
get(name, version) {
|
|
113
|
-
if (version !== void 0) return definitions.get(registryKey(name, version));
|
|
114
|
-
let latest;
|
|
115
|
-
let latestVersion = -1;
|
|
116
|
-
for (const def of definitions.values()) if (def.name === name && def.version > latestVersion) {
|
|
117
|
-
latest = def;
|
|
118
|
-
latestVersion = def.version;
|
|
119
|
-
}
|
|
120
|
-
return latest;
|
|
121
|
-
},
|
|
122
|
-
catalog() {
|
|
123
|
-
return Array.from(definitions.values()).map((def) => ({
|
|
124
|
-
name: def.name,
|
|
125
|
-
version: def.version,
|
|
126
|
-
description: def.description,
|
|
127
|
-
schema: def.schema
|
|
128
|
-
}));
|
|
129
|
-
},
|
|
130
|
-
validate(name, payload, version) {
|
|
131
|
-
let target = version !== void 0 ? definitions.get(registryKey(name, version)) : void 0;
|
|
132
|
-
if (!target && version === void 0) {
|
|
133
|
-
let latestVersion = -1;
|
|
134
|
-
for (const candidate of definitions.values()) if (candidate.name === name && candidate.version > latestVersion) {
|
|
135
|
-
target = candidate;
|
|
136
|
-
latestVersion = candidate.version;
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
if (!target) return { valid: true };
|
|
140
|
-
if (!target.schema) return { valid: true };
|
|
141
|
-
return customValidator ? customValidator(target.schema, payload) : validatePayload(payload, target.schema);
|
|
142
|
-
}
|
|
143
|
-
};
|
|
144
|
-
}
|
|
145
|
-
/**
|
|
146
|
-
* Built-in minimal validator — lightweight guard, NOT a full JSON Schema engine.
|
|
147
|
-
*
|
|
148
|
-
* Checks:
|
|
149
|
-
* - payload is an object (not null, not array)
|
|
150
|
-
* - required fields are present
|
|
151
|
-
* - top-level property types match (string, number, boolean, array, object)
|
|
152
|
-
*
|
|
153
|
-
* Does NOT check:
|
|
154
|
-
* - nested object properties
|
|
155
|
-
* - array item types
|
|
156
|
-
* - enum, pattern, format, minLength, minimum, $ref
|
|
157
|
-
*
|
|
158
|
-
* For full validation, pass a custom `validate` function to `createEventRegistry()`.
|
|
159
|
-
*/
|
|
160
|
-
function validatePayload(payload, schema) {
|
|
161
|
-
const errors = [];
|
|
162
|
-
if (schema.type === "object") {
|
|
163
|
-
if (payload === null || payload === void 0 || typeof payload !== "object" || Array.isArray(payload)) return {
|
|
164
|
-
valid: false,
|
|
165
|
-
errors: ["Payload must be an object"]
|
|
166
|
-
};
|
|
167
|
-
const record = payload;
|
|
168
|
-
if (schema.required) {
|
|
169
|
-
for (const field of schema.required) if (!(field in record) || record[field] === void 0) errors.push(`Missing required field: '${field}'`);
|
|
170
|
-
}
|
|
171
|
-
if (schema.properties) {
|
|
172
|
-
for (const [key, propSchema] of Object.entries(schema.properties)) if (key in record && record[key] !== void 0 && record[key] !== null) {
|
|
173
|
-
const expectedType = propSchema.type;
|
|
174
|
-
if (expectedType) {
|
|
175
|
-
const value = record[key];
|
|
176
|
-
const actualType = Array.isArray(value) ? "array" : typeof value;
|
|
177
|
-
if (expectedType === "integer") {
|
|
178
|
-
if (actualType !== "number" || !Number.isInteger(value)) errors.push(`Field '${key}': expected integer, got ${actualType}`);
|
|
179
|
-
} else if (expectedType !== actualType) errors.push(`Field '${key}': expected ${expectedType}, got ${actualType}`);
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
return errors.length === 0 ? { valid: true } : {
|
|
185
|
-
valid: false,
|
|
186
|
-
errors
|
|
187
|
-
};
|
|
188
|
-
}
|
|
189
|
-
//#endregion
|
|
190
8
|
//#region src/events/eventTypes.ts
|
|
191
9
|
/**
|
|
192
10
|
* Event Type Constants and Helpers
|
|
@@ -251,6 +69,19 @@ const DEFAULT_LEASE_MS$2 = 3e4;
|
|
|
251
69
|
var MemoryOutboxStore = class {
|
|
252
70
|
entries = [];
|
|
253
71
|
seenDedupeKeys = /* @__PURE__ */ new Set();
|
|
72
|
+
/**
|
|
73
|
+
* Drop every entry (including delivered / failed / dead-lettered rows) and
|
|
74
|
+
* the dedupe-key memory.
|
|
75
|
+
*
|
|
76
|
+
* For tests only — it is the in-memory analogue of truncating the table, and
|
|
77
|
+
* exists so a suite can isolate cases against ONE store instance (the
|
|
78
|
+
* `reset` hook of `runOutboxStoreContract`). Not part of `OutboxStore`; a
|
|
79
|
+
* production store must never expose this.
|
|
80
|
+
*/
|
|
81
|
+
clear() {
|
|
82
|
+
this.entries.length = 0;
|
|
83
|
+
this.seenDedupeKeys.clear();
|
|
84
|
+
}
|
|
254
85
|
async save(event, options) {
|
|
255
86
|
if (!event?.type || typeof event.type !== "string") throw new InvalidOutboxEventError("event.type is required");
|
|
256
87
|
if (!event.meta?.id || typeof event.meta.id !== "string") throw new InvalidOutboxEventError("event.meta.id is required");
|
|
@@ -467,7 +298,10 @@ function exponentialBackoff(options) {
|
|
|
467
298
|
const DEFAULT_LEASE_MS$1 = 3e4;
|
|
468
299
|
const DEFAULT_CLAIM_LIMIT = 100;
|
|
469
300
|
const DEFAULT_PURGE_BATCH = 500;
|
|
470
|
-
|
|
301
|
+
/** Column this adapter reads/writes for the visibility timestamp. */
|
|
302
|
+
const DEFAULT_VISIBLE_AT_FIELD = "visibleAt";
|
|
303
|
+
function repositoryAsOutboxStore(repository, options) {
|
|
304
|
+
const visibleAtField = options?.visibleAtField ?? DEFAULT_VISIBLE_AT_FIELD;
|
|
471
305
|
const missing = [];
|
|
472
306
|
if (typeof repository.create !== "function") missing.push("create");
|
|
473
307
|
if (typeof repository.getOne !== "function") missing.push("getOne");
|
|
@@ -494,7 +328,7 @@ function repositoryAsOutboxStore(repository) {
|
|
|
494
328
|
* lease. Used by `getPending` and `claimPending` — defined once so the
|
|
495
329
|
* two code paths stay in lockstep.
|
|
496
330
|
*/
|
|
497
|
-
const claimableFilter = (now) => and(eq("status", "pending"), lte(
|
|
331
|
+
const claimableFilter = (now) => and(eq("status", "pending"), lte(visibleAtField, now), or(eq("leaseOwner", null), lte("leaseExpiresAt", now)));
|
|
498
332
|
return {
|
|
499
333
|
async save(event, options) {
|
|
500
334
|
if (!event?.type || typeof event.type !== "string") throw new InvalidOutboxEventError("event.type is required");
|
|
@@ -506,7 +340,7 @@ function repositoryAsOutboxStore(repository) {
|
|
|
506
340
|
type: event.type,
|
|
507
341
|
status: "pending",
|
|
508
342
|
attempts: 0,
|
|
509
|
-
|
|
343
|
+
[visibleAtField]: options?.visibleAt ?? now,
|
|
510
344
|
leaseOwner: null,
|
|
511
345
|
leaseExpiresAt: null,
|
|
512
346
|
deliveredAt: null,
|
|
@@ -592,7 +426,7 @@ function repositoryAsOutboxStore(repository) {
|
|
|
592
426
|
const firstFailedAt = current.firstFailedAt ?? now;
|
|
593
427
|
if (await r.findOneAndUpdate(filter, update({ set: {
|
|
594
428
|
status: targetStatus,
|
|
595
|
-
visibleAt,
|
|
429
|
+
[visibleAtField]: visibleAt,
|
|
596
430
|
leaseOwner: null,
|
|
597
431
|
leaseExpiresAt: null,
|
|
598
432
|
lastFailedAt: now,
|
|
@@ -960,157 +794,4 @@ function normalizeError(err) {
|
|
|
960
794
|
return { message: String(err) };
|
|
961
795
|
}
|
|
962
796
|
//#endregion
|
|
963
|
-
//#region src/events/subscribe-helpers.ts
|
|
964
|
-
/**
|
|
965
|
-
* Subscribe-side helpers — close the symmetry that arc's publish-side
|
|
966
|
-
* already has via [`eventPlugin({ registry, validateMode: 'reject' })`](./eventPlugin.ts).
|
|
967
|
-
*
|
|
968
|
-
* Two wrapper pairs, both transport-agnostic:
|
|
969
|
-
*
|
|
970
|
-
* - `wrapWithSchema` / `subscribeWithSchema` — read the schema from a
|
|
971
|
-
* typed `EventDefinitionOutput<T>` and validate `event.payload` before
|
|
972
|
-
* the handler runs. Single source of truth for event shape: declare
|
|
973
|
-
* once at `defineEvent`, enforced on BOTH sides without parallel Zod
|
|
974
|
-
* schemas in subscriber files.
|
|
975
|
-
*
|
|
976
|
-
* - `wrapWithBoundary` / `subscribeWithBoundary` — catch + log + swallow
|
|
977
|
-
* handler errors, for projection / cache-invalidation / fire-and-forget
|
|
978
|
-
* handlers where retry would just delay the next-event resync. Lighter
|
|
979
|
-
* than `withRetry` (no DLQ, no exponential backoff) and avoids the
|
|
980
|
-
* "single bad event poisons the bus" hazard.
|
|
981
|
-
*
|
|
982
|
-
* Both pairs compose with `withRetry` and with each other:
|
|
983
|
-
*
|
|
984
|
-
* ```ts
|
|
985
|
-
* await subscribeWithSchema(
|
|
986
|
-
* fastify,
|
|
987
|
-
* OrderPaid,
|
|
988
|
-
* withRetry(handler, { maxRetries: 3 }),
|
|
989
|
-
* );
|
|
990
|
-
* ```
|
|
991
|
-
*
|
|
992
|
-
* @see [retry.ts](./retry.ts) for the retry + DLQ wrapper.
|
|
993
|
-
* @see [defineEvent.ts](./defineEvent.ts) for `defineEvent` / `EventDefinitionOutput`.
|
|
994
|
-
*/
|
|
995
|
-
/**
|
|
996
|
-
* Pure handler wrapper — returns a new `EventHandler` that validates
|
|
997
|
-
* `event.payload` against the definition's schema before invoking the handler.
|
|
998
|
-
*
|
|
999
|
-
* The returned handler's input is `DomainEvent<unknown>` (since the transport
|
|
1000
|
-
* delivers untyped events) but the inner `handler` receives `DomainEvent<T>`.
|
|
1001
|
-
* No cast at the call site.
|
|
1002
|
-
*
|
|
1003
|
-
* @example
|
|
1004
|
-
* ```ts
|
|
1005
|
-
* await fastify.events.subscribe(
|
|
1006
|
-
* OrderPaid.name,
|
|
1007
|
-
* wrapWithSchema(OrderPaid, async (event) => {
|
|
1008
|
-
* // event.payload is typed via the registered schema — no cast.
|
|
1009
|
-
* await postSalesEntry(event.payload.orderId, event.payload.total);
|
|
1010
|
-
* }),
|
|
1011
|
-
* );
|
|
1012
|
-
* ```
|
|
1013
|
-
*/
|
|
1014
|
-
function wrapWithSchema(definition, handler, options = {}) {
|
|
1015
|
-
const { validate, registry, onInvalid, logger = console, name } = options;
|
|
1016
|
-
const label = name ?? definition.name;
|
|
1017
|
-
return async (event) => {
|
|
1018
|
-
const eventVersion = typeof event.meta?.schemaVersion === "number" ? event.meta.schemaVersion : definition.version;
|
|
1019
|
-
let result;
|
|
1020
|
-
if (validate && definition.schema) result = validate(definition.schema, event.payload);
|
|
1021
|
-
else if (registry) result = registry.validate(definition.name, event.payload, eventVersion);
|
|
1022
|
-
else if (definition.schema) {
|
|
1023
|
-
const adhoc = createEventRegistry();
|
|
1024
|
-
adhoc.register(definition);
|
|
1025
|
-
result = adhoc.validate(definition.name, event.payload);
|
|
1026
|
-
} else result = { valid: true };
|
|
1027
|
-
if (!result.valid) {
|
|
1028
|
-
const errors = result.errors ?? ["payload failed validation"];
|
|
1029
|
-
if (onInvalid) try {
|
|
1030
|
-
await onInvalid(event, errors);
|
|
1031
|
-
} catch (cbErr) {
|
|
1032
|
-
logger.error(`[Arc Events] '${label}' onInvalid callback threw:`, cbErr);
|
|
1033
|
-
}
|
|
1034
|
-
else logger.warn(`[Arc Events] '${label}' skipped event ${event.meta?.id ?? "<no-id>"} — payload failed validation: ${errors.join("; ")}`);
|
|
1035
|
-
return;
|
|
1036
|
-
}
|
|
1037
|
-
await handler(event);
|
|
1038
|
-
};
|
|
1039
|
-
}
|
|
1040
|
-
/**
|
|
1041
|
-
* Convenience: validate + subscribe in one call. Equivalent to
|
|
1042
|
-
* `fastify.events.subscribe(definition.name, wrapWithSchema(definition, handler, options))`.
|
|
1043
|
-
*
|
|
1044
|
-
* Returns the unsubscribe function from the underlying transport.
|
|
1045
|
-
*
|
|
1046
|
-
* @example
|
|
1047
|
-
* ```ts
|
|
1048
|
-
* await subscribeWithSchema(fastify, OrderPaid, async (event) => {
|
|
1049
|
-
* await postSalesEntry(event.payload.orderId, event.payload.total);
|
|
1050
|
-
* });
|
|
1051
|
-
*
|
|
1052
|
-
* // Compose with withRetry — schema validation runs FIRST, then retry on
|
|
1053
|
-
* // handler failure. Invalid payloads skip without burning retry attempts.
|
|
1054
|
-
* await subscribeWithSchema(
|
|
1055
|
-
* fastify,
|
|
1056
|
-
* OrderPaid,
|
|
1057
|
-
* withRetry(handler, { maxRetries: 3 }),
|
|
1058
|
-
* );
|
|
1059
|
-
* ```
|
|
1060
|
-
*/
|
|
1061
|
-
async function subscribeWithSchema(fastify, definition, handler, options) {
|
|
1062
|
-
return fastify.events.subscribe(definition.name, wrapWithSchema(definition, handler, options));
|
|
1063
|
-
}
|
|
1064
|
-
/**
|
|
1065
|
-
* Pure handler wrapper — returns a new `EventHandler` that catches handler
|
|
1066
|
-
* exceptions and routes them to `onError` (or logs and swallows). For
|
|
1067
|
-
* projection / cache-invalidation / fire-and-forget handlers where retry
|
|
1068
|
-
* would just delay the next-event resync, and where one bad event must NOT
|
|
1069
|
-
* stop processing of subsequent events.
|
|
1070
|
-
*
|
|
1071
|
-
* Lighter than `withRetry`: no exponential backoff, no DLQ. Composes with
|
|
1072
|
-
* `withRetry` if you want both ("retry, then log if exhausted, never throw").
|
|
1073
|
-
*
|
|
1074
|
-
* @example
|
|
1075
|
-
* ```ts
|
|
1076
|
-
* await fastify.events.subscribe(
|
|
1077
|
-
* 'product:variants.changed',
|
|
1078
|
-
* wrapWithBoundary(async (event) => {
|
|
1079
|
-
* cache.invalidate(event.payload.productId);
|
|
1080
|
-
* }),
|
|
1081
|
-
* );
|
|
1082
|
-
* ```
|
|
1083
|
-
*/
|
|
1084
|
-
function wrapWithBoundary(handler, options = {}) {
|
|
1085
|
-
const { onError, logger = console, name } = options;
|
|
1086
|
-
const label = name ?? handler.name ?? "anonymous";
|
|
1087
|
-
return async (event) => {
|
|
1088
|
-
try {
|
|
1089
|
-
await handler(event);
|
|
1090
|
-
} catch (err) {
|
|
1091
|
-
const error = err instanceof Error ? err : new Error(String(err));
|
|
1092
|
-
if (onError) try {
|
|
1093
|
-
await onError(error, event);
|
|
1094
|
-
} catch (cbErr) {
|
|
1095
|
-
logger.error(`[Arc Events] '${label}' onError callback threw:`, cbErr);
|
|
1096
|
-
}
|
|
1097
|
-
else logger.error(`[Arc Events] '${label}' threw on ${event.type} — swallowed (boundary): ${error.message}`, {
|
|
1098
|
-
err: error,
|
|
1099
|
-
event: event.type,
|
|
1100
|
-
eventId: event.meta?.id,
|
|
1101
|
-
handler: label
|
|
1102
|
-
});
|
|
1103
|
-
}
|
|
1104
|
-
};
|
|
1105
|
-
}
|
|
1106
|
-
/**
|
|
1107
|
-
* Convenience: subscribe + error-boundary in one call. Equivalent to
|
|
1108
|
-
* `fastify.events.subscribe(pattern, wrapWithBoundary(handler, options))`.
|
|
1109
|
-
*
|
|
1110
|
-
* Returns the unsubscribe function from the underlying transport.
|
|
1111
|
-
*/
|
|
1112
|
-
async function subscribeWithBoundary(fastify, pattern, handler, options) {
|
|
1113
|
-
return fastify.events.subscribe(pattern, wrapWithBoundary(handler, options));
|
|
1114
|
-
}
|
|
1115
|
-
//#endregion
|
|
1116
797
|
export { ARC_LIFECYCLE_EVENTS, CACHE_EVENTS, CRUD_EVENT_SUFFIXES, EventOutbox, MemoryEventTransport, MemoryOutboxStore, createDeadLetterPublisher, createEventRegistry, crudEventType, defineEvent, eventPlugin, exponentialBackoff, repositoryAsOutboxStore, subscribeWithBoundary, subscribeWithSchema, withRetry, wrapWithBoundary, wrapWithSchema };
|
package/dist/factory/index.d.mts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import "../
|
|
3
|
-
import
|
|
1
|
+
import { a as ModuleContribution, c as ResourceModule, h as HealthCheck, i as EventHandlerDefinition, l as loadResources, n as ArcModuleInput, o as LoadResourcesOptions, r as ArcModuleRegistry, s as ResourceLike, t as ArcModule } from "../types-D_n8L6VY.mjs";
|
|
2
|
+
import { a as orderModules, c as collectModuleScheduledJobs, i as resolveModule, l as collectModuleWorkflows, n as getModuleExports, o as subscribeModuleEventHandlers, r as resolveContribution, s as collectModuleHealthChecks, t as defineModule } from "../index-CCzVR-N3.mjs";
|
|
3
|
+
import "../fastify-augmentation-0WhPnUH7.mjs";
|
|
4
|
+
import { a as RawBodyOptions, c as BetterAuthOption, d as JwtAuthOption, i as MultipartOptions, l as CustomAuthenticatorOption, n as preloadResourcesAsync, o as UnderPressureOptions, r as CreateAppOptions, s as AuthOption, t as preloadResources, u as CustomPluginAuthOption } from "../preloadResources-DCfa2egz.mjs";
|
|
4
5
|
import { FastifyInstance, FastifyServerOptions } from "fastify";
|
|
5
6
|
//#region src/factory/createApp.d.ts
|
|
6
7
|
/**
|
package/dist/factory/index.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { r as mergeHealthChecks, t as healthPlugin } from "../health-CB_m4S32.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { a as edgePreset, c as testingPreset, d as subscribeModuleEventHandlers, f as collectModuleHealthChecks, g as resolveModule, h as resolveContribution, i as developmentPreset, l as workerPreset, m as collectModuleWorkflows, n as createApp, o as getPreset, p as collectModuleScheduledJobs, s as productionPreset, t as ArcFactory, u as orderModules } from "../createApp-CXrKFciH.mjs";
|
|
3
|
+
import { n as getModuleExports, t as defineModule } from "../module-_-M7C5ES.mjs";
|
|
3
4
|
import { t as loadResources } from "../loadResources-DpU8pfjV.mjs";
|
|
5
|
+
import { n as preloadResourcesAsync, t as preloadResources } from "../preloadResources-DSY5HGpS.mjs";
|
|
4
6
|
//#region src/factory/createWorker.ts
|
|
5
7
|
async function createWorker(options, workerOptions = {}) {
|
|
6
8
|
const { auth: _auth, helmet: _helmet, cors: _cors, rateLimit: _rateLimit, multipart: _multipart, rawBody: _rawBody, sensible: _sensible, underPressure: _underPressure, replyHelpers: _replyHelpers, ...runtimeOptions } = options;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { mn as HookSystem, z as ResourceRegistry } from "./index-
|
|
1
|
+
import { mn as HookSystem, z as ResourceRegistry } from "./index-Q5gzEIWY.mjs";
|
|
2
2
|
import { t as ExternalOpenApiPaths } from "./externalPaths-BE6wFpYv.mjs";
|
|
3
|
-
import {
|
|
3
|
+
import { h as HealthCheck, r as ArcModuleRegistry, t as ArcModule, u as ScheduleDefinition } from "./types-D_n8L6VY.mjs";
|
|
4
|
+
import "./index-CCzVR-N3.mjs";
|
|
4
5
|
import { FastifyPluginAsync } from "fastify";
|
|
5
6
|
//#region src/core/arcCorePlugin.d.ts
|
|
6
7
|
interface ArcCorePluginOptions {
|
|
@@ -165,100 +165,4 @@ function resolveEffectiveRoles(userRoles, orgRoles) {
|
|
|
165
165
|
return [.../* @__PURE__ */ new Set([...userRoles, ...orgRoles])];
|
|
166
166
|
}
|
|
167
167
|
//#endregion
|
|
168
|
-
|
|
169
|
-
/**
|
|
170
|
-
* Normalize a permission check return value (`boolean | PermissionResult`)
|
|
171
|
-
* into a concrete `PermissionResult`. This is the only place in Arc that
|
|
172
|
-
* promotes booleans to results — keeps the type narrowing honest everywhere.
|
|
173
|
-
*/
|
|
174
|
-
function normalizePermissionResult(result) {
|
|
175
|
-
if (typeof result === "boolean") return { granted: result };
|
|
176
|
-
return result;
|
|
177
|
-
}
|
|
178
|
-
/**
|
|
179
|
-
* Apply a granted `PermissionResult` to a Fastify request — merges row-level
|
|
180
|
-
* filters into `_policyFilters` and conditionally installs the scope.
|
|
181
|
-
*
|
|
182
|
-
* **Scope install rule:** only writes `scope` when the current request scope
|
|
183
|
-
* is absent or `public`. This prevents downgrading an already-authenticated
|
|
184
|
-
* request (e.g. Better Auth set `member`, then a permission check returns a
|
|
185
|
-
* narrower `service` scope — the original `member` wins because it came from
|
|
186
|
-
* a more authoritative source).
|
|
187
|
-
*
|
|
188
|
-
* Safe to call with a non-granted result — it simply no-ops. Callers should
|
|
189
|
-
* still check `result.granted` and send an error response before reaching here,
|
|
190
|
-
* but this function tolerates the misuse defensively.
|
|
191
|
-
*/
|
|
192
|
-
function applyPermissionResult(result, request) {
|
|
193
|
-
if (!result.granted) return;
|
|
194
|
-
if (result.filters) request._policyFilters = {
|
|
195
|
-
...request._policyFilters ?? {},
|
|
196
|
-
...result.filters
|
|
197
|
-
};
|
|
198
|
-
if (result.scope) {
|
|
199
|
-
const current = request.scope;
|
|
200
|
-
if (!current || current.kind === "public") request.scope = result.scope;
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
/**
|
|
204
|
-
* Max length of a `PermissionResult.reason` string before we fall back to the
|
|
205
|
-
* generic default message. Upstream checks can return arbitrary strings; we
|
|
206
|
-
* clamp to prevent accidental leakage of internal diagnostics or oversized
|
|
207
|
-
* payloads via the 4xx response body.
|
|
208
|
-
*/
|
|
209
|
-
const MAX_DENIAL_REASON_LENGTH = 100;
|
|
210
|
-
/**
|
|
211
|
-
* End-to-end evaluator: runs the permission check, catches throws, normalizes
|
|
212
|
-
* the result, sends a 401/403 response on denial, and applies side-effects on
|
|
213
|
-
* grant. Returns `true` if the caller should continue, `false` if a response
|
|
214
|
-
* has been sent and the caller should return.
|
|
215
|
-
*
|
|
216
|
-
* This is the single source of truth for the 5-step sequence shared by the
|
|
217
|
-
* CRUD router, action router, and MCP tool handlers:
|
|
218
|
-
*
|
|
219
|
-
* 1. `try { await check(ctx) } catch { reply 403 }`
|
|
220
|
-
* 2. `normalizePermissionResult(result)`
|
|
221
|
-
* 3. If denied → 401 (no user) or 403 (user) with clamped reason
|
|
222
|
-
* 4. If granted → `applyPermissionResult` (filters + scope)
|
|
223
|
-
* 5. Return true/false so the caller knows whether to keep going
|
|
224
|
-
*
|
|
225
|
-
* Context construction, pre-check auth gating, and success-path handler
|
|
226
|
-
* invocation stay at the callsite — those are genuinely different per router
|
|
227
|
-
* and don't belong here.
|
|
228
|
-
*
|
|
229
|
-
* @returns `true` if authorized (caller continues), `false` if a response was sent
|
|
230
|
-
*/
|
|
231
|
-
async function evaluateAndApplyPermission(check, context, request, reply, opts) {
|
|
232
|
-
let result;
|
|
233
|
-
try {
|
|
234
|
-
result = await check(context);
|
|
235
|
-
} catch (err) {
|
|
236
|
-
request.log?.warn?.({
|
|
237
|
-
err,
|
|
238
|
-
resource: context.resource,
|
|
239
|
-
action: context.action
|
|
240
|
-
}, "Permission check threw");
|
|
241
|
-
reply.code(403).send({
|
|
242
|
-
code: "arc.forbidden",
|
|
243
|
-
message: "Permission denied",
|
|
244
|
-
status: 403
|
|
245
|
-
});
|
|
246
|
-
return false;
|
|
247
|
-
}
|
|
248
|
-
const permResult = normalizePermissionResult(result);
|
|
249
|
-
if (!permResult.granted) {
|
|
250
|
-
const defaultMsg = opts?.defaultDenialMessage?.(context.user) ?? (context.user ? "Permission denied" : "Authentication required");
|
|
251
|
-
const reason = permResult.reason && permResult.reason.length <= MAX_DENIAL_REASON_LENGTH ? permResult.reason : defaultMsg;
|
|
252
|
-
const status = context.user ? 403 : 401;
|
|
253
|
-
reply.code(status).send({
|
|
254
|
-
code: context.user ? "arc.forbidden" : "arc.unauthorized",
|
|
255
|
-
message: reason,
|
|
256
|
-
status
|
|
257
|
-
});
|
|
258
|
-
return false;
|
|
259
|
-
}
|
|
260
|
-
applyPermissionResult(permResult, request);
|
|
261
|
-
return true;
|
|
262
|
-
}
|
|
263
|
-
//#endregion
|
|
264
|
-
export { applyFieldWritePermissions as a, applyFieldReadPermissions as i, evaluateAndApplyPermission as n, fields as o, normalizePermissionResult as r, resolveEffectiveRoles as s, applyPermissionResult as t };
|
|
168
|
+
export { resolveEffectiveRoles as i, applyFieldWritePermissions as n, fields as r, applyFieldReadPermissions as t };
|
package/dist/hooks/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Cn as defineHook, Sn as createHookSystem, _n as afterDelete, bn as beforeDelete, cn as DefineHookOptions, dn as HookOperation, fn as HookPhase, gn as afterCreate, hn as HookSystemOptions, ln as HookContext, mn as HookSystem, pn as HookRegistration, un as HookHandler, vn as afterUpdate, xn as beforeUpdate, yn as beforeCreate } from "../index-
|
|
1
|
+
import { Cn as defineHook, Sn as createHookSystem, _n as afterDelete, bn as beforeDelete, cn as DefineHookOptions, dn as HookOperation, fn as HookPhase, gn as afterCreate, hn as HookSystemOptions, ln as HookContext, mn as HookSystem, pn as HookRegistration, un as HookHandler, vn as afterUpdate, xn as beforeUpdate, yn as beforeCreate } from "../index-Q5gzEIWY.mjs";
|
|
2
2
|
export { type DefineHookOptions, type HookContext, type HookHandler, type HookOperation, type HookPhase, type HookRegistration, HookSystem, type HookSystemOptions, afterCreate, afterDelete, afterUpdate, beforeCreate, beforeDelete, beforeUpdate, createHookSystem, defineHook };
|
package/dist/hooks/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as beforeCreate, c as createHookSystem, i as afterUpdate, l as defineHook, n as afterCreate, o as beforeDelete, r as afterDelete, s as beforeUpdate, t as HookSystem } from "../HookSystem-
|
|
1
|
+
import { a as beforeCreate, c as createHookSystem, i as afterUpdate, l as defineHook, n as afterCreate, o as beforeDelete, r as afterDelete, s as beforeUpdate, t as HookSystem } from "../HookSystem-WkIougo6.mjs";
|
|
2
2
|
export { HookSystem, afterCreate, afterDelete, afterUpdate, beforeCreate, beforeDelete, beforeUpdate, createHookSystem, defineHook };
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { n as requireSingleHeaderValue } from "../headers-BvlQSDMB.mjs";
|
|
2
2
|
import { n as createSafeGetOne, t as createIsDuplicateKeyError } from "../store-helpers-DY6xq4sM.mjs";
|
|
3
3
|
import { t as createIdempotencyResult } from "../interface-n5hpKg1d.mjs";
|
|
4
|
+
import { and, eq, exists, gt, lt, or, startsWith } from "@classytic/repo-core/filter";
|
|
4
5
|
import { createHash } from "node:crypto";
|
|
5
6
|
import fp from "fastify-plugin";
|
|
6
|
-
import { and, eq, exists, gt, lt, or, startsWith } from "@classytic/repo-core/filter";
|
|
7
7
|
import { update } from "@classytic/repo-core/update";
|
|
8
8
|
//#region src/idempotency/repository-idempotency-adapter.ts
|
|
9
9
|
function repositoryAsIdempotencyStore(repository, defaultTtlMs) {
|