@dyrected/core 2.6.4 → 2.7.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.
@@ -0,0 +1,3537 @@
1
+ // src/observability.ts
2
+ import {
3
+ TraceFlags,
4
+ context as otelContext,
5
+ trace
6
+ } from "@opentelemetry/api";
7
+ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";
8
+ import { PrometheusExporter } from "@opentelemetry/exporter-prometheus";
9
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
10
+ import { resourceFromAttributes } from "@opentelemetry/resources";
11
+ import {
12
+ MeterProvider,
13
+ PeriodicExportingMetricReader
14
+ } from "@opentelemetry/sdk-metrics";
15
+ import {
16
+ BasicTracerProvider,
17
+ BatchSpanProcessor,
18
+ ConsoleSpanExporter
19
+ } from "@opentelemetry/sdk-trace-base";
20
+ import pino, {
21
+ destination as pinoDestination,
22
+ multistream,
23
+ stdTimeFunctions
24
+ } from "pino";
25
+ import pinoPretty from "pino-pretty";
26
+ import { Writable } from "stream";
27
+ var DEFAULT_REDACT_HEADERS = ["authorization", "cookie", "set-cookie", "x-api-key"];
28
+ var DEFAULT_REDACT_PATHS = [
29
+ "password",
30
+ "currentPassword",
31
+ "newPassword",
32
+ "confirmPassword",
33
+ "token",
34
+ "refreshToken",
35
+ "accessToken",
36
+ "secret",
37
+ "apiKey",
38
+ "inviteToken",
39
+ "resetToken"
40
+ ];
41
+ var DEFAULT_MAX_BODY_BYTES = 8192;
42
+ var DEFAULT_SUCCESS_SAMPLE_RATE = 0.1;
43
+ var DEFAULT_BODY_SAMPLE_RATE = 0.02;
44
+ var REDACTED_VALUE = "[REDACTED]";
45
+ var runtimeByConfig = /* @__PURE__ */ new WeakMap();
46
+ var fallbackLogger = pino({
47
+ name: "dyrected",
48
+ enabled: process.env.DISABLE_LOGGING !== "true",
49
+ timestamp: stdTimeFunctions.isoTime
50
+ });
51
+ function resolveObservabilityConfig(config) {
52
+ const requestLogging = config?.requestLogging;
53
+ const sampling = config?.sampling;
54
+ const tracing = config?.tracing;
55
+ const metrics = config?.metrics;
56
+ return {
57
+ requestLogging: {
58
+ enabled: requestLogging?.enabled ?? true,
59
+ logBodies: requestLogging?.logBodies ?? false,
60
+ maxBodyBytes: requestLogging?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES,
61
+ redactPaths: uniqueValues([
62
+ ...DEFAULT_REDACT_PATHS,
63
+ ...requestLogging?.redactPaths ?? []
64
+ ]),
65
+ includeHeaders: normalizeHeaderNames(requestLogging?.includeHeaders ?? []),
66
+ redactHeaders: uniqueValues(
67
+ normalizeHeaderNames([
68
+ ...DEFAULT_REDACT_HEADERS,
69
+ ...requestLogging?.redactHeaders ?? []
70
+ ])
71
+ )
72
+ },
73
+ sampling: {
74
+ successRate: clampRate(sampling?.successRate ?? DEFAULT_SUCCESS_SAMPLE_RATE),
75
+ traceSuccessRate: clampRate(
76
+ sampling?.traceSuccessRate ?? sampling?.successRate ?? DEFAULT_SUCCESS_SAMPLE_RATE
77
+ ),
78
+ bodySuccessRate: clampRate(
79
+ sampling?.bodySuccessRate ?? Math.min(DEFAULT_BODY_SAMPLE_RATE, sampling?.successRate ?? DEFAULT_SUCCESS_SAMPLE_RATE)
80
+ ),
81
+ alwaysKeep4xx: sampling?.alwaysKeep4xx ?? true,
82
+ alwaysKeep5xx: sampling?.alwaysKeep5xx ?? true
83
+ },
84
+ tracing: {
85
+ enabled: tracing?.enabled ?? false,
86
+ serviceName: tracing?.serviceName ?? "dyrected",
87
+ exporter: tracing?.exporter ?? "none",
88
+ headers: tracing?.headers ?? {},
89
+ endpoint: tracing?.endpoint
90
+ },
91
+ metrics: {
92
+ enabled: metrics?.enabled ?? false,
93
+ exporter: metrics?.exporter ?? "none",
94
+ endpoint: metrics?.endpoint,
95
+ path: metrics?.path ?? "/metrics"
96
+ },
97
+ transports: {
98
+ targets: config?.transports?.targets && config.transports.targets.length > 0 ? config.transports.targets : [{ type: "stdout" }]
99
+ }
100
+ };
101
+ }
102
+ function createObservabilityRuntime(config) {
103
+ const resolved = resolveObservabilityConfig(config.observability);
104
+ const logger = createRootLogger(config.logger, resolved);
105
+ const shutdownTasks = [];
106
+ const meterRuntime = resolved.metrics.enabled || resolved.metrics.exporter === "prometheus" ? createMeterProvider(resolved) : void 0;
107
+ const tracerProvider = resolved.tracing.enabled ? createTracerProvider(resolved) : void 0;
108
+ const tracer = tracerProvider?.getTracer("dyrected");
109
+ const meter = meterRuntime?.provider.getMeter("dyrected");
110
+ const metrics = meter ? {
111
+ requestCount: meter.createCounter("dyrected_http_requests_total", {
112
+ description: "Total HTTP requests served by Dyrected"
113
+ }),
114
+ authFailureCount: meter.createCounter("dyrected_auth_failures_total", {
115
+ description: "Authentication failures"
116
+ }),
117
+ uncaughtErrorCount: meter.createCounter("dyrected_uncaught_errors_total", {
118
+ description: "Uncaught application errors"
119
+ }),
120
+ auditWriteFailureCount: meter.createCounter("dyrected_audit_write_failures_total", {
121
+ description: "Audit log persistence failures"
122
+ }),
123
+ emailSendFailureCount: meter.createCounter("dyrected_email_send_failures_total", {
124
+ description: "Transactional email delivery failures"
125
+ }),
126
+ workflowHookFailureCount: meter.createCounter("dyrected_workflow_hook_failures_total", {
127
+ description: "Workflow hook failures isolated after successful writes"
128
+ }),
129
+ requestDuration: meter.createHistogram("dyrected_http_request_duration_ms", {
130
+ description: "HTTP request duration in milliseconds",
131
+ unit: "ms"
132
+ })
133
+ } : void 0;
134
+ if (meterRuntime) {
135
+ shutdownTasks.push(() => meterRuntime.provider.shutdown());
136
+ }
137
+ if (tracerProvider) {
138
+ shutdownTasks.push(() => tracerProvider.shutdown());
139
+ }
140
+ return {
141
+ logger,
142
+ config: resolved,
143
+ tracer,
144
+ metrics,
145
+ prometheusExporter: meterRuntime?.prometheusExporter,
146
+ shutdown: async () => {
147
+ for (const task of shutdownTasks) {
148
+ await task();
149
+ }
150
+ },
151
+ recordAuthFailure: (attributes) => metrics?.authFailureCount.add(1, attributes),
152
+ recordUncaughtError: (attributes) => metrics?.uncaughtErrorCount.add(1, attributes),
153
+ recordAuditWriteFailure: (attributes) => metrics?.auditWriteFailureCount.add(1, attributes),
154
+ recordEmailSendFailure: (attributes) => metrics?.emailSendFailureCount.add(1, attributes),
155
+ recordWorkflowHookFailure: (attributes) => metrics?.workflowHookFailureCount.add(1, attributes)
156
+ };
157
+ }
158
+ function bindObservabilityRuntime(config, runtime) {
159
+ runtimeByConfig.set(config, runtime);
160
+ }
161
+ function getObservabilityRuntime(config) {
162
+ if (!config || typeof config !== "object") return void 0;
163
+ return runtimeByConfig.get(config);
164
+ }
165
+ function createRootLogger(loggerConfig, observability) {
166
+ if (loggerConfig && !("options" in loggerConfig)) {
167
+ return loggerConfig;
168
+ }
169
+ const options = loggerConfig?.options ?? {};
170
+ const enabled = options.enabled ?? process.env.DISABLE_LOGGING !== "true";
171
+ const name = options.name ?? "dyrected";
172
+ if (loggerConfig?.destination) {
173
+ return pino(
174
+ {
175
+ ...options,
176
+ enabled,
177
+ name,
178
+ timestamp: options.timestamp ?? stdTimeFunctions.isoTime
179
+ },
180
+ loggerConfig.destination
181
+ );
182
+ }
183
+ const streams = buildTransportStreams(observability);
184
+ const destination = streams.length === 1 ? streams[0] : multistream(streams.map((stream) => ({ stream })));
185
+ return pino(
186
+ {
187
+ ...options,
188
+ enabled,
189
+ name,
190
+ timestamp: options.timestamp ?? stdTimeFunctions.isoTime
191
+ },
192
+ destination
193
+ );
194
+ }
195
+ function buildTransportStreams(observability) {
196
+ const targets = observability.transports.targets;
197
+ if (targets.length === 0) {
198
+ return [defaultLoggerDestination()];
199
+ }
200
+ return targets.map((target) => {
201
+ switch (target.type) {
202
+ case "stdout":
203
+ return defaultLoggerDestination();
204
+ case "stderr":
205
+ return pinoDestination(2);
206
+ case "file":
207
+ return pinoDestination(target.path);
208
+ case "otlp":
209
+ return new OtlpLogWritable(target.endpoint, target.headers);
210
+ }
211
+ });
212
+ }
213
+ function defaultLoggerDestination() {
214
+ if (process.env.NODE_ENV !== "production") {
215
+ return pinoPretty({
216
+ colorize: true,
217
+ ignore: "pid,hostname",
218
+ translateTime: "SYS:HH:MM:ss",
219
+ destination: 1,
220
+ sync: true
221
+ });
222
+ }
223
+ return pinoDestination(1);
224
+ }
225
+ var OtlpLogWritable = class extends Writable {
226
+ constructor(endpoint, headers = {}) {
227
+ super();
228
+ this.endpoint = endpoint;
229
+ this.headers = headers;
230
+ }
231
+ endpoint;
232
+ headers;
233
+ _write(chunk, _encoding, callback) {
234
+ const payload = chunk.toString();
235
+ void fetch(this.endpoint, {
236
+ method: "POST",
237
+ headers: {
238
+ "content-type": "application/json",
239
+ ...this.headers
240
+ },
241
+ body: JSON.stringify({ logs: payload.trim().split("\n").filter(Boolean) })
242
+ }).then(() => callback()).catch(
243
+ (error) => callback(error instanceof Error ? error : new Error(String(error)))
244
+ );
245
+ }
246
+ };
247
+ function createTracerProvider(observability) {
248
+ const exporter = createTraceExporter(observability);
249
+ const provider = new BasicTracerProvider({
250
+ resource: resourceFromAttributes({
251
+ "service.name": observability.tracing.serviceName
252
+ }),
253
+ spanProcessors: exporter ? [new BatchSpanProcessor(exporter)] : []
254
+ });
255
+ trace.setGlobalTracerProvider(provider);
256
+ return provider;
257
+ }
258
+ function createTraceExporter(observability) {
259
+ switch (observability.tracing.exporter) {
260
+ case "console":
261
+ return new ConsoleSpanExporter();
262
+ case "otlp":
263
+ return new OTLPTraceExporter({
264
+ url: observability.tracing.endpoint,
265
+ headers: observability.tracing.headers
266
+ });
267
+ default:
268
+ return void 0;
269
+ }
270
+ }
271
+ function createMeterProvider(observability) {
272
+ const readers = [];
273
+ let prometheusExporter;
274
+ switch (observability.metrics.exporter) {
275
+ case "otlp":
276
+ readers.push(
277
+ new PeriodicExportingMetricReader({
278
+ exporter: new OTLPMetricExporter({
279
+ url: observability.metrics.endpoint
280
+ })
281
+ })
282
+ );
283
+ break;
284
+ case "prometheus":
285
+ prometheusExporter = new PrometheusExporter({
286
+ endpoint: observability.metrics.path,
287
+ preventServerStart: true
288
+ });
289
+ readers.push(prometheusExporter);
290
+ break;
291
+ }
292
+ const provider = new MeterProvider({
293
+ resource: resourceFromAttributes({
294
+ "service.name": observability.tracing.serviceName
295
+ }),
296
+ readers
297
+ });
298
+ return { provider, prometheusExporter };
299
+ }
300
+ function getConfigLogger(config, component) {
301
+ const base = config?.logger && !("options" in config.logger) ? config.logger : fallbackLogger;
302
+ return base.child({ component });
303
+ }
304
+ function getRequestLogger(c, component) {
305
+ const base = c.get("logger") ?? fallbackLogger;
306
+ return component ? base.child({ component }) : base;
307
+ }
308
+ function buildRequestLogger(runtime, vars, requestId) {
309
+ const trace2 = vars.requestTrace;
310
+ return runtime.logger.child({
311
+ requestId,
312
+ siteId: vars.siteId,
313
+ workspaceId: vars.workspaceId,
314
+ traceId: trace2?.traceId,
315
+ spanId: trace2?.spanId
316
+ });
317
+ }
318
+ function shouldSampleRequest(requestId, statusCode, sampling, kind) {
319
+ if (statusCode >= 500 && sampling.alwaysKeep5xx) return true;
320
+ if (statusCode >= 400 && sampling.alwaysKeep4xx) return true;
321
+ const rate = kind === "trace" ? sampling.traceSuccessRate : kind === "body" ? sampling.bodySuccessRate : sampling.successRate;
322
+ return deterministicSample(requestId ?? "no-request-id", rate);
323
+ }
324
+ function redactHeaders(headers, observability) {
325
+ const includeHeaders = new Set(observability.requestLogging.includeHeaders);
326
+ const redactHeaders2 = new Set(observability.requestLogging.redactHeaders);
327
+ const output = {};
328
+ for (const [key, value] of Object.entries(headers)) {
329
+ const normalizedKey = key.toLowerCase();
330
+ if (includeHeaders.size > 0 && !includeHeaders.has(normalizedKey)) continue;
331
+ output[normalizedKey] = redactHeaders2.has(normalizedKey) ? REDACTED_VALUE : value;
332
+ }
333
+ return output;
334
+ }
335
+ async function captureRequestBody(request, observability) {
336
+ const contentType = request.headers.get("content-type") ?? void 0;
337
+ const contentLength = toNumber(request.headers.get("content-length"));
338
+ const jsonBody = contentType?.includes("application/json");
339
+ if (!jsonBody) {
340
+ return {
341
+ attempted: false,
342
+ contentType,
343
+ contentLength
344
+ };
345
+ }
346
+ try {
347
+ const text = await request.clone().text();
348
+ if (!text) {
349
+ return { attempted: true, contentType, contentLength };
350
+ }
351
+ const truncated = text.length > observability.requestLogging.maxBodyBytes;
352
+ const raw = truncated ? text.slice(0, observability.requestLogging.maxBodyBytes) : text;
353
+ try {
354
+ const parsed = JSON.parse(raw);
355
+ return {
356
+ attempted: true,
357
+ contentType,
358
+ contentLength: contentLength ?? text.length,
359
+ truncated,
360
+ body: redactBody(parsed, observability.requestLogging.redactPaths)
361
+ };
362
+ } catch {
363
+ return {
364
+ attempted: true,
365
+ contentType,
366
+ contentLength: contentLength ?? text.length,
367
+ truncated,
368
+ parseFailed: true
369
+ };
370
+ }
371
+ } catch {
372
+ return {
373
+ attempted: true,
374
+ contentType,
375
+ contentLength,
376
+ parseFailed: true
377
+ };
378
+ }
379
+ }
380
+ function redactBody(value, redactPaths) {
381
+ const cloned = deepClone(value);
382
+ for (const path of redactPaths) {
383
+ applyRedaction(cloned, path.split("."));
384
+ }
385
+ return cloned;
386
+ }
387
+ function applyRedaction(target, segments) {
388
+ if (!target || segments.length === 0) return;
389
+ const [segment, ...rest] = segments;
390
+ if (Array.isArray(target)) {
391
+ for (const item of target) {
392
+ if (segment === "*") {
393
+ applyRedaction(item, rest);
394
+ } else {
395
+ applyRedaction(item, segments);
396
+ }
397
+ }
398
+ return;
399
+ }
400
+ if (typeof target !== "object") return;
401
+ const record = target;
402
+ if (segment === "*") {
403
+ for (const value of Object.values(record)) {
404
+ applyRedaction(value, rest);
405
+ }
406
+ return;
407
+ }
408
+ if (!(segment in record)) return;
409
+ if (rest.length === 0) {
410
+ record[segment] = REDACTED_VALUE;
411
+ return;
412
+ }
413
+ applyRedaction(record[segment], rest);
414
+ }
415
+ function deepClone(value) {
416
+ if (typeof structuredClone === "function") {
417
+ return structuredClone(value);
418
+ }
419
+ return JSON.parse(JSON.stringify(value));
420
+ }
421
+ function createRequestSpan(runtime, name, attributes) {
422
+ if (!runtime.tracer) return void 0;
423
+ const span = runtime.tracer.startSpan(name, { attributes }, otelContext.active());
424
+ const spanContext = span.spanContext();
425
+ return {
426
+ span,
427
+ traceId: spanContext.traceId,
428
+ spanId: spanContext.spanId,
429
+ sampled: spanContext.traceFlags === TraceFlags.SAMPLED
430
+ };
431
+ }
432
+ function endRequestSpan(requestTrace, statusCode, error) {
433
+ if (!requestTrace) return;
434
+ requestTrace.span.setAttribute("http.status_code", statusCode);
435
+ if (error) {
436
+ requestTrace.span.recordException(error instanceof Error ? error : new Error(String(error)));
437
+ }
438
+ requestTrace.span.end();
439
+ }
440
+ function attachRequestMetrics(runtime, args) {
441
+ runtime.metrics?.requestCount.add(1, {
442
+ method: args.method,
443
+ route: args.route,
444
+ status_class: `${Math.floor(args.statusCode / 100)}xx`
445
+ });
446
+ runtime.metrics?.requestDuration.record(args.durationMs, {
447
+ method: args.method,
448
+ route: args.route,
449
+ status_class: `${Math.floor(args.statusCode / 100)}xx`
450
+ });
451
+ }
452
+ async function renderPrometheusMetrics(exporter) {
453
+ let statusCode = 200;
454
+ const headers = {};
455
+ let body = "";
456
+ await new Promise((resolve) => {
457
+ const response = {
458
+ statusCode,
459
+ setHeader(name, value) {
460
+ headers[name.toLowerCase()] = value;
461
+ },
462
+ end(chunk) {
463
+ if (chunk) body += chunk;
464
+ statusCode = this.statusCode;
465
+ resolve();
466
+ }
467
+ };
468
+ exporter.getMetricsRequestHandler({}, response);
469
+ });
470
+ return { body, headers, statusCode };
471
+ }
472
+ function normalizeHeaderNames(headers) {
473
+ return headers.map((value) => value.toLowerCase());
474
+ }
475
+ function uniqueValues(values) {
476
+ return [...new Set(values)];
477
+ }
478
+ function clampRate(value) {
479
+ if (Number.isNaN(value)) return 0;
480
+ return Math.max(0, Math.min(1, value));
481
+ }
482
+ function deterministicSample(seed, rate) {
483
+ if (rate >= 1) return true;
484
+ if (rate <= 0) return false;
485
+ let hash = 0;
486
+ for (let index = 0; index < seed.length; index += 1) {
487
+ hash = hash * 31 + seed.charCodeAt(index) >>> 0;
488
+ }
489
+ return hash / 4294967295 <= rate;
490
+ }
491
+ function toNumber(value) {
492
+ if (!value) return void 0;
493
+ const parsed = Number(value);
494
+ return Number.isFinite(parsed) ? parsed : void 0;
495
+ }
496
+
497
+ // src/workflows.ts
498
+ var WORKFLOW_HISTORY_COLLECTION = "__workflow_history";
499
+ var LIFECYCLE_EVENTS_COLLECTION = "__lifecycle_events";
500
+ var EDITOR_CAPABILITIES = ["entry.edit", "entry.submit"];
501
+ var PUBLISHER_CAPABILITIES = ["entry.edit", "entry.submit", "entry.publish", "entry.unpublish"];
502
+ function definePublishingWorkflow(options = {}) {
503
+ const editors = options.editors ?? ["editor"];
504
+ const publishers = options.publishers ?? ["publisher", "admin"];
505
+ return {
506
+ initialState: "draft",
507
+ draftState: "draft",
508
+ states: [
509
+ { name: "draft", label: "Draft", color: "neutral" },
510
+ { name: "in_review", label: "In review", color: "warning" },
511
+ { name: "published", label: "Published", color: "success", published: true }
512
+ ],
513
+ transitions: [
514
+ { name: "submit", label: "Submit for review", from: "draft", to: "in_review", requiredCapabilities: ["entry.submit"] },
515
+ { name: "publish", label: "Publish", from: "in_review", to: "published", requiredCapabilities: ["entry.publish"] },
516
+ { name: "reject", label: "Request changes", from: "in_review", to: "draft", requiredCapabilities: ["entry.publish"], requireComment: true },
517
+ { name: "unpublish", label: "Unpublish", from: "published", to: "draft", requiredCapabilities: ["entry.unpublish"], unpublish: true }
518
+ ],
519
+ roles: [
520
+ ...editors.map((role) => ({ role, capabilities: [...EDITOR_CAPABILITIES] })),
521
+ ...publishers.map((role) => ({ role, capabilities: [...PUBLISHER_CAPABILITIES] }))
522
+ ]
523
+ };
524
+ }
525
+ function publishingWorkflow() {
526
+ return definePublishingWorkflow();
527
+ }
528
+ function simplePublishingWorkflow() {
529
+ return {
530
+ initialState: "draft",
531
+ draftState: "draft",
532
+ states: [
533
+ { name: "draft", label: "Draft", color: "neutral" },
534
+ { name: "published", label: "Published", color: "success", published: true }
535
+ ],
536
+ transitions: [
537
+ { name: "publish", label: "Publish", from: "draft", to: "published" },
538
+ { name: "unpublish", label: "Unpublish", from: "published", to: "draft", unpublish: true }
539
+ ]
540
+ // Intentionally no `roles`: this lightweight workflow (synthesized from
541
+ // `drafts: true`) does no capability-based gating. Draft visibility for a
542
+ // no-roles workflow is handled in `canViewWorkflowDraft`.
543
+ };
544
+ }
545
+ function publicMetadata(meta) {
546
+ const { availableTransitions: _availableTransitions, ...safe } = meta;
547
+ return safe;
548
+ }
549
+ function workflowCapabilities(workflow, user) {
550
+ const capabilities = new Set(Array.isArray(user?.capabilities) ? user.capabilities : []);
551
+ const roles = Array.isArray(user?.roles) ? user.roles : [];
552
+ for (const mapping of workflow.roles ?? []) {
553
+ if (roles.includes(mapping.role)) mapping.capabilities.forEach((capability) => capabilities.add(capability));
554
+ }
555
+ return capabilities;
556
+ }
557
+ function canViewWorkflowDraft(workflow, user) {
558
+ if (!user) return false;
559
+ const capabilities = workflowCapabilities(workflow, user);
560
+ if (capabilities.has("entry.edit")) return true;
561
+ if (workflow.transitions.some(
562
+ (transition) => (transition.requiredCapabilities ?? []).some((capability) => capabilities.has(capability))
563
+ )) {
564
+ return true;
565
+ }
566
+ if (!workflow.roles || workflow.roles.length === 0) return true;
567
+ return false;
568
+ }
569
+ function availableWorkflowTransitions(workflow, state, user) {
570
+ const capabilities = workflowCapabilities(workflow, user);
571
+ return workflow.transitions.filter((transition) => {
572
+ const from = Array.isArray(transition.from) ? transition.from : [transition.from];
573
+ return from.includes(state) && (transition.requiredCapabilities ?? []).every((item) => capabilities.has(item));
574
+ });
575
+ }
576
+ function initializeWorkflowDocument(data, workflow) {
577
+ return {
578
+ ...data,
579
+ __workflow: { state: workflow.initialState, revision: 1 }
580
+ };
581
+ }
582
+ function publishedStateName(workflow) {
583
+ return workflow.states.find((state) => state.published)?.name ?? workflow.states[workflow.states.length - 1]?.name ?? workflow.initialState;
584
+ }
585
+ function materializeWorkflowDocument(doc, workflow, user) {
586
+ const meta = doc.__workflow;
587
+ const publishedState = publishedStateName(workflow);
588
+ if (!meta) {
589
+ const { __published: _legacyPublished, __workflow: _legacyWorkflow, ...working2 } = doc;
590
+ const state = publishedStateName(workflow);
591
+ return {
592
+ ...working2,
593
+ _workflow: {
594
+ state,
595
+ revision: 1,
596
+ availableTransitions: availableWorkflowTransitions(workflow, state, user).map((item) => item.name)
597
+ }
598
+ };
599
+ }
600
+ const { __published, __workflow, ...working } = doc;
601
+ if (!canViewWorkflowDraft(workflow, user)) {
602
+ if (!__published || typeof __published !== "object") {
603
+ if (meta.state === publishedState) {
604
+ return { ...working, _workflow: publicMetadata(meta) };
605
+ }
606
+ return null;
607
+ }
608
+ return { id: doc.id, ...__published, _workflow: publicMetadata(meta) };
609
+ }
610
+ return {
611
+ ...working,
612
+ _workflow: {
613
+ ...meta,
614
+ availableTransitions: availableWorkflowTransitions(workflow, meta.state, user).map((item) => item.name)
615
+ }
616
+ };
617
+ }
618
+ function eventId() {
619
+ return globalThis.crypto?.randomUUID?.() ?? `evt_${Date.now()}_${Math.random().toString(36).slice(2)}`;
620
+ }
621
+ function createLifecycleEvent(args) {
622
+ return {
623
+ id: eventId(),
624
+ name: args.name,
625
+ collection: args.collection,
626
+ documentId: args.documentId,
627
+ occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
628
+ actorId: args.actorId,
629
+ payload: args.payload,
630
+ attempts: 0,
631
+ status: "pending"
632
+ };
633
+ }
634
+ async function persistEvent(db, event) {
635
+ await db.create({ collection: LIFECYCLE_EVENTS_COLLECTION, data: event });
636
+ }
637
+ async function dispatchLifecycleEvent(config, event) {
638
+ const db = config.db;
639
+ if (!db || !config.events?.handlers.length) return;
640
+ const maxAttempts = config.events.maxAttempts ?? 8;
641
+ const retryDelayMs = config.events.retryDelayMs ?? 1e3;
642
+ const attempts = event.attempts + 1;
643
+ try {
644
+ await db.update({ collection: LIFECYCLE_EVENTS_COLLECTION, id: event.id, data: { status: "processing", attempts } });
645
+ for (const handler of config.events.handlers) await handler({ ...event, status: "processing", attempts });
646
+ await db.update({
647
+ collection: LIFECYCLE_EVENTS_COLLECTION,
648
+ id: event.id,
649
+ data: { status: "delivered", attempts, deliveredAt: (/* @__PURE__ */ new Date()).toISOString(), lastError: null }
650
+ });
651
+ } catch (error) {
652
+ const exhausted = attempts >= maxAttempts;
653
+ await db.update({
654
+ collection: LIFECYCLE_EVENTS_COLLECTION,
655
+ id: event.id,
656
+ data: {
657
+ status: "failed",
658
+ attempts,
659
+ lastError: error instanceof Error ? error.message : String(error),
660
+ nextAttemptAt: exhausted ? null : new Date(Date.now() + retryDelayMs * 2 ** (attempts - 1)).toISOString()
661
+ }
662
+ });
663
+ }
664
+ }
665
+ async function dispatchPendingLifecycleEvents(config, limit = 50) {
666
+ if (!config.db || !config.events?.handlers.length) return 0;
667
+ const maxAttempts = config.events.maxAttempts ?? 8;
668
+ const result = await config.db.find({
669
+ collection: LIFECYCLE_EVENTS_COLLECTION,
670
+ where: { status: { in: ["pending", "failed"] } },
671
+ sort: "occurredAt",
672
+ limit
673
+ });
674
+ const now2 = Date.now();
675
+ const due = result.docs.filter(
676
+ (doc) => Number(doc.attempts ?? 0) < maxAttempts && (!doc.nextAttemptAt || new Date(doc.nextAttemptAt).getTime() <= now2)
677
+ );
678
+ for (const event of due) await dispatchLifecycleEvent(config, event);
679
+ return due.length;
680
+ }
681
+ async function saveWorkflowDraft(args) {
682
+ const { config, collection, id, originalDoc, data, user } = args;
683
+ const db = config.db;
684
+ const workflow = collection.workflow;
685
+ if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
686
+ const previous = originalDoc.__workflow;
687
+ const isLegacyPublishedDoc = !previous;
688
+ const baselineRevision = previous?.revision ?? 1;
689
+ const event = createLifecycleEvent({
690
+ name: "revision.created",
691
+ collection: collection.slug,
692
+ documentId: id,
693
+ actorId: user?.sub,
694
+ payload: {
695
+ revision: baselineRevision + 1,
696
+ previousRevision: isLegacyPublishedDoc ? baselineRevision : previous?.revision ?? null
697
+ }
698
+ });
699
+ const doc = await db.transaction(async (tx) => {
700
+ const nextMeta = {
701
+ ...previous ?? {},
702
+ state: isLegacyPublishedDoc ? workflow.draftState ?? workflow.initialState : originalDoc.__published ? workflow.draftState ?? workflow.initialState : previous.state,
703
+ revision: baselineRevision + 1,
704
+ ...isLegacyPublishedDoc ? { publishedRevision: baselineRevision } : {}
705
+ };
706
+ const updateData = {
707
+ ...data,
708
+ __workflow: nextMeta
709
+ };
710
+ if (isLegacyPublishedDoc) {
711
+ const { __workflow: _legacyWorkflow, __published: _legacyPublished, ...publishedSnapshot } = originalDoc;
712
+ updateData.__published = publishedSnapshot;
713
+ }
714
+ const updated = await tx.update({ collection: collection.slug, id, data: updateData });
715
+ await persistEvent(tx, event);
716
+ return updated;
717
+ });
718
+ void dispatchLifecycleEvent(config, event);
719
+ return { doc, event };
720
+ }
721
+ async function createWorkflowDocument(args) {
722
+ const { config, collection, data, user } = args;
723
+ const db = config.db;
724
+ if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
725
+ let event;
726
+ const doc = await db.transaction(async (tx) => {
727
+ const created = await tx.create({ collection: collection.slug, data });
728
+ event = createLifecycleEvent({
729
+ name: "revision.created",
730
+ collection: collection.slug,
731
+ documentId: created.id,
732
+ actorId: user?.sub,
733
+ payload: { revision: 1, previousRevision: null }
734
+ });
735
+ await persistEvent(tx, event);
736
+ return created;
737
+ });
738
+ void dispatchLifecycleEvent(config, event);
739
+ return { doc, event };
740
+ }
741
+ async function transitionWorkflow(args) {
742
+ const { config, collection, id, transitionName, expectedRevision, comment, user, req } = args;
743
+ const db = config.db;
744
+ const workflow = collection.workflow;
745
+ if (!db.transaction) throw new Error(`The configured database adapter does not support workflow transactions.`);
746
+ const original = await db.findOne({ collection: collection.slug, id });
747
+ if (!original) throw Object.assign(new Error("Not Found"), { statusCode: 404 });
748
+ const meta = original.__workflow;
749
+ if (!meta) throw Object.assign(new Error("Entry has no workflow metadata"), { statusCode: 409 });
750
+ if (expectedRevision !== void 0 && expectedRevision !== meta.revision) {
751
+ throw Object.assign(new Error("This entry changed since it was loaded. Refresh before transitioning it."), { statusCode: 409 });
752
+ }
753
+ const transition = workflow.transitions.find((item) => item.name === transitionName);
754
+ const fromStates = transition ? Array.isArray(transition.from) ? transition.from : [transition.from] : [];
755
+ if (!transition || !fromStates.includes(meta.state)) {
756
+ throw Object.assign(new Error(`Transition "${transitionName}" is not valid from "${meta.state}".`), { statusCode: 409 });
757
+ }
758
+ if (!availableWorkflowTransitions(workflow, meta.state, user).some((item) => item.name === transition.name)) {
759
+ throw Object.assign(new Error(`You do not have permission to perform "${transition.label}".`), { statusCode: 403 });
760
+ }
761
+ if (transition.requireComment && !comment?.trim()) {
762
+ throw Object.assign(new Error(`A comment is required for "${transition.label}".`), { statusCode: 400 });
763
+ }
764
+ const hookContext = { transition, from: meta.state, to: transition.to, doc: original, user, comment, req, db };
765
+ for (const hook of workflow.hooks?.beforeTransition ?? []) await hook(hookContext);
766
+ const events = [createLifecycleEvent({
767
+ name: "workflow.transitioned",
768
+ collection: collection.slug,
769
+ documentId: id,
770
+ actorId: user?.sub,
771
+ payload: { transition: transition.name, from: meta.state, to: transition.to, revision: meta.revision, comment }
772
+ })];
773
+ const targetState = workflow.states.find((state) => state.name === transition.to);
774
+ if (targetState.published) {
775
+ events.push(createLifecycleEvent({ name: "entry.published", collection: collection.slug, documentId: id, actorId: user?.sub, payload: { revision: meta.revision } }));
776
+ } else if (transition.unpublish) {
777
+ events.push(createLifecycleEvent({ name: "entry.unpublished", collection: collection.slug, documentId: id, actorId: user?.sub, payload: { revision: meta.publishedRevision } }));
778
+ }
779
+ const updated = await db.transaction(async (tx) => {
780
+ const locked = await tx.findOne({ collection: collection.slug, id });
781
+ if (!locked) throw Object.assign(new Error("Not Found"), { statusCode: 404 });
782
+ const lockedMeta = locked.__workflow;
783
+ if (lockedMeta.revision !== meta.revision || lockedMeta.state !== meta.state || expectedRevision !== void 0 && lockedMeta.revision !== expectedRevision) {
784
+ throw Object.assign(new Error("This entry changed since it was loaded. Refresh before transitioning it."), { statusCode: 409 });
785
+ }
786
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
787
+ const { __published: _published, __workflow: _workflow, id: _id, ...working } = locked;
788
+ const nextMeta = {
789
+ ...lockedMeta,
790
+ state: transition.to,
791
+ ...targetState.published ? { publishedRevision: lockedMeta.revision, publishedAt: now2, publishedBy: user?.sub } : {},
792
+ ...transition.unpublish ? { publishedRevision: void 0, publishedAt: void 0, publishedBy: void 0 } : {}
793
+ };
794
+ const data = { __workflow: nextMeta };
795
+ if (targetState.published) data.__published = working;
796
+ if (transition.unpublish) data.__published = null;
797
+ const next = await tx.update({ collection: collection.slug, id, data });
798
+ await tx.create({
799
+ collection: WORKFLOW_HISTORY_COLLECTION,
800
+ data: { collection: collection.slug, documentId: id, transition: transition.name, from: lockedMeta.state, to: transition.to, revision: lockedMeta.revision, comment: comment ?? null, actorId: user?.sub ?? null, createdAt: now2 }
801
+ });
802
+ for (const event of events) await persistEvent(tx, event);
803
+ if (collection.audit) {
804
+ await tx.create({ collection: "__audit", data: { collection: collection.slug, documentId: id, operation: "workflow.transition", user: user?.sub ?? null, timestamp: now2, changes: JSON.stringify({ transition: transition.name, from: lockedMeta.state, to: transition.to, revision: lockedMeta.revision }) } });
805
+ }
806
+ return next;
807
+ });
808
+ for (const event of events) void dispatchLifecycleEvent(config, event);
809
+ for (const hook of workflow.hooks?.afterTransition ?? []) {
810
+ try {
811
+ await hook({ ...hookContext, doc: updated, event: events[0] });
812
+ } catch (error) {
813
+ getObservabilityRuntime(config)?.recordWorkflowHookFailure({
814
+ collection: collection.slug,
815
+ transition: transition.name
816
+ });
817
+ getConfigLogger(config, "workflow").error({
818
+ err: error,
819
+ msg: "afterTransition hook failed",
820
+ collection: collection.slug,
821
+ transition: transition.name,
822
+ documentId: id
823
+ });
824
+ }
825
+ }
826
+ return updated;
827
+ }
828
+
829
+ // src/utils/admin-auth.ts
830
+ function getAdminAuthCollection(config) {
831
+ const adminCollection = resolveAdminAuthCollection(config.collections, config.adminAuth?.collectionSlug);
832
+ return adminCollection ?? null;
833
+ }
834
+ function resolveAdminAuthCollection(collections, collectionSlug) {
835
+ const adminsCollection = collections.find((collection) => collection.slug === "__admins");
836
+ if (adminsCollection) return adminsCollection;
837
+ if (collectionSlug) {
838
+ const requestedCollection = collections.find((collection) => collection.slug === collectionSlug);
839
+ if (requestedCollection) return requestedCollection;
840
+ }
841
+ return collections.find((collection) => collection.auth);
842
+ }
843
+ function getPublicAdminAuthConfig(adminAuth, collections) {
844
+ const providers = (adminAuth?.providers ?? []).map((provider) => ({
845
+ id: provider.id,
846
+ type: provider.type,
847
+ displayName: provider.displayName || humanizeProviderName(provider.id, provider.type),
848
+ autoRedirect: provider.autoRedirect
849
+ }));
850
+ const resolvedCollectionSlug = collections ? resolveAdminAuthCollection(collections, adminAuth?.collectionSlug)?.slug : adminAuth?.collectionSlug;
851
+ return {
852
+ mode: adminAuth?.mode ?? "local",
853
+ collectionSlug: resolvedCollectionSlug,
854
+ provisioningMode: adminAuth?.provisioningMode,
855
+ providers
856
+ };
857
+ }
858
+ function humanizeProviderName(id, type) {
859
+ const cleaned = id.replace(/[-_]+/g, " ").trim();
860
+ if (!cleaned) return type.toUpperCase();
861
+ return cleaned.replace(/\b\w/g, (char) => char.toUpperCase());
862
+ }
863
+
864
+ // src/utils/jexl-helpers.ts
865
+ import jexl from "jexl";
866
+ function slugify(val) {
867
+ if (val === void 0 || val === null) return "";
868
+ return String(val).normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim().replace(/[^a-z0-9\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
869
+ }
870
+ function lower(val) {
871
+ if (val === void 0 || val === null) return "";
872
+ return String(val).toLowerCase();
873
+ }
874
+ function upper(val) {
875
+ if (val === void 0 || val === null) return "";
876
+ return String(val).toUpperCase();
877
+ }
878
+ function trim(val) {
879
+ if (val === void 0 || val === null) return "";
880
+ return String(val).trim();
881
+ }
882
+ function capitalize(val) {
883
+ if (val === void 0 || val === null) return "";
884
+ const str = String(val).trim();
885
+ if (!str) return "";
886
+ return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
887
+ }
888
+ function truncate(val, length2, ellipsis = "...") {
889
+ if (val === void 0 || val === null) return "";
890
+ const str = String(val);
891
+ const maxLen = typeof length2 === "number" && length2 > 0 ? length2 : 100;
892
+ if (str.length <= maxLen) return str;
893
+ return str.slice(0, maxLen).trim() + String(ellipsis ?? "...");
894
+ }
895
+ function readingTime(val, wpm = 200) {
896
+ if (val === void 0 || val === null) return 1;
897
+ const str = String(val).trim();
898
+ if (!str) return 1;
899
+ const words = str.split(/\s+/).filter(Boolean).length;
900
+ return Math.max(1, Math.ceil(words / (typeof wpm === "number" && wpm > 0 ? wpm : 200)));
901
+ }
902
+ function wordCount(val) {
903
+ if (val === void 0 || val === null) return 0;
904
+ const str = String(val).trim();
905
+ if (!str) return 0;
906
+ return str.split(/\s+/).filter(Boolean).length;
907
+ }
908
+ function replace(val, search, replacement) {
909
+ if (val === void 0 || val === null) return "";
910
+ return String(val).replace(new RegExp(String(search || ""), "g"), String(replacement ?? ""));
911
+ }
912
+ function startsWith(str, prefix) {
913
+ if (str === void 0 || str === null) return false;
914
+ return String(str).startsWith(String(prefix ?? ""));
915
+ }
916
+ function endsWith(str, suffix) {
917
+ if (str === void 0 || str === null) return false;
918
+ return String(str).endsWith(String(suffix ?? ""));
919
+ }
920
+ function now() {
921
+ return (/* @__PURE__ */ new Date()).toISOString();
922
+ }
923
+ function today() {
924
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
925
+ }
926
+ function formatDate(val, style = "short") {
927
+ if (!val) return "";
928
+ const d = new Date(val);
929
+ if (Number.isNaN(d.getTime())) return "";
930
+ const styleStr = String(style).toLowerCase();
931
+ if (styleStr === "iso" || styleStr === "date") return d.toISOString().slice(0, 10);
932
+ if (styleStr === "datetime" || styleStr === "full") return d.toISOString();
933
+ return d.toLocaleDateString("en-US", {
934
+ year: "numeric",
935
+ month: "short",
936
+ day: "numeric"
937
+ });
938
+ }
939
+ function addDays(val, days) {
940
+ const d = val ? new Date(val) : /* @__PURE__ */ new Date();
941
+ if (Number.isNaN(d.getTime())) return "";
942
+ const daysNum = typeof days === "number" ? days : Number(days) || 0;
943
+ d.setDate(d.getDate() + daysNum);
944
+ return d.toISOString();
945
+ }
946
+ function diffDays(dateA, dateB) {
947
+ const dA = dateA ? new Date(dateA) : /* @__PURE__ */ new Date();
948
+ const dB = dateB ? new Date(dateB) : /* @__PURE__ */ new Date();
949
+ if (Number.isNaN(dA.getTime()) || Number.isNaN(dB.getTime())) return 0;
950
+ const diffMs = Math.abs(dA.getTime() - dB.getTime());
951
+ return Math.floor(diffMs / (1e3 * 60 * 60 * 24));
952
+ }
953
+ function isPast(val) {
954
+ if (!val) return false;
955
+ const d = new Date(val);
956
+ if (Number.isNaN(d.getTime())) return false;
957
+ return d.getTime() < Date.now();
958
+ }
959
+ function isFuture(val) {
960
+ if (!val) return false;
961
+ const d = new Date(val);
962
+ if (Number.isNaN(d.getTime())) return false;
963
+ return d.getTime() > Date.now();
964
+ }
965
+ function includes(arrOrStr, item) {
966
+ if (Array.isArray(arrOrStr)) {
967
+ return arrOrStr.includes(item);
968
+ }
969
+ if (typeof arrOrStr === "string") {
970
+ return arrOrStr.includes(String(item ?? ""));
971
+ }
972
+ return false;
973
+ }
974
+ function join(arr, separator = ", ") {
975
+ if (!Array.isArray(arr)) return "";
976
+ return arr.filter((item) => item !== void 0 && item !== null).join(String(separator));
977
+ }
978
+ function first(arr) {
979
+ if (Array.isArray(arr)) return arr[0] ?? null;
980
+ return null;
981
+ }
982
+ function last(arr) {
983
+ if (Array.isArray(arr)) return arr[arr.length - 1] ?? null;
984
+ return null;
985
+ }
986
+ function compact(arr) {
987
+ if (!Array.isArray(arr)) return [];
988
+ return arr.filter((item) => item !== void 0 && item !== null && item !== "");
989
+ }
990
+ function unique(arr) {
991
+ if (!Array.isArray(arr)) return [];
992
+ return Array.from(new Set(arr));
993
+ }
994
+ function length(val) {
995
+ if (Array.isArray(val) || typeof val === "string") return val.length;
996
+ if (val && typeof val === "object") return Object.keys(val).length;
997
+ return 0;
998
+ }
999
+ function round(val, decimals = 0) {
1000
+ const num = Number(val);
1001
+ if (Number.isNaN(num)) return 0;
1002
+ const dec = typeof decimals === "number" ? decimals : Number(decimals) || 0;
1003
+ const factor = Math.pow(10, dec);
1004
+ return Math.round(num * factor) / factor;
1005
+ }
1006
+ function clamp(val, minVal, maxVal) {
1007
+ const num = Number(val) || 0;
1008
+ const min = Number(minVal) || 0;
1009
+ const max = Number(maxVal) || 0;
1010
+ return Math.min(Math.max(num, min), max);
1011
+ }
1012
+ function defaultValue(val, fallback) {
1013
+ if (val === void 0 || val === null || val === "") return fallback;
1014
+ return val;
1015
+ }
1016
+ function coalesce(...args) {
1017
+ for (const arg of args) {
1018
+ if (arg !== void 0 && arg !== null && arg !== "") return arg;
1019
+ }
1020
+ return null;
1021
+ }
1022
+ function isEmpty(val) {
1023
+ if (val === void 0 || val === null || val === "") return true;
1024
+ if (Array.isArray(val)) return val.length === 0;
1025
+ if (typeof val === "object") return Object.keys(val).length === 0;
1026
+ return false;
1027
+ }
1028
+ function get(obj, path, fallback = null) {
1029
+ if (!obj || typeof obj !== "object") return fallback;
1030
+ const pathStr = String(path || "").trim();
1031
+ if (!pathStr) return fallback;
1032
+ const parts = pathStr.split(".");
1033
+ let curr = obj;
1034
+ for (const part of parts) {
1035
+ if (curr === void 0 || curr === null) return fallback;
1036
+ curr = curr[part];
1037
+ }
1038
+ return curr === void 0 || curr === null ? fallback : curr;
1039
+ }
1040
+ function registerJexlHelpers(jexlInstance = jexl) {
1041
+ const helpers = {
1042
+ // Strings
1043
+ slugify,
1044
+ lower,
1045
+ upper,
1046
+ trim,
1047
+ capitalize,
1048
+ truncate,
1049
+ readingTime,
1050
+ wordCount,
1051
+ replace,
1052
+ startsWith,
1053
+ endsWith,
1054
+ // Dates
1055
+ now,
1056
+ today,
1057
+ formatDate,
1058
+ addDays,
1059
+ diffDays,
1060
+ isPast,
1061
+ isFuture,
1062
+ // Arrays
1063
+ includes,
1064
+ join,
1065
+ first,
1066
+ last,
1067
+ compact,
1068
+ unique,
1069
+ length,
1070
+ // Math
1071
+ round,
1072
+ clamp,
1073
+ // Objects & Logical
1074
+ default: defaultValue,
1075
+ coalesce,
1076
+ isEmpty,
1077
+ get
1078
+ };
1079
+ for (const [name, fn] of Object.entries(helpers)) {
1080
+ try {
1081
+ jexlInstance.addFunction(name, fn);
1082
+ } catch {
1083
+ }
1084
+ }
1085
+ }
1086
+ registerJexlHelpers(jexl);
1087
+ var BUILTIN_JEXL_HELPERS = [
1088
+ // Strings
1089
+ "slugify",
1090
+ "lower",
1091
+ "upper",
1092
+ "trim",
1093
+ "capitalize",
1094
+ "truncate",
1095
+ "readingTime",
1096
+ "wordCount",
1097
+ "replace",
1098
+ "startsWith",
1099
+ "endsWith",
1100
+ // Dates
1101
+ "now",
1102
+ "today",
1103
+ "formatDate",
1104
+ "addDays",
1105
+ "diffDays",
1106
+ "isPast",
1107
+ "isFuture",
1108
+ // Arrays
1109
+ "includes",
1110
+ "join",
1111
+ "first",
1112
+ "last",
1113
+ "compact",
1114
+ "unique",
1115
+ "length",
1116
+ // Math
1117
+ "round",
1118
+ "clamp",
1119
+ // Objects & Logical
1120
+ "default",
1121
+ "coalesce",
1122
+ "isEmpty",
1123
+ "get"
1124
+ ];
1125
+
1126
+ // src/utils/declarative-hooks.ts
1127
+ import jexl2 from "jexl";
1128
+ registerJexlHelpers(jexl2);
1129
+ var SURFACE_ROOTS = {
1130
+ "collection.beforeRead": ["req", "user", "query", ...BUILTIN_JEXL_HELPERS],
1131
+ "collection.afterRead": ["req", "user", "doc", ...BUILTIN_JEXL_HELPERS],
1132
+ "collection.beforeChange": ["req", "user", "data", "doc", "operation", ...BUILTIN_JEXL_HELPERS],
1133
+ "global.beforeRead": ["req", "user", "query", ...BUILTIN_JEXL_HELPERS],
1134
+ "global.afterRead": ["req", "user", "doc", ...BUILTIN_JEXL_HELPERS],
1135
+ "global.beforeChange": ["req", "user", "data", "doc", "operation", ...BUILTIN_JEXL_HELPERS],
1136
+ "field.beforeChange": ["value", "data", "originalDoc", "user", ...BUILTIN_JEXL_HELPERS],
1137
+ "field.admin.onChange": ["value", "siblingData", "data", ...BUILTIN_JEXL_HELPERS]
1138
+ };
1139
+ var ACCESS_ROOTS = ["user", "req", "doc", "data", "id", "config", ...BUILTIN_JEXL_HELPERS];
1140
+ var ADMIN_CONDITION_RESERVED_ROOTS = ["data", "siblingData", "user", "id", ...BUILTIN_JEXL_HELPERS];
1141
+ var PREVIEW_URL_RESERVED_ROOTS = ["siteUrl", "id", ...BUILTIN_JEXL_HELPERS];
1142
+ var COMPILE_CACHE = /* @__PURE__ */ new Map();
1143
+ function compileExpression(expression) {
1144
+ const cached = COMPILE_CACHE.get(expression);
1145
+ if (cached) return cached;
1146
+ const compiled = jexl2.compile(expression);
1147
+ const next = { ast: compiled._ast };
1148
+ COMPILE_CACHE.set(expression, next);
1149
+ return next;
1150
+ }
1151
+ function isPlainObject(value) {
1152
+ return !!value && typeof value === "object" && !Array.isArray(value);
1153
+ }
1154
+ function quoteSegment(value) {
1155
+ return `["${value.replace(/"/g, '\\"')}"]`;
1156
+ }
1157
+ function fieldSegment(field, index) {
1158
+ return typeof field.name === "string" && field.name.length > 0 ? `fields${quoteSegment(field.name)}` : `fields[${index}]`;
1159
+ }
1160
+ function blockSegment(block, index) {
1161
+ return typeof block.slug === "string" && block.slug.length > 0 ? `blocks${quoteSegment(block.slug)}` : `blocks[${index}]`;
1162
+ }
1163
+ function collectionSegment(collection, index) {
1164
+ return typeof collection.slug === "string" && collection.slug.length > 0 ? `collections${quoteSegment(collection.slug)}` : `collections[${index}]`;
1165
+ }
1166
+ function globalSegment(global, index) {
1167
+ return typeof global.slug === "string" && global.slug.length > 0 ? `globals${quoteSegment(global.slug)}` : `globals[${index}]`;
1168
+ }
1169
+ function colorize(value, code, enabled) {
1170
+ return enabled ? `\x1B[${code}m${value}\x1B[0m` : value;
1171
+ }
1172
+ function collectRootIdentifiers(node, roots, seen) {
1173
+ if (!node || typeof node !== "object" || seen.has(node)) return;
1174
+ seen.add(node);
1175
+ const candidate = node;
1176
+ if (candidate.type === "Identifier") {
1177
+ if (candidate.from) {
1178
+ collectRootIdentifiers(candidate.from, roots, seen);
1179
+ return;
1180
+ }
1181
+ if (typeof candidate.value === "string" && candidate.value !== "null") {
1182
+ roots.add(candidate.value);
1183
+ }
1184
+ return;
1185
+ }
1186
+ if (Array.isArray(node)) {
1187
+ for (const entry of node) collectRootIdentifiers(entry, roots, seen);
1188
+ return;
1189
+ }
1190
+ for (const value of Object.values(node)) {
1191
+ if (Array.isArray(value)) {
1192
+ for (const entry of value) collectRootIdentifiers(entry, roots, seen);
1193
+ continue;
1194
+ }
1195
+ if (value && typeof value === "object") {
1196
+ collectRootIdentifiers(value, roots, seen);
1197
+ }
1198
+ }
1199
+ }
1200
+ function getInvalidRoots(expression, allowedRoots) {
1201
+ const { ast } = compileExpression(expression);
1202
+ const roots = /* @__PURE__ */ new Set();
1203
+ collectRootIdentifiers(ast, roots, /* @__PURE__ */ new Set());
1204
+ const allowed = new Set(allowedRoots);
1205
+ return [...roots].filter((root) => !allowed.has(root));
1206
+ }
1207
+ function validateDeclarativeHookExpression(expression, surface, path) {
1208
+ try {
1209
+ const invalidRoots = getInvalidRoots(expression, SURFACE_ROOTS[surface]);
1210
+ if (invalidRoots.length === 0) return [];
1211
+ return [
1212
+ {
1213
+ path,
1214
+ surface,
1215
+ expression,
1216
+ message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${SURFACE_ROOTS[surface].map((root) => `"${root}"`).join(", ")}`
1217
+ }
1218
+ ];
1219
+ } catch (error) {
1220
+ return [
1221
+ {
1222
+ path,
1223
+ surface,
1224
+ expression,
1225
+ message: `has invalid syntax: ${error.message}`
1226
+ }
1227
+ ];
1228
+ }
1229
+ }
1230
+ function validateDeclarativeAccessExpression(expression, surface, path) {
1231
+ try {
1232
+ const invalidRoots = getInvalidRoots(expression, ACCESS_ROOTS);
1233
+ if (invalidRoots.length === 0) return [];
1234
+ return [
1235
+ {
1236
+ path,
1237
+ surface,
1238
+ expression,
1239
+ message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${ACCESS_ROOTS.map((root) => `"${root}"`).join(", ")}`
1240
+ }
1241
+ ];
1242
+ } catch (error) {
1243
+ return [
1244
+ {
1245
+ path,
1246
+ surface,
1247
+ expression,
1248
+ message: `has invalid syntax: ${error.message}`
1249
+ }
1250
+ ];
1251
+ }
1252
+ }
1253
+ function validateAdminConditionExpression(expression, path, allowedRoots) {
1254
+ try {
1255
+ const invalidRoots = getInvalidRoots(expression, allowedRoots);
1256
+ if (invalidRoots.length === 0) return [];
1257
+ return [
1258
+ {
1259
+ path,
1260
+ surface: "field.admin.condition",
1261
+ expression,
1262
+ message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${allowedRoots.map((root) => `"${root}"`).join(", ")}`
1263
+ }
1264
+ ];
1265
+ } catch (error) {
1266
+ return [
1267
+ {
1268
+ path,
1269
+ surface: "field.admin.condition",
1270
+ expression,
1271
+ message: `has invalid syntax: ${error.message}`
1272
+ }
1273
+ ];
1274
+ }
1275
+ }
1276
+ function validatePreviewUrlExpression(expression, path, allowedRoots) {
1277
+ try {
1278
+ const invalidRoots = getInvalidRoots(expression, allowedRoots);
1279
+ if (invalidRoots.length === 0) return [];
1280
+ return [
1281
+ {
1282
+ path,
1283
+ surface: "collection.admin.previewUrl",
1284
+ expression,
1285
+ message: `uses unsupported context ${invalidRoots.map((root) => `"${root}"`).join(", ")}. Allowed context: ${allowedRoots.map((root) => `"${root}"`).join(", ")}`
1286
+ }
1287
+ ];
1288
+ } catch (error) {
1289
+ return [
1290
+ {
1291
+ path,
1292
+ surface: "collection.admin.previewUrl",
1293
+ expression,
1294
+ message: `has invalid syntax: ${error.message}`
1295
+ }
1296
+ ];
1297
+ }
1298
+ }
1299
+ function assertValidDeclarativeHookExpression(expression, surface, path) {
1300
+ const issues = validateDeclarativeHookExpression(expression, surface, path);
1301
+ if (issues.length === 0) return;
1302
+ throw new Error(`Invalid declarative hook at ${path}: ${issues[0].message}`);
1303
+ }
1304
+ function assertValidDeclarativeHookResult(result, surface, path) {
1305
+ if (isPlainObject(result)) return;
1306
+ throw new Error(`Invalid declarative hook result at ${path}: ${surface} expressions must return an object`);
1307
+ }
1308
+ function collectFieldIssues(fields, path, issues) {
1309
+ fields.forEach((field, index) => {
1310
+ const fieldPath = `${path}.${fieldSegment(field, index)}`;
1311
+ field.hooks?.beforeChange?.forEach((hook, hookIndex) => {
1312
+ if (typeof hook !== "string") return;
1313
+ issues.push(
1314
+ ...validateDeclarativeHookExpression(
1315
+ hook,
1316
+ "field.beforeChange",
1317
+ `${fieldPath}.hooks.beforeChange[${hookIndex}]`
1318
+ )
1319
+ );
1320
+ });
1321
+ field.hooks?.afterRead?.forEach((hook, hookIndex) => {
1322
+ if (typeof hook !== "string") return;
1323
+ issues.push({
1324
+ path: `${fieldPath}.hooks.afterRead[${hookIndex}]`,
1325
+ surface: "unsupported",
1326
+ expression: hook,
1327
+ message: "declarative strings are not supported on field hooks.afterRead"
1328
+ });
1329
+ });
1330
+ if (typeof field.admin?.hooks?.onChange === "string") {
1331
+ issues.push(
1332
+ ...validateDeclarativeHookExpression(
1333
+ field.admin.hooks.onChange,
1334
+ "field.admin.onChange",
1335
+ `${fieldPath}.admin.hooks.onChange`
1336
+ )
1337
+ );
1338
+ }
1339
+ if (typeof field.admin?.hooks?.options === "string") {
1340
+ issues.push({
1341
+ path: `${fieldPath}.admin.hooks.options`,
1342
+ surface: "unsupported",
1343
+ expression: field.admin.hooks.options,
1344
+ message: "declarative strings are not supported on field admin.hooks.options"
1345
+ });
1346
+ }
1347
+ if (Array.isArray(field.fields)) {
1348
+ collectFieldIssues(field.fields, fieldPath, issues);
1349
+ }
1350
+ if (Array.isArray(field.blocks)) {
1351
+ field.blocks.forEach((block, blockIndex) => {
1352
+ if (!Array.isArray(block.fields)) return;
1353
+ collectFieldIssues(block.fields, `${fieldPath}.${blockSegment(block, blockIndex)}`, issues);
1354
+ });
1355
+ }
1356
+ });
1357
+ }
1358
+ function collectFieldNames(fields) {
1359
+ return fields.flatMap(
1360
+ (field) => typeof field.name === "string" && field.name.length > 0 ? [field.name] : []
1361
+ );
1362
+ }
1363
+ function collectAdminConditionIssues(fields, path, rootFieldNames, issues) {
1364
+ const scopeFieldNames = collectFieldNames(fields);
1365
+ const allowedRoots = [.../* @__PURE__ */ new Set([...ADMIN_CONDITION_RESERVED_ROOTS, ...rootFieldNames, ...scopeFieldNames])];
1366
+ fields.forEach((field, index) => {
1367
+ const fieldPath = `${path}.${fieldSegment(field, index)}`;
1368
+ if (typeof field.admin?.condition === "string") {
1369
+ issues.push(
1370
+ ...validateAdminConditionExpression(
1371
+ field.admin.condition,
1372
+ `${fieldPath}.admin.condition`,
1373
+ allowedRoots
1374
+ )
1375
+ );
1376
+ }
1377
+ if (Array.isArray(field.fields)) {
1378
+ collectAdminConditionIssues(field.fields, fieldPath, rootFieldNames, issues);
1379
+ }
1380
+ if (Array.isArray(field.blocks)) {
1381
+ field.blocks.forEach((block, blockIndex) => {
1382
+ if (!Array.isArray(block.fields)) return;
1383
+ collectAdminConditionIssues(
1384
+ block.fields,
1385
+ `${fieldPath}.${blockSegment(block, blockIndex)}`,
1386
+ rootFieldNames,
1387
+ issues
1388
+ );
1389
+ });
1390
+ }
1391
+ });
1392
+ }
1393
+ function collectFieldAccessIssues(fields, path, issues) {
1394
+ fields.forEach((field, index) => {
1395
+ const fieldPath = `${path}.${fieldSegment(field, index)}`;
1396
+ if (typeof field.access?.read === "string") {
1397
+ issues.push(...validateDeclarativeAccessExpression(field.access.read, "field.access", `${fieldPath}.access.read`));
1398
+ }
1399
+ if (typeof field.access?.create === "string") {
1400
+ issues.push(
1401
+ ...validateDeclarativeAccessExpression(field.access.create, "field.access", `${fieldPath}.access.create`)
1402
+ );
1403
+ }
1404
+ if (typeof field.access?.update === "string") {
1405
+ issues.push(
1406
+ ...validateDeclarativeAccessExpression(field.access.update, "field.access", `${fieldPath}.access.update`)
1407
+ );
1408
+ }
1409
+ if (Array.isArray(field.fields)) {
1410
+ collectFieldAccessIssues(field.fields, fieldPath, issues);
1411
+ }
1412
+ if (Array.isArray(field.blocks)) {
1413
+ field.blocks.forEach((block, blockIndex) => {
1414
+ if (!Array.isArray(block.fields)) return;
1415
+ collectFieldAccessIssues(
1416
+ block.fields,
1417
+ `${fieldPath}.${blockSegment(block, blockIndex)}`,
1418
+ issues
1419
+ );
1420
+ });
1421
+ }
1422
+ });
1423
+ }
1424
+ function collectHookIssues(hooks, scope, path, issues) {
1425
+ if (!hooks) return;
1426
+ const supported = {
1427
+ beforeRead: `${scope}.beforeRead`,
1428
+ afterRead: `${scope}.afterRead`,
1429
+ beforeChange: `${scope}.beforeChange`
1430
+ };
1431
+ for (const [key, value] of Object.entries(hooks)) {
1432
+ if (!Array.isArray(value)) continue;
1433
+ value.forEach((hook, index) => {
1434
+ if (typeof hook !== "string") return;
1435
+ const surface = supported[key];
1436
+ if (!surface) {
1437
+ issues.push({
1438
+ path: `${path}.${key}[${index}]`,
1439
+ surface: "unsupported",
1440
+ expression: hook,
1441
+ message: `declarative strings are not supported on ${scope} hooks.${key}`
1442
+ });
1443
+ return;
1444
+ }
1445
+ issues.push(...validateDeclarativeHookExpression(hook, surface, `${path}.${key}[${index}]`));
1446
+ });
1447
+ }
1448
+ }
1449
+ function collectDeclarativeHookValidationIssues(config) {
1450
+ const issues = [];
1451
+ config.blocks?.forEach((block, blockIndex) => {
1452
+ if (!Array.isArray(block.fields)) return;
1453
+ collectFieldIssues(
1454
+ block.fields,
1455
+ blockSegment(block, blockIndex),
1456
+ issues
1457
+ );
1458
+ });
1459
+ config.collections.forEach((collection, collectionIndex) => {
1460
+ const collectionPath = collectionSegment(collection, collectionIndex);
1461
+ collectHookIssues(
1462
+ collection.hooks,
1463
+ "collection",
1464
+ `${collectionPath}.hooks`,
1465
+ issues
1466
+ );
1467
+ collectFieldIssues(collection.fields, collectionPath, issues);
1468
+ });
1469
+ config.globals?.forEach((global, globalIndex) => {
1470
+ const globalPath = globalSegment(global, globalIndex);
1471
+ collectHookIssues(
1472
+ global.hooks,
1473
+ "global",
1474
+ `${globalPath}.hooks`,
1475
+ issues
1476
+ );
1477
+ collectFieldIssues(global.fields, globalPath, issues);
1478
+ });
1479
+ return issues;
1480
+ }
1481
+ function collectDeclarativeAccessValidationIssues(config) {
1482
+ const issues = [];
1483
+ Object.entries(config.accessPolicies ?? {}).forEach(([name, value]) => {
1484
+ if (typeof value !== "string") return;
1485
+ issues.push(
1486
+ ...validateDeclarativeAccessExpression(value, "config.accessPolicy", `accessPolicies.${name}`)
1487
+ );
1488
+ });
1489
+ config.blocks?.forEach((block, blockIndex) => {
1490
+ if (!Array.isArray(block.fields)) return;
1491
+ collectFieldAccessIssues(
1492
+ block.fields,
1493
+ blockSegment(block, blockIndex),
1494
+ issues
1495
+ );
1496
+ });
1497
+ config.collections.forEach((collection, collectionIndex) => {
1498
+ const collectionPath = collectionSegment(collection, collectionIndex);
1499
+ if (typeof collection.access?.read === "string") {
1500
+ issues.push(
1501
+ ...validateDeclarativeAccessExpression(
1502
+ collection.access.read,
1503
+ "collection.access",
1504
+ `${collectionPath}.access.read`
1505
+ )
1506
+ );
1507
+ }
1508
+ if (typeof collection.access?.create === "string") {
1509
+ issues.push(
1510
+ ...validateDeclarativeAccessExpression(
1511
+ collection.access.create,
1512
+ "collection.access",
1513
+ `${collectionPath}.access.create`
1514
+ )
1515
+ );
1516
+ }
1517
+ if (typeof collection.access?.update === "string") {
1518
+ issues.push(
1519
+ ...validateDeclarativeAccessExpression(
1520
+ collection.access.update,
1521
+ "collection.access",
1522
+ `${collectionPath}.access.update`
1523
+ )
1524
+ );
1525
+ }
1526
+ if (typeof collection.access?.delete === "string") {
1527
+ issues.push(
1528
+ ...validateDeclarativeAccessExpression(
1529
+ collection.access.delete,
1530
+ "collection.access",
1531
+ `${collectionPath}.access.delete`
1532
+ )
1533
+ );
1534
+ }
1535
+ if (typeof collection.access?.readAudit === "string") {
1536
+ issues.push(
1537
+ ...validateDeclarativeAccessExpression(
1538
+ collection.access.readAudit,
1539
+ "collection.access",
1540
+ `${collectionPath}.access.readAudit`
1541
+ )
1542
+ );
1543
+ }
1544
+ collectFieldAccessIssues(collection.fields, collectionPath, issues);
1545
+ });
1546
+ config.globals?.forEach((global, globalIndex) => {
1547
+ const globalPath = globalSegment(global, globalIndex);
1548
+ if (typeof global.access?.read === "string") {
1549
+ issues.push(
1550
+ ...validateDeclarativeAccessExpression(global.access.read, "global.access", `${globalPath}.access.read`)
1551
+ );
1552
+ }
1553
+ if (typeof global.access?.update === "string") {
1554
+ issues.push(
1555
+ ...validateDeclarativeAccessExpression(
1556
+ global.access.update,
1557
+ "global.access",
1558
+ `${globalPath}.access.update`
1559
+ )
1560
+ );
1561
+ }
1562
+ collectFieldAccessIssues(global.fields, globalPath, issues);
1563
+ });
1564
+ return issues;
1565
+ }
1566
+ function collectAdminConditionValidationIssues(config) {
1567
+ const issues = [];
1568
+ config.blocks?.forEach((block, blockIndex) => {
1569
+ if (!Array.isArray(block.fields)) return;
1570
+ collectAdminConditionIssues(
1571
+ block.fields,
1572
+ blockSegment(block, blockIndex),
1573
+ collectFieldNames(block.fields),
1574
+ issues
1575
+ );
1576
+ });
1577
+ config.collections.forEach((collection, collectionIndex) => {
1578
+ const collectionPath = collectionSegment(collection, collectionIndex);
1579
+ const rootFieldNames = collectFieldNames(collection.fields);
1580
+ collectAdminConditionIssues(collection.fields, collectionPath, rootFieldNames, issues);
1581
+ });
1582
+ config.globals?.forEach((global, globalIndex) => {
1583
+ const globalPath = globalSegment(global, globalIndex);
1584
+ const rootFieldNames = collectFieldNames(global.fields);
1585
+ collectAdminConditionIssues(global.fields, globalPath, rootFieldNames, issues);
1586
+ });
1587
+ return issues;
1588
+ }
1589
+ function collectPreviewUrlValidationIssues(config) {
1590
+ const issues = [];
1591
+ config.collections.forEach((collection, collectionIndex) => {
1592
+ if (typeof collection.admin?.previewUrl !== "string") return;
1593
+ const collectionPath = collectionSegment(collection, collectionIndex);
1594
+ const allowedRoots = [
1595
+ .../* @__PURE__ */ new Set([...PREVIEW_URL_RESERVED_ROOTS, ...collectFieldNames(collection.fields)])
1596
+ ];
1597
+ issues.push(
1598
+ ...validatePreviewUrlExpression(
1599
+ collection.admin.previewUrl,
1600
+ `${collectionPath}.admin.previewUrl`,
1601
+ allowedRoots
1602
+ )
1603
+ );
1604
+ });
1605
+ return issues;
1606
+ }
1607
+ function assertValidAdminConditionsInConfig(config, source = "config") {
1608
+ const diagnostics = collectAdminConditionValidationIssues(config).map((issue) => ({
1609
+ severity: "error",
1610
+ source: "adminCondition",
1611
+ path: issue.path,
1612
+ surface: issue.surface,
1613
+ message: issue.message,
1614
+ expression: issue.expression
1615
+ }));
1616
+ if (diagnostics.length === 0) return;
1617
+ throw new ConfigValidationError(source, diagnostics);
1618
+ }
1619
+ function assertValidPreviewUrlsInConfig(config, source = "config") {
1620
+ const diagnostics = collectPreviewUrlValidationIssues(config).map((issue) => ({
1621
+ severity: "error",
1622
+ source: "previewUrl",
1623
+ path: issue.path,
1624
+ surface: issue.surface,
1625
+ message: issue.message,
1626
+ expression: issue.expression
1627
+ }));
1628
+ if (diagnostics.length === 0) return;
1629
+ throw new ConfigValidationError(source, diagnostics);
1630
+ }
1631
+ function collectConfigDiagnostics(config) {
1632
+ const hookIssues = collectDeclarativeHookValidationIssues(config).map((issue) => ({
1633
+ severity: "error",
1634
+ source: "declarativeHook",
1635
+ path: issue.path,
1636
+ surface: issue.surface,
1637
+ message: issue.message,
1638
+ expression: issue.expression
1639
+ }));
1640
+ const accessIssues = collectDeclarativeAccessValidationIssues(config).map((issue) => ({
1641
+ severity: "error",
1642
+ source: "declarativeAccess",
1643
+ path: issue.path,
1644
+ surface: issue.surface,
1645
+ message: issue.message,
1646
+ expression: issue.expression
1647
+ }));
1648
+ const adminConditionIssues = collectAdminConditionValidationIssues(config).map((issue) => ({
1649
+ severity: "error",
1650
+ source: "adminCondition",
1651
+ path: issue.path,
1652
+ surface: issue.surface,
1653
+ message: issue.message,
1654
+ expression: issue.expression
1655
+ }));
1656
+ const previewUrlIssues = collectPreviewUrlValidationIssues(config).map((issue) => ({
1657
+ severity: "error",
1658
+ source: "previewUrl",
1659
+ path: issue.path,
1660
+ surface: issue.surface,
1661
+ message: issue.message,
1662
+ expression: issue.expression
1663
+ }));
1664
+ return [...hookIssues, ...accessIssues, ...adminConditionIssues, ...previewUrlIssues];
1665
+ }
1666
+ function formatConfigDiagnostics(source, diagnostics, options = {}) {
1667
+ const color = options.color ?? false;
1668
+ const header = `${colorize("Config validation failed", 31, color)} in ${colorize(source, 36, color)}`;
1669
+ const docLink = `${colorize(" Learn how to write declarative rules:", 90, color)} ${colorize("https://docs.dyrected.com/docs/features/admin/form-and-field-hooks", 34, color)}`;
1670
+ const lines = diagnostics.flatMap((issue, index) => [
1671
+ `${colorize(`${index + 1}.`, 31, color)} ${colorize(issue.path, 1, color)}`,
1672
+ ` ${issue.message}`,
1673
+ ` ${colorize("surface:", 90, color)} ${issue.surface}`
1674
+ ]);
1675
+ return `${header}
1676
+ ${lines.join("\n")}
1677
+
1678
+ ${docLink}`;
1679
+ }
1680
+ var ConfigValidationError = class extends Error {
1681
+ diagnostics;
1682
+ source;
1683
+ constructor(source, diagnostics) {
1684
+ super(formatConfigDiagnostics(source, diagnostics));
1685
+ this.name = "ConfigValidationError";
1686
+ this.source = source;
1687
+ this.diagnostics = diagnostics;
1688
+ }
1689
+ };
1690
+ function isConfigValidationError(error) {
1691
+ return error instanceof ConfigValidationError;
1692
+ }
1693
+ function assertValidDeclarativeHooksInConfig(config, source = "config") {
1694
+ const diagnostics = collectDeclarativeHookValidationIssues(config).map((issue) => ({
1695
+ severity: "error",
1696
+ source: "declarativeHook",
1697
+ path: issue.path,
1698
+ surface: issue.surface,
1699
+ message: issue.message,
1700
+ expression: issue.expression
1701
+ }));
1702
+ if (diagnostics.length === 0) return;
1703
+ throw new ConfigValidationError(source, diagnostics);
1704
+ }
1705
+ function assertValidDeclarativeAccessInConfig(config, source = "config") {
1706
+ const diagnostics = collectDeclarativeAccessValidationIssues(config).map((issue) => ({
1707
+ severity: "error",
1708
+ source: "declarativeAccess",
1709
+ path: issue.path,
1710
+ surface: issue.surface,
1711
+ message: issue.message,
1712
+ expression: issue.expression
1713
+ }));
1714
+ if (diagnostics.length === 0) return;
1715
+ throw new ConfigValidationError(source, diagnostics);
1716
+ }
1717
+
1718
+ // src/auth/token.ts
1719
+ import { SignJWT, jwtVerify, decodeJwt } from "jose";
1720
+ import { TextEncoder } from "util";
1721
+ function getSecret() {
1722
+ const secret = process.env.DYRECTED_JWT_SECRET;
1723
+ if (!secret) {
1724
+ throw new Error(
1725
+ "[dyrected/core] DYRECTED_JWT_SECRET is not set. Add it to your environment variables to enable auth collections."
1726
+ );
1727
+ }
1728
+ return new TextEncoder().encode(secret);
1729
+ }
1730
+ var DEFAULT_EXPIRY = "7d";
1731
+ async function signCollectionToken(payload, expiresIn = DEFAULT_EXPIRY) {
1732
+ return new SignJWT({ ...payload }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(expiresIn).sign(getSecret());
1733
+ }
1734
+ async function verifyCollectionToken(token) {
1735
+ const { payload } = await jwtVerify(token, getSecret());
1736
+ return payload;
1737
+ }
1738
+ function decodeCollectionToken(token) {
1739
+ try {
1740
+ return decodeJwt(token);
1741
+ } catch {
1742
+ return null;
1743
+ }
1744
+ }
1745
+
1746
+ // src/auth/sessions.ts
1747
+ var AUTH_SESSIONS_COLLECTION = "__auth_sessions";
1748
+ async function issueAuthSessionToken(args) {
1749
+ const sessionId = createSessionId();
1750
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
1751
+ const db = args.config.db;
1752
+ if (db) {
1753
+ await db.create({
1754
+ collection: AUTH_SESSIONS_COLLECTION,
1755
+ data: {
1756
+ id: sessionId,
1757
+ userId: args.userId,
1758
+ email: args.email,
1759
+ collection: args.collection,
1760
+ authSource: args.authSource ?? "local",
1761
+ providerId: args.providerId,
1762
+ lastIp: args.ip,
1763
+ lastSeenAt: now2,
1764
+ revokedAt: null,
1765
+ expiresAt: null
1766
+ }
1767
+ });
1768
+ }
1769
+ const token = await signCollectionToken(
1770
+ {
1771
+ sub: args.userId,
1772
+ email: args.email,
1773
+ collection: args.collection,
1774
+ authSource: args.authSource,
1775
+ providerId: args.providerId,
1776
+ sid: sessionId
1777
+ },
1778
+ args.expiresIn
1779
+ );
1780
+ const payload = decodeCollectionToken(token);
1781
+ const expiresAt = payload?.exp != null ? new Date(payload.exp * 1e3).toISOString() : null;
1782
+ if (db && expiresAt) {
1783
+ await db.update({
1784
+ collection: AUTH_SESSIONS_COLLECTION,
1785
+ id: sessionId,
1786
+ data: {
1787
+ expiresAt,
1788
+ lastSeenAt: now2,
1789
+ lastIp: args.ip
1790
+ }
1791
+ });
1792
+ }
1793
+ return token;
1794
+ }
1795
+ async function getAuthSession(config, sessionId) {
1796
+ const db = config.db;
1797
+ if (!db) return null;
1798
+ return await db.findOne({
1799
+ collection: AUTH_SESSIONS_COLLECTION,
1800
+ id: sessionId
1801
+ });
1802
+ }
1803
+ function isAuthSessionActive(session) {
1804
+ if (!session) return false;
1805
+ if (session.revokedAt) return false;
1806
+ if (session.expiresAt && new Date(session.expiresAt).getTime() <= Date.now()) {
1807
+ return false;
1808
+ }
1809
+ return true;
1810
+ }
1811
+ async function touchAuthSession(config, sessionId, args) {
1812
+ const db = config.db;
1813
+ if (!db) return;
1814
+ await db.update({
1815
+ collection: AUTH_SESSIONS_COLLECTION,
1816
+ id: sessionId,
1817
+ data: {
1818
+ lastSeenAt: (/* @__PURE__ */ new Date()).toISOString(),
1819
+ ...args.ip ? { lastIp: args.ip } : {}
1820
+ }
1821
+ });
1822
+ }
1823
+ async function revokeAuthSession(config, sessionId) {
1824
+ const db = config.db;
1825
+ if (!db) return;
1826
+ await db.update({
1827
+ collection: AUTH_SESSIONS_COLLECTION,
1828
+ id: sessionId,
1829
+ data: {
1830
+ revokedAt: (/* @__PURE__ */ new Date()).toISOString()
1831
+ }
1832
+ });
1833
+ }
1834
+ async function revokeAllAuthSessions(config, args) {
1835
+ const db = config.db;
1836
+ if (!db) return 0;
1837
+ let page = 1;
1838
+ let revoked = 0;
1839
+ while (true) {
1840
+ const result = await db.find({
1841
+ collection: AUTH_SESSIONS_COLLECTION,
1842
+ where: {
1843
+ userId: { equals: args.userId },
1844
+ collection: { equals: args.collection }
1845
+ },
1846
+ page,
1847
+ limit: 100
1848
+ });
1849
+ for (const session of result.docs) {
1850
+ if (session.revokedAt) continue;
1851
+ await revokeAuthSession(config, session.id);
1852
+ revoked += 1;
1853
+ }
1854
+ if (!result.hasNextPage) break;
1855
+ page += 1;
1856
+ }
1857
+ return revoked;
1858
+ }
1859
+ function createSessionId() {
1860
+ return globalThis.crypto?.randomUUID?.() ? globalThis.crypto.randomUUID() : `sess_${Date.now()}_${Math.random().toString(36).slice(2)}`;
1861
+ }
1862
+
1863
+ // src/utils/block-references.ts
1864
+ function mergeUniqueBlocks(blocks) {
1865
+ const seen = /* @__PURE__ */ new Map();
1866
+ for (const block of blocks) {
1867
+ const existing = seen.get(block.slug);
1868
+ if (existing && existing !== block) {
1869
+ throw new Error(
1870
+ `Duplicate block slug "${block.slug}" found in the reusable block registry. Block slugs must be unique.`
1871
+ );
1872
+ }
1873
+ if (!existing) seen.set(block.slug, block);
1874
+ }
1875
+ return Array.from(seen.values());
1876
+ }
1877
+ function buildRegistry(blocks) {
1878
+ return new Map(blocks.map((block) => [block.slug, block]));
1879
+ }
1880
+ function resolveField(field, registry, blockCache) {
1881
+ const next = { ...field };
1882
+ if (next.fields) {
1883
+ next.fields = next.fields.map(
1884
+ (child) => resolveField(child, registry, blockCache)
1885
+ );
1886
+ }
1887
+ if (next.type !== "blocks") return next;
1888
+ const hasInlineBlocks = Array.isArray(next.blocks) && next.blocks.length > 0;
1889
+ const hasReferences = Array.isArray(next.blockReferences) && next.blockReferences.length > 0;
1890
+ if (hasInlineBlocks && hasReferences) {
1891
+ throw new Error(
1892
+ `Blocks field "${next.name ?? "(unnamed)"}" cannot define both "blocks" and "blockReferences". Use one or the other.`
1893
+ );
1894
+ }
1895
+ if (hasReferences) {
1896
+ next.blocks = next.blockReferences.map((slug) => {
1897
+ const block = registry.get(slug);
1898
+ if (!block) {
1899
+ throw new Error(
1900
+ `Unknown block reference "${slug}" on blocks field "${next.name ?? "(unnamed)"}". Add it to defineConfig({ blocks: [...] }).`
1901
+ );
1902
+ }
1903
+ return resolveBlock(block, registry, blockCache);
1904
+ });
1905
+ return next;
1906
+ }
1907
+ if (hasInlineBlocks) {
1908
+ next.blocks = next.blocks.map(
1909
+ (block) => resolveBlock(block, registry, blockCache)
1910
+ );
1911
+ }
1912
+ return next;
1913
+ }
1914
+ function resolveBlock(block, registry, blockCache) {
1915
+ const cached = blockCache.get(block);
1916
+ if (cached) return cached;
1917
+ const resolved = {
1918
+ ...block,
1919
+ fields: []
1920
+ };
1921
+ blockCache.set(block, resolved);
1922
+ resolved.fields = block.fields.map(
1923
+ (field) => resolveField(field, registry, blockCache)
1924
+ );
1925
+ return resolved;
1926
+ }
1927
+ function resolveFields(fields, registry, blockCache) {
1928
+ return fields.map((field) => resolveField(field, registry, blockCache));
1929
+ }
1930
+ function normalizeSchemaFragment(fragment) {
1931
+ const reusableBlocks = mergeUniqueBlocks(fragment.blocks ?? []);
1932
+ const registry = buildRegistry(reusableBlocks);
1933
+ const blockCache = /* @__PURE__ */ new WeakMap();
1934
+ const resolvedBlocks = reusableBlocks.map(
1935
+ (block) => resolveBlock(block, registry, blockCache)
1936
+ );
1937
+ const resolvedCollections = (fragment.collections ?? []).map(
1938
+ (collection) => ({
1939
+ ...collection,
1940
+ fields: resolveFields(collection.fields ?? [], registry, blockCache)
1941
+ })
1942
+ );
1943
+ const resolvedGlobals = (fragment.globals ?? []).map((global) => ({
1944
+ ...global,
1945
+ fields: resolveFields(global.fields ?? [], registry, blockCache)
1946
+ }));
1947
+ return {
1948
+ ...fragment,
1949
+ ...fragment.blocks ? { blocks: resolvedBlocks } : {},
1950
+ ...fragment.collections ? { collections: resolvedCollections } : {},
1951
+ ...fragment.globals ? { globals: resolvedGlobals } : {}
1952
+ };
1953
+ }
1954
+ function mergeDynamicConfig(baseConfig, dynamic) {
1955
+ const normalizedDynamic = normalizeSchemaFragment({
1956
+ ...dynamic,
1957
+ blocks: [...baseConfig.blocks ?? [], ...dynamic.blocks ?? []]
1958
+ });
1959
+ return {
1960
+ ...baseConfig,
1961
+ ...normalizedDynamic.blocks ? { blocks: normalizedDynamic.blocks } : {},
1962
+ ...dynamic.accessPolicies ? {
1963
+ accessPolicies: {
1964
+ ...baseConfig.accessPolicies ?? {},
1965
+ ...dynamic.accessPolicies
1966
+ }
1967
+ } : {},
1968
+ ...dynamic.admin ? { admin: { ...baseConfig.admin, ...dynamic.admin } } : {},
1969
+ ...dynamic.adminAuth ? { adminAuth: { ...baseConfig.adminAuth, ...dynamic.adminAuth } } : {},
1970
+ collections: normalizedDynamic.collections ? [...baseConfig.collections, ...normalizedDynamic.collections] : baseConfig.collections,
1971
+ globals: normalizedDynamic.globals ? [...baseConfig.globals, ...normalizedDynamic.globals] : baseConfig.globals
1972
+ };
1973
+ }
1974
+
1975
+ // src/utils/config.ts
1976
+ var AUDIT_COLLECTION_SLUG = "__audit";
1977
+ var SYSTEM_FIELDS = [
1978
+ {
1979
+ name: "createdAt",
1980
+ type: "date",
1981
+ label: "Created At",
1982
+ admin: { readOnly: true, hidden: true }
1983
+ },
1984
+ {
1985
+ name: "updatedAt",
1986
+ type: "date",
1987
+ label: "Updated At",
1988
+ admin: { readOnly: true, hidden: true }
1989
+ },
1990
+ {
1991
+ name: "createdBy",
1992
+ type: "text",
1993
+ label: "Created By",
1994
+ admin: { readOnly: true, hidden: true }
1995
+ },
1996
+ {
1997
+ name: "updatedBy",
1998
+ type: "text",
1999
+ label: "Updated By",
2000
+ admin: { readOnly: true, hidden: true }
2001
+ }
2002
+ ];
2003
+ var AUDIT_COLLECTION = {
2004
+ slug: AUDIT_COLLECTION_SLUG,
2005
+ labels: { singular: "Audit Log", plural: "Audit Logs" },
2006
+ fields: [
2007
+ { name: "collection", type: "text", label: "Collection", required: true },
2008
+ { name: "documentId", type: "text", label: "Document ID" },
2009
+ {
2010
+ name: "operation",
2011
+ type: "select",
2012
+ label: "Operation",
2013
+ options: ["create", "update", "delete"],
2014
+ required: true
2015
+ },
2016
+ { name: "user", type: "text", label: "User ID" },
2017
+ { name: "timestamp", type: "date", label: "Timestamp", required: true },
2018
+ { name: "changes", type: "json", label: "Changes" }
2019
+ ],
2020
+ access: {
2021
+ read: () => false,
2022
+ create: () => false,
2023
+ update: () => false,
2024
+ delete: () => false
2025
+ },
2026
+ admin: { hidden: true }
2027
+ };
2028
+ var WORKFLOW_HISTORY_COLLECTION_CONFIG = {
2029
+ slug: WORKFLOW_HISTORY_COLLECTION,
2030
+ labels: { singular: "Workflow transition", plural: "Workflow transitions" },
2031
+ fields: [
2032
+ { name: "collection", type: "text", required: true },
2033
+ { name: "documentId", type: "text", required: true },
2034
+ { name: "transition", type: "text", required: true },
2035
+ { name: "from", type: "text", required: true },
2036
+ { name: "to", type: "text", required: true },
2037
+ { name: "revision", type: "number", required: true },
2038
+ { name: "comment", type: "textarea" },
2039
+ { name: "actorId", type: "text" },
2040
+ { name: "createdAt", type: "date", required: true }
2041
+ ],
2042
+ access: {
2043
+ read: ({ user }) => !!user,
2044
+ create: () => false,
2045
+ update: () => false,
2046
+ delete: () => false
2047
+ },
2048
+ admin: { hidden: true }
2049
+ };
2050
+ var LIFECYCLE_EVENTS_COLLECTION_CONFIG = {
2051
+ slug: LIFECYCLE_EVENTS_COLLECTION,
2052
+ labels: { singular: "Lifecycle event", plural: "Lifecycle events" },
2053
+ fields: [
2054
+ { name: "name", type: "text", required: true },
2055
+ { name: "collection", type: "text", required: true },
2056
+ { name: "documentId", type: "text", required: true },
2057
+ { name: "occurredAt", type: "date", required: true },
2058
+ { name: "actorId", type: "text" },
2059
+ { name: "payload", type: "json", required: true },
2060
+ { name: "attempts", type: "number", required: true },
2061
+ {
2062
+ name: "status",
2063
+ type: "select",
2064
+ options: ["pending", "processing", "delivered", "failed"],
2065
+ required: true
2066
+ },
2067
+ { name: "nextAttemptAt", type: "date" },
2068
+ { name: "deliveredAt", type: "date" },
2069
+ { name: "lastError", type: "textarea" }
2070
+ ],
2071
+ access: {
2072
+ read: ({ user }) => !!user?.roles?.includes("admin"),
2073
+ create: () => false,
2074
+ update: () => false,
2075
+ delete: () => false
2076
+ },
2077
+ admin: { hidden: true }
2078
+ };
2079
+ var AUTH_SESSIONS_COLLECTION_CONFIG = {
2080
+ slug: AUTH_SESSIONS_COLLECTION,
2081
+ labels: { singular: "Auth session", plural: "Auth sessions" },
2082
+ fields: [
2083
+ { name: "userId", type: "text", required: true },
2084
+ { name: "email", type: "email", required: true },
2085
+ { name: "collection", type: "text", required: true },
2086
+ { name: "authSource", type: "text" },
2087
+ { name: "providerId", type: "text" },
2088
+ { name: "lastIp", type: "text" },
2089
+ { name: "lastSeenAt", type: "date" },
2090
+ { name: "expiresAt", type: "date" },
2091
+ { name: "revokedAt", type: "date" }
2092
+ ],
2093
+ access: {
2094
+ read: () => false,
2095
+ create: () => false,
2096
+ update: () => false,
2097
+ delete: () => false
2098
+ },
2099
+ admin: { hidden: true }
2100
+ };
2101
+ function normalizeConfig(config) {
2102
+ const schemaAwareConfig = normalizeSchemaFragment(config);
2103
+ assertValidDeclarativeHooksInConfig(schemaAwareConfig, "config");
2104
+ assertValidDeclarativeAccessInConfig(schemaAwareConfig, "config");
2105
+ assertValidAdminConditionsInConfig(schemaAwareConfig, "config");
2106
+ assertValidPreviewUrlsInConfig(schemaAwareConfig, "config");
2107
+ const collections = schemaAwareConfig?.collections || [];
2108
+ const globals = schemaAwareConfig?.globals || [];
2109
+ const needsAudit = collections.some((col) => col.audit);
2110
+ const needsWorkflow = collections.some((col) => col.workflow || col.drafts);
2111
+ const needsAuthSessions = collections.some((col) => !!col.auth);
2112
+ const adminAuthCollectionSlug = getAdminAuthCollection({
2113
+ collections,
2114
+ adminAuth: schemaAwareConfig.adminAuth
2115
+ })?.slug;
2116
+ const normalizedCollections = collections.map((col) => {
2117
+ let fields = col.fields || [];
2118
+ const existingFieldNames = new Set(fields.map((f) => f.name));
2119
+ if (col.auth) {
2120
+ if (!existingFieldNames.has("email")) {
2121
+ fields = [
2122
+ ...fields,
2123
+ {
2124
+ name: "email",
2125
+ type: "email",
2126
+ label: "Email",
2127
+ required: true,
2128
+ unique: true,
2129
+ promoted: true,
2130
+ access: {
2131
+ update: "!id"
2132
+ }
2133
+ }
2134
+ ];
2135
+ }
2136
+ if (!existingFieldNames.has("password")) {
2137
+ fields = [
2138
+ ...fields,
2139
+ {
2140
+ name: "password",
2141
+ type: "text",
2142
+ label: "Password",
2143
+ required: true,
2144
+ access: {
2145
+ update: "!id || user.id == id"
2146
+ }
2147
+ }
2148
+ ];
2149
+ }
2150
+ if (!existingFieldNames.has("roles")) {
2151
+ fields = [
2152
+ ...fields,
2153
+ {
2154
+ name: "roles",
2155
+ type: "select",
2156
+ label: "Roles",
2157
+ defaultValue: [],
2158
+ options: [
2159
+ { value: "admin", label: "Admin" },
2160
+ { value: "editor", label: "Editor" },
2161
+ { value: "viewer", label: "Viewer" }
2162
+ ],
2163
+ access: {
2164
+ update: "user.roles && 'admin' in user.roles"
2165
+ }
2166
+ }
2167
+ ];
2168
+ }
2169
+ if (!existingFieldNames.has("status")) {
2170
+ fields = [
2171
+ ...fields,
2172
+ {
2173
+ name: "status",
2174
+ type: "select",
2175
+ label: "Status",
2176
+ defaultValue: "active",
2177
+ options: [
2178
+ { value: "active", label: "Active" },
2179
+ { value: "pending", label: "Pending" }
2180
+ ],
2181
+ access: {
2182
+ update: "user.roles && 'admin' in user.roles && user.id != id"
2183
+ },
2184
+ admin: {
2185
+ condition: `!(data.roles && "admin" in data.roles)`
2186
+ }
2187
+ }
2188
+ ];
2189
+ }
2190
+ fields = fields.map((field) => {
2191
+ if (field.name === "email") {
2192
+ return {
2193
+ ...field,
2194
+ // Email is the login identifier. Keep the integrity constraints
2195
+ // auth relies on even when the field is explicitly redefined, so a
2196
+ // custom `email` field can never silently drop uniqueness.
2197
+ required: true,
2198
+ unique: true,
2199
+ promoted: true,
2200
+ access: {
2201
+ ...field.access || {},
2202
+ update: "!id"
2203
+ }
2204
+ };
2205
+ }
2206
+ if (field.name === "password") {
2207
+ return {
2208
+ ...field,
2209
+ // Password is required to authenticate; enforce it regardless of
2210
+ // how the field was declared.
2211
+ required: true,
2212
+ admin: { ...field.admin || {} },
2213
+ access: {
2214
+ ...field.access || {},
2215
+ update: "!id || user.id == id"
2216
+ }
2217
+ };
2218
+ }
2219
+ if (field.name === "roles") {
2220
+ return {
2221
+ ...field,
2222
+ access: {
2223
+ ...field.access || {},
2224
+ // Must be an admin; cannot edit own roles (no self-elevation).
2225
+ update: "user.roles && 'admin' in user.roles && user.id != id"
2226
+ }
2227
+ };
2228
+ }
2229
+ if (field.name === "status") {
2230
+ return {
2231
+ ...field,
2232
+ access: {
2233
+ ...field.access || {},
2234
+ update: "user.roles && 'admin' in user.roles && user.id != id"
2235
+ }
2236
+ };
2237
+ }
2238
+ return field;
2239
+ });
2240
+ }
2241
+ if (adminAuthCollectionSlug && col.slug === adminAuthCollectionSlug && schemaAwareConfig.adminAuth?.mode === "external") {
2242
+ const externalAdminFields = [
2243
+ {
2244
+ name: "authProvider",
2245
+ type: "text",
2246
+ label: "Auth Provider",
2247
+ admin: { readOnly: true, hidden: true }
2248
+ },
2249
+ {
2250
+ name: "externalSubject",
2251
+ type: "text",
2252
+ label: "External Subject",
2253
+ admin: { readOnly: true, hidden: true }
2254
+ },
2255
+ {
2256
+ name: "authSource",
2257
+ type: "text",
2258
+ label: "Auth Source",
2259
+ admin: { readOnly: true, hidden: true }
2260
+ },
2261
+ {
2262
+ name: "lastLoginAt",
2263
+ type: "date",
2264
+ label: "Last Login At",
2265
+ admin: { readOnly: true, hidden: true }
2266
+ }
2267
+ ];
2268
+ for (const field of externalAdminFields) {
2269
+ if (!existingFieldNames.has(field.name)) {
2270
+ fields = [...fields, field];
2271
+ }
2272
+ }
2273
+ }
2274
+ const updatedFieldNames = new Set(fields.map((f) => f.name));
2275
+ const fieldsToInject = SYSTEM_FIELDS.filter((f) => !updatedFieldNames.has(f.name));
2276
+ const workflow = col.workflow || (col.drafts ? simplePublishingWorkflow() : void 0);
2277
+ return {
2278
+ ...col,
2279
+ workflow,
2280
+ fields: [...fields, ...fieldsToInject]
2281
+ };
2282
+ });
2283
+ const hasAuditCollection = normalizedCollections.some((col) => col.slug === AUDIT_COLLECTION_SLUG);
2284
+ const systemCollections = [];
2285
+ if (needsAudit && !hasAuditCollection) systemCollections.push(AUDIT_COLLECTION);
2286
+ if (needsWorkflow && !normalizedCollections.some((col) => col.slug === WORKFLOW_HISTORY_COLLECTION)) {
2287
+ systemCollections.push(WORKFLOW_HISTORY_COLLECTION_CONFIG);
2288
+ }
2289
+ if (needsWorkflow && !normalizedCollections.some((col) => col.slug === LIFECYCLE_EVENTS_COLLECTION)) {
2290
+ systemCollections.push(LIFECYCLE_EVENTS_COLLECTION_CONFIG);
2291
+ }
2292
+ if (needsAuthSessions && !normalizedCollections.some((col) => col.slug === AUTH_SESSIONS_COLLECTION)) {
2293
+ systemCollections.push(AUTH_SESSIONS_COLLECTION_CONFIG);
2294
+ }
2295
+ return {
2296
+ ...schemaAwareConfig,
2297
+ collections: [...normalizedCollections, ...systemCollections],
2298
+ globals
2299
+ };
2300
+ }
2301
+
2302
+ // src/utils/hooks.ts
2303
+ import jexl3 from "jexl";
2304
+ async function runCollectionHooks(hooks, args, options = {}) {
2305
+ if (!hooks || hooks.length === 0) {
2306
+ return args.data ?? args.doc ?? args.query ?? void 0;
2307
+ }
2308
+ const payloadKey = args.data !== void 0 ? "data" : args.doc !== void 0 ? "doc" : "query" in args ? "query" : void 0;
2309
+ let currentPayload = payloadKey === void 0 ? void 0 : args[payloadKey];
2310
+ for (const hook of hooks) {
2311
+ try {
2312
+ const hookArgs = {
2313
+ ...args,
2314
+ ...payloadKey !== void 0 ? { [payloadKey]: currentPayload } : {}
2315
+ };
2316
+ const result = typeof hook === "string" ? await (() => {
2317
+ if (options.surface) {
2318
+ assertValidDeclarativeHookExpression(
2319
+ hook,
2320
+ options.surface,
2321
+ options.path ?? options.surface
2322
+ );
2323
+ }
2324
+ return jexl3.eval(hook, hookArgs);
2325
+ })() : await hook(hookArgs);
2326
+ if (result !== void 0) {
2327
+ if (typeof hook === "string" && options.surface) {
2328
+ assertValidDeclarativeHookResult(
2329
+ result,
2330
+ options.surface,
2331
+ options.path ?? options.surface
2332
+ );
2333
+ }
2334
+ currentPayload = typeof hook === "string" && currentPayload && typeof currentPayload === "object" && !Array.isArray(currentPayload) && result && typeof result === "object" && !Array.isArray(result) ? {
2335
+ ...currentPayload,
2336
+ ...result
2337
+ } : result;
2338
+ }
2339
+ } catch (err) {
2340
+ if (options.isolated) {
2341
+ getConfigLogger(void 0, "hooks").error({
2342
+ err,
2343
+ msg: "Side-effect hook failed after a successful write"
2344
+ });
2345
+ } else {
2346
+ throw err;
2347
+ }
2348
+ }
2349
+ }
2350
+ return currentPayload;
2351
+ }
2352
+ async function executeFieldBeforeChange(fields, data, originalDoc, user, db, pathPrefix = "") {
2353
+ if (!data || typeof data !== "object") return data;
2354
+ const result = { ...data };
2355
+ for (const field of fields) {
2356
+ if (!field.name) continue;
2357
+ const fieldPath = pathPrefix ? `${pathPrefix}.${field.name}` : field.name;
2358
+ const value = result[field.name];
2359
+ const origValue = originalDoc?.[field.name];
2360
+ let updatedValue = value;
2361
+ if (field.hooks?.beforeChange) {
2362
+ for (const hook of field.hooks.beforeChange) {
2363
+ const hookArgs = {
2364
+ value: updatedValue,
2365
+ originalDoc: originalDoc ?? void 0,
2366
+ data: result,
2367
+ user,
2368
+ db
2369
+ };
2370
+ updatedValue = typeof hook === "string" ? await (() => {
2371
+ assertValidDeclarativeHookExpression(
2372
+ hook,
2373
+ "field.beforeChange",
2374
+ fieldPath
2375
+ );
2376
+ return jexl3.eval(hook, hookArgs);
2377
+ })() : await hook(hookArgs);
2378
+ }
2379
+ result[field.name] = updatedValue;
2380
+ }
2381
+ if (updatedValue !== void 0 && updatedValue !== null) {
2382
+ if (field.type === "object" && field.fields) {
2383
+ result[field.name] = await executeFieldBeforeChange(
2384
+ field.fields,
2385
+ updatedValue,
2386
+ origValue,
2387
+ user,
2388
+ db,
2389
+ fieldPath
2390
+ );
2391
+ } else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
2392
+ const arrayResult = [];
2393
+ for (let i = 0; i < updatedValue.length; i++) {
2394
+ const item = updatedValue[i];
2395
+ const origItem = Array.isArray(origValue) ? origValue[i] : null;
2396
+ arrayResult.push(
2397
+ await executeFieldBeforeChange(
2398
+ field.fields,
2399
+ item,
2400
+ origItem,
2401
+ user,
2402
+ db,
2403
+ fieldPath
2404
+ )
2405
+ );
2406
+ }
2407
+ result[field.name] = arrayResult;
2408
+ } else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
2409
+ const blocksResult = [];
2410
+ for (let i = 0; i < updatedValue.length; i++) {
2411
+ const blockData = updatedValue[i];
2412
+ const origBlock = Array.isArray(origValue) ? origValue[i] : null;
2413
+ const blockConfig = field.blocks.find(
2414
+ (b) => b.slug === blockData.blockType
2415
+ );
2416
+ if (blockConfig) {
2417
+ blocksResult.push(
2418
+ await executeFieldBeforeChange(
2419
+ blockConfig.fields,
2420
+ blockData,
2421
+ origBlock,
2422
+ user,
2423
+ db,
2424
+ fieldPath
2425
+ )
2426
+ );
2427
+ } else {
2428
+ blocksResult.push(blockData);
2429
+ }
2430
+ }
2431
+ result[field.name] = blocksResult;
2432
+ }
2433
+ }
2434
+ }
2435
+ return result;
2436
+ }
2437
+ async function executeFieldAfterRead(fields, doc, user, db) {
2438
+ if (!doc || typeof doc !== "object") return doc;
2439
+ const result = { ...doc };
2440
+ for (const field of fields) {
2441
+ if (!field.name) continue;
2442
+ const value = result[field.name];
2443
+ let updatedValue = value;
2444
+ if (field.hooks?.afterRead) {
2445
+ for (const hook of field.hooks.afterRead) {
2446
+ const typedHook = hook;
2447
+ const hookArgs = {
2448
+ value: updatedValue,
2449
+ doc: result,
2450
+ user,
2451
+ db
2452
+ };
2453
+ updatedValue = await typedHook(hookArgs);
2454
+ }
2455
+ result[field.name] = updatedValue;
2456
+ }
2457
+ if (updatedValue !== void 0 && updatedValue !== null) {
2458
+ if (field.type === "object" && field.fields) {
2459
+ result[field.name] = await executeFieldAfterRead(
2460
+ field.fields,
2461
+ updatedValue,
2462
+ user,
2463
+ db
2464
+ );
2465
+ } else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
2466
+ const arrayResult = [];
2467
+ for (const item of updatedValue) {
2468
+ arrayResult.push(
2469
+ await executeFieldAfterRead(
2470
+ field.fields,
2471
+ item,
2472
+ user,
2473
+ db
2474
+ )
2475
+ );
2476
+ }
2477
+ result[field.name] = arrayResult;
2478
+ } else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
2479
+ const blocksResult = [];
2480
+ for (const blockData of updatedValue) {
2481
+ const typedBlock = blockData;
2482
+ const blockConfig = field.blocks.find(
2483
+ (b) => b.slug === typedBlock.blockType
2484
+ );
2485
+ if (blockConfig) {
2486
+ blocksResult.push(
2487
+ await executeFieldAfterRead(
2488
+ blockConfig.fields,
2489
+ typedBlock,
2490
+ user,
2491
+ db
2492
+ )
2493
+ );
2494
+ } else {
2495
+ blocksResult.push(blockData);
2496
+ }
2497
+ }
2498
+ result[field.name] = blocksResult;
2499
+ }
2500
+ }
2501
+ }
2502
+ return result;
2503
+ }
2504
+
2505
+ // src/utils/openapi.ts
2506
+ function getCollectionLabels(collection) {
2507
+ return collection.labels || { singular: collection.slug, plural: collection.slug };
2508
+ }
2509
+ function getCollectionTag(collection) {
2510
+ return `Collection: ${getCollectionLabels(collection).plural}`;
2511
+ }
2512
+ function getGlobalTag(global) {
2513
+ return `Global: ${global.label || global.slug}`;
2514
+ }
2515
+ function generateOpenApi(config) {
2516
+ const spec = {
2517
+ openapi: "3.0.0",
2518
+ info: {
2519
+ title: "Dyrected API",
2520
+ version: "1.0.0",
2521
+ description: "Automatically generated OpenAPI specification for the Dyrected project."
2522
+ },
2523
+ components: {
2524
+ schemas: {
2525
+ WorkflowMetadata: {
2526
+ type: "object",
2527
+ required: ["state", "revision"],
2528
+ properties: {
2529
+ state: { type: "string" },
2530
+ revision: { type: "integer", minimum: 1 },
2531
+ publishedRevision: { type: "integer", minimum: 1 },
2532
+ publishedAt: { type: "string", format: "date-time" },
2533
+ publishedBy: { type: "string" },
2534
+ availableTransitions: { type: "array", items: { type: "string" } }
2535
+ }
2536
+ },
2537
+ WorkflowTransitionRequest: {
2538
+ type: "object",
2539
+ properties: {
2540
+ expectedRevision: { type: "integer", minimum: 1 },
2541
+ comment: { type: "string" }
2542
+ }
2543
+ },
2544
+ WorkflowHistoryEntry: {
2545
+ type: "object",
2546
+ required: [
2547
+ "collection",
2548
+ "documentId",
2549
+ "transition",
2550
+ "from",
2551
+ "to",
2552
+ "revision",
2553
+ "createdAt"
2554
+ ],
2555
+ properties: {
2556
+ id: { type: "string" },
2557
+ collection: { type: "string" },
2558
+ documentId: { type: "string" },
2559
+ transition: { type: "string" },
2560
+ from: { type: "string" },
2561
+ to: { type: "string" },
2562
+ revision: { type: "integer" },
2563
+ comment: { type: "string", nullable: true },
2564
+ actorId: { type: "string", nullable: true },
2565
+ createdAt: { type: "string", format: "date-time" }
2566
+ }
2567
+ },
2568
+ AuditEntry: {
2569
+ type: "object",
2570
+ required: ["collection", "operation", "timestamp"],
2571
+ properties: {
2572
+ id: { type: "string" },
2573
+ collection: { type: "string" },
2574
+ documentId: { type: "string", nullable: true },
2575
+ operation: { type: "string" },
2576
+ user: { type: "string", nullable: true },
2577
+ timestamp: { type: "string", format: "date-time" },
2578
+ changes: {
2579
+ oneOf: [
2580
+ { type: "string" },
2581
+ { type: "object", additionalProperties: true },
2582
+ { type: "null" }
2583
+ ]
2584
+ }
2585
+ }
2586
+ },
2587
+ Error: {
2588
+ type: "object",
2589
+ properties: {
2590
+ message: { type: "string" },
2591
+ errors: {
2592
+ type: "array",
2593
+ items: { type: "object", additionalProperties: true }
2594
+ }
2595
+ }
2596
+ },
2597
+ AuthCredentials: {
2598
+ type: "object",
2599
+ required: ["email", "password"],
2600
+ properties: {
2601
+ email: { type: "string", format: "email" },
2602
+ password: { type: "string" }
2603
+ }
2604
+ },
2605
+ TokenResponse: {
2606
+ type: "object",
2607
+ properties: {
2608
+ token: { type: "string" },
2609
+ user: { type: "object", additionalProperties: true }
2610
+ }
2611
+ }
2612
+ },
2613
+ securitySchemes: {
2614
+ ApiKeyAuth: {
2615
+ type: "apiKey",
2616
+ in: "header",
2617
+ name: "x-api-key"
2618
+ }
2619
+ }
2620
+ },
2621
+ paths: {},
2622
+ security: [{ ApiKeyAuth: [] }]
2623
+ };
2624
+ spec.paths["/api/schemas"] = {
2625
+ get: {
2626
+ tags: ["System"],
2627
+ summary: "Get the serialized Dyrected schema",
2628
+ security: [],
2629
+ responses: {
2630
+ 200: { description: "Collection and global schema definitions" }
2631
+ }
2632
+ }
2633
+ };
2634
+ spec.paths["/api/openapi.json"] = {
2635
+ get: {
2636
+ tags: ["System"],
2637
+ summary: "Get the OpenAPI specification",
2638
+ security: [],
2639
+ responses: { 200: { description: "OpenAPI 3.0 document" } }
2640
+ }
2641
+ };
2642
+ spec.paths["/api/docs"] = {
2643
+ get: {
2644
+ tags: ["System"],
2645
+ summary: "Open interactive API documentation",
2646
+ security: [],
2647
+ responses: { 200: { description: "Swagger UI HTML" } }
2648
+ }
2649
+ };
2650
+ spec.paths["/api/dyrected/options/{collection}/{field}"] = {
2651
+ get: {
2652
+ tags: ["System"],
2653
+ summary: "Resolve dynamic field options",
2654
+ parameters: [
2655
+ {
2656
+ name: "collection",
2657
+ in: "path",
2658
+ required: true,
2659
+ schema: { type: "string" }
2660
+ },
2661
+ {
2662
+ name: "field",
2663
+ in: "path",
2664
+ required: true,
2665
+ schema: { type: "string" }
2666
+ }
2667
+ ],
2668
+ responses: { 200: { description: "Resolved option items" } }
2669
+ }
2670
+ };
2671
+ spec.paths["/api/preferences/{key}"] = {
2672
+ get: {
2673
+ tags: ["Preferences"],
2674
+ summary: "Get an authenticated user preference",
2675
+ parameters: [
2676
+ { name: "key", in: "path", required: true, schema: { type: "string" } }
2677
+ ],
2678
+ responses: { 200: { description: "Preference value" } }
2679
+ },
2680
+ put: {
2681
+ tags: ["Preferences"],
2682
+ summary: "Set an authenticated user preference",
2683
+ parameters: [
2684
+ { name: "key", in: "path", required: true, schema: { type: "string" } }
2685
+ ],
2686
+ requestBody: {
2687
+ required: true,
2688
+ content: { "application/json": { schema: { type: "object" } } }
2689
+ },
2690
+ responses: { 200: { description: "Updated preference" } }
2691
+ }
2692
+ };
2693
+ spec.paths["/api/preview-token"] = {
2694
+ post: {
2695
+ tags: ["Preview"],
2696
+ summary: "Create a preview token",
2697
+ responses: { 200: { description: "Short-lived preview token" } }
2698
+ }
2699
+ };
2700
+ spec.paths["/api/preview-data"] = {
2701
+ get: {
2702
+ tags: ["Preview"],
2703
+ summary: "Resolve preview data from a token",
2704
+ security: [],
2705
+ parameters: [
2706
+ {
2707
+ name: "token",
2708
+ in: "query",
2709
+ required: true,
2710
+ schema: { type: "string" }
2711
+ }
2712
+ ],
2713
+ responses: { 200: { description: "Preview document data" } }
2714
+ }
2715
+ };
2716
+ spec.paths["/api/audit"] = {
2717
+ get: {
2718
+ tags: ["Audit"],
2719
+ summary: "Get audit entries across all readable audited collections",
2720
+ parameters: [
2721
+ {
2722
+ name: "limit",
2723
+ in: "query",
2724
+ schema: { type: "integer", default: 50, maximum: 100 }
2725
+ },
2726
+ { name: "page", in: "query", schema: { type: "integer", default: 1 } },
2727
+ {
2728
+ name: "where",
2729
+ in: "query",
2730
+ schema: { type: "string" },
2731
+ description: "JSON filter"
2732
+ },
2733
+ {
2734
+ name: "sort",
2735
+ in: "query",
2736
+ schema: { type: "string", default: "-timestamp" }
2737
+ }
2738
+ ],
2739
+ responses: {
2740
+ 200: {
2741
+ description: "Audit entries",
2742
+ content: {
2743
+ "application/json": {
2744
+ schema: {
2745
+ type: "object",
2746
+ properties: {
2747
+ docs: {
2748
+ type: "array",
2749
+ items: { $ref: "#/components/schemas/AuditEntry" }
2750
+ },
2751
+ total: { type: "integer" },
2752
+ limit: { type: "integer" },
2753
+ page: { type: "integer" }
2754
+ }
2755
+ }
2756
+ }
2757
+ }
2758
+ }
2759
+ }
2760
+ }
2761
+ };
2762
+ for (const collection of config.collections) {
2763
+ spec.components.schemas[collection.slug] = collectionToSchema(collection);
2764
+ }
2765
+ for (const global of config.globals) {
2766
+ spec.components.schemas[global.slug] = globalToSchema(global);
2767
+ }
2768
+ for (const collection of config.collections) {
2769
+ const slug = collection.slug;
2770
+ const path = `/api/collections/${slug}`;
2771
+ const labels = getCollectionLabels(collection);
2772
+ const collectionTag = getCollectionTag(collection);
2773
+ spec.paths[path] = {
2774
+ get: {
2775
+ tags: [collectionTag],
2776
+ summary: `Find ${labels.plural}`,
2777
+ parameters: [
2778
+ {
2779
+ name: "limit",
2780
+ in: "query",
2781
+ schema: { type: "integer", default: 10 }
2782
+ },
2783
+ {
2784
+ name: "page",
2785
+ in: "query",
2786
+ schema: { type: "integer", default: 1 }
2787
+ },
2788
+ {
2789
+ name: "where",
2790
+ in: "query",
2791
+ schema: { type: "string" },
2792
+ description: "JSON filter"
2793
+ },
2794
+ {
2795
+ name: "search",
2796
+ in: "query",
2797
+ schema: { type: "string" },
2798
+ description: "Free-text search across configured searchable fields"
2799
+ },
2800
+ {
2801
+ name: "sort",
2802
+ in: "query",
2803
+ schema: { type: "string" },
2804
+ description: "Sort field (e.g. -createdAt)"
2805
+ }
2806
+ ],
2807
+ responses: {
2808
+ 200: {
2809
+ description: "Success",
2810
+ content: {
2811
+ "application/json": {
2812
+ schema: {
2813
+ type: "object",
2814
+ properties: {
2815
+ docs: {
2816
+ type: "array",
2817
+ items: { $ref: `#/components/schemas/${slug}` }
2818
+ },
2819
+ total: { type: "integer" },
2820
+ limit: { type: "integer" },
2821
+ page: { type: "integer" }
2822
+ }
2823
+ }
2824
+ }
2825
+ }
2826
+ }
2827
+ }
2828
+ },
2829
+ post: {
2830
+ tags: [collectionTag],
2831
+ summary: `Create ${labels.singular}`,
2832
+ requestBody: {
2833
+ required: true,
2834
+ content: {
2835
+ "application/json": {
2836
+ schema: { $ref: `#/components/schemas/${slug}` }
2837
+ }
2838
+ }
2839
+ },
2840
+ responses: {
2841
+ 201: {
2842
+ description: "Created",
2843
+ content: {
2844
+ "application/json": {
2845
+ schema: { $ref: `#/components/schemas/${slug}` }
2846
+ }
2847
+ }
2848
+ }
2849
+ }
2850
+ }
2851
+ };
2852
+ spec.paths[`${path}/{id}`] = {
2853
+ get: {
2854
+ tags: [collectionTag],
2855
+ summary: `Get a single ${labels.singular}`,
2856
+ parameters: [
2857
+ {
2858
+ name: "id",
2859
+ in: "path",
2860
+ required: true,
2861
+ schema: { type: "string" }
2862
+ }
2863
+ ],
2864
+ responses: {
2865
+ 200: {
2866
+ description: "Success",
2867
+ content: {
2868
+ "application/json": {
2869
+ schema: { $ref: `#/components/schemas/${slug}` }
2870
+ }
2871
+ }
2872
+ }
2873
+ }
2874
+ },
2875
+ patch: {
2876
+ tags: [collectionTag],
2877
+ summary: `Update ${labels.singular}`,
2878
+ parameters: [
2879
+ {
2880
+ name: "id",
2881
+ in: "path",
2882
+ required: true,
2883
+ schema: { type: "string" }
2884
+ }
2885
+ ],
2886
+ requestBody: {
2887
+ required: true,
2888
+ content: {
2889
+ "application/json": {
2890
+ schema: { $ref: `#/components/schemas/${slug}` }
2891
+ }
2892
+ }
2893
+ },
2894
+ responses: {
2895
+ 200: {
2896
+ description: "Updated",
2897
+ content: {
2898
+ "application/json": {
2899
+ schema: { $ref: `#/components/schemas/${slug}` }
2900
+ }
2901
+ }
2902
+ }
2903
+ }
2904
+ },
2905
+ delete: {
2906
+ tags: [collectionTag],
2907
+ summary: `Delete ${labels.singular}`,
2908
+ parameters: [
2909
+ {
2910
+ name: "id",
2911
+ in: "path",
2912
+ required: true,
2913
+ schema: { type: "string" }
2914
+ }
2915
+ ],
2916
+ responses: {
2917
+ 204: { description: "Deleted" }
2918
+ }
2919
+ }
2920
+ };
2921
+ spec.paths[`${path}/delete-many`] = {
2922
+ delete: {
2923
+ tags: [collectionTag],
2924
+ summary: `Delete multiple ${labels.plural}`,
2925
+ requestBody: {
2926
+ required: true,
2927
+ content: {
2928
+ "application/json": {
2929
+ schema: {
2930
+ type: "object",
2931
+ required: ["ids"],
2932
+ properties: {
2933
+ ids: { type: "array", items: { type: "string" } }
2934
+ }
2935
+ }
2936
+ }
2937
+ }
2938
+ },
2939
+ responses: { 200: { description: "Deleted and failed document IDs" } }
2940
+ }
2941
+ };
2942
+ if (collection.audit) {
2943
+ spec.paths[`${path}/__audit`] = {
2944
+ get: {
2945
+ tags: [collectionTag],
2946
+ summary: `Get ${labels.singular} audit entries`,
2947
+ parameters: [
2948
+ {
2949
+ name: "limit",
2950
+ in: "query",
2951
+ schema: { type: "integer", default: 50, maximum: 100 }
2952
+ },
2953
+ {
2954
+ name: "page",
2955
+ in: "query",
2956
+ schema: { type: "integer", default: 1 }
2957
+ },
2958
+ {
2959
+ name: "where",
2960
+ in: "query",
2961
+ schema: { type: "string" },
2962
+ description: "JSON filter"
2963
+ },
2964
+ {
2965
+ name: "sort",
2966
+ in: "query",
2967
+ schema: { type: "string", default: "-timestamp" }
2968
+ }
2969
+ ],
2970
+ responses: {
2971
+ 200: {
2972
+ description: "Audit entries for this collection",
2973
+ content: {
2974
+ "application/json": {
2975
+ schema: {
2976
+ type: "object",
2977
+ properties: {
2978
+ docs: {
2979
+ type: "array",
2980
+ items: { $ref: "#/components/schemas/AuditEntry" }
2981
+ },
2982
+ total: { type: "integer" },
2983
+ limit: { type: "integer" },
2984
+ page: { type: "integer" }
2985
+ }
2986
+ }
2987
+ }
2988
+ }
2989
+ },
2990
+ 403: { description: "Collection read access denied" },
2991
+ 404: { description: "Audit is not enabled for this collection" }
2992
+ }
2993
+ }
2994
+ };
2995
+ }
2996
+ if (collection.upload) {
2997
+ spec.paths[`${path}/media`] = {
2998
+ get: {
2999
+ tags: [collectionTag],
3000
+ summary: `List ${labels.plural}`,
3001
+ responses: { 200: { description: "Paginated media documents" } }
3002
+ },
3003
+ post: {
3004
+ tags: [collectionTag],
3005
+ summary: `Upload ${labels.singular}`,
3006
+ requestBody: {
3007
+ required: true,
3008
+ content: {
3009
+ "multipart/form-data": {
3010
+ schema: {
3011
+ type: "object",
3012
+ required: ["file"],
3013
+ properties: { file: { type: "string", format: "binary" } }
3014
+ }
3015
+ }
3016
+ }
3017
+ },
3018
+ responses: { 201: { description: "Uploaded media document" } }
3019
+ }
3020
+ };
3021
+ spec.paths[`${path}/media/{filename}`] = {
3022
+ get: {
3023
+ tags: [collectionTag],
3024
+ summary: `Serve ${labels.singular} bytes`,
3025
+ parameters: [
3026
+ {
3027
+ name: "filename",
3028
+ in: "path",
3029
+ required: true,
3030
+ schema: { type: "string" }
3031
+ }
3032
+ ],
3033
+ security: [],
3034
+ responses: {
3035
+ 200: { description: "Stored file" },
3036
+ 404: { description: "File not found" }
3037
+ }
3038
+ }
3039
+ };
3040
+ }
3041
+ if (collection.auth) {
3042
+ const publicAuthPost = (summary) => ({
3043
+ tags: [collectionTag],
3044
+ summary,
3045
+ security: [],
3046
+ requestBody: {
3047
+ required: true,
3048
+ content: {
3049
+ "application/json": {
3050
+ schema: { type: "object", additionalProperties: true }
3051
+ }
3052
+ }
3053
+ },
3054
+ responses: {
3055
+ 200: { description: "Success" },
3056
+ 400: { description: "Invalid request" }
3057
+ }
3058
+ });
3059
+ spec.paths[`${path}/login`] = {
3060
+ post: {
3061
+ ...publicAuthPost(`Log in to ${labels.plural}`),
3062
+ requestBody: {
3063
+ required: true,
3064
+ content: {
3065
+ "application/json": {
3066
+ schema: { $ref: "#/components/schemas/AuthCredentials" }
3067
+ }
3068
+ }
3069
+ },
3070
+ responses: {
3071
+ 200: {
3072
+ description: "Authenticated",
3073
+ content: {
3074
+ "application/json": {
3075
+ schema: { $ref: "#/components/schemas/TokenResponse" }
3076
+ }
3077
+ }
3078
+ },
3079
+ 401: { description: "Invalid credentials" }
3080
+ }
3081
+ }
3082
+ };
3083
+ spec.paths[`${path}/logout`] = {
3084
+ post: {
3085
+ tags: [collectionTag],
3086
+ summary: `Log out of ${labels.plural}`,
3087
+ parameters: [
3088
+ {
3089
+ name: "allSessions",
3090
+ in: "query",
3091
+ required: false,
3092
+ schema: { type: "boolean" },
3093
+ description: "Revoke every active session for this account instead of only the current one."
3094
+ }
3095
+ ],
3096
+ responses: { 200: { description: "Logged out" } }
3097
+ }
3098
+ };
3099
+ spec.paths[`${path}/init`] = {
3100
+ get: {
3101
+ tags: [collectionTag],
3102
+ summary: `Get ${labels.plural} initialization state`,
3103
+ security: [],
3104
+ responses: { 200: { description: "Initialization state" } }
3105
+ }
3106
+ };
3107
+ spec.paths[`${path}/first-user`] = {
3108
+ post: publicAuthPost(`Register the first ${labels.singular}`)
3109
+ };
3110
+ spec.paths[`${path}/me`] = {
3111
+ get: {
3112
+ tags: [collectionTag],
3113
+ summary: `Get the current ${labels.singular}`,
3114
+ responses: { 200: { description: "Authenticated user" } }
3115
+ }
3116
+ };
3117
+ spec.paths[`${path}/refresh-token`] = {
3118
+ post: {
3119
+ tags: [collectionTag],
3120
+ summary: "Refresh an authentication token",
3121
+ responses: {
3122
+ 200: {
3123
+ description: "Refreshed token for the current active session"
3124
+ }
3125
+ }
3126
+ }
3127
+ };
3128
+ spec.paths[`${path}/forgot-password`] = {
3129
+ post: publicAuthPost("Request a password reset")
3130
+ };
3131
+ spec.paths[`${path}/reset-password`] = {
3132
+ post: publicAuthPost("Reset a password")
3133
+ };
3134
+ spec.paths[`${path}/invite`] = {
3135
+ post: {
3136
+ tags: [collectionTag],
3137
+ summary: `Invite a ${labels.singular}`,
3138
+ responses: { 200: { description: "Invitation sent" } }
3139
+ }
3140
+ };
3141
+ spec.paths[`${path}/accept-invite`] = {
3142
+ post: publicAuthPost("Accept an invitation")
3143
+ };
3144
+ spec.paths[`${path}/{id}/change-password`] = {
3145
+ post: {
3146
+ tags: [collectionTag],
3147
+ summary: `Change a ${labels.singular} password`,
3148
+ parameters: [
3149
+ {
3150
+ name: "id",
3151
+ in: "path",
3152
+ required: true,
3153
+ schema: { type: "string" }
3154
+ }
3155
+ ],
3156
+ responses: {
3157
+ 200: {
3158
+ description: "Password changed and active sessions revoked"
3159
+ }
3160
+ }
3161
+ }
3162
+ };
3163
+ }
3164
+ if (collection.workflow) {
3165
+ spec.paths[`${path}/{id}/transitions/{transition}`] = {
3166
+ post: {
3167
+ tags: [collectionTag],
3168
+ summary: `Transition ${labels.singular} workflow`,
3169
+ parameters: [
3170
+ {
3171
+ name: "id",
3172
+ in: "path",
3173
+ required: true,
3174
+ schema: { type: "string" }
3175
+ },
3176
+ {
3177
+ name: "transition",
3178
+ in: "path",
3179
+ required: true,
3180
+ schema: {
3181
+ type: "string",
3182
+ enum: collection.workflow.transitions.map((item) => item.name)
3183
+ }
3184
+ }
3185
+ ],
3186
+ requestBody: {
3187
+ content: {
3188
+ "application/json": {
3189
+ schema: {
3190
+ $ref: "#/components/schemas/WorkflowTransitionRequest"
3191
+ }
3192
+ }
3193
+ }
3194
+ },
3195
+ responses: {
3196
+ 200: {
3197
+ description: "Transition applied",
3198
+ content: {
3199
+ "application/json": {
3200
+ schema: { $ref: `#/components/schemas/${slug}` }
3201
+ }
3202
+ }
3203
+ },
3204
+ 400: { description: "Required transition input is missing" },
3205
+ 403: { description: "Transition capability denied" },
3206
+ 409: { description: "Invalid state or stale revision" }
3207
+ }
3208
+ }
3209
+ };
3210
+ spec.paths[`${path}/{id}/workflow-history`] = {
3211
+ get: {
3212
+ tags: [collectionTag],
3213
+ summary: `Get ${labels.singular} workflow history`,
3214
+ parameters: [
3215
+ {
3216
+ name: "id",
3217
+ in: "path",
3218
+ required: true,
3219
+ schema: { type: "string" }
3220
+ },
3221
+ {
3222
+ name: "limit",
3223
+ in: "query",
3224
+ schema: { type: "integer", default: 50, maximum: 100 }
3225
+ }
3226
+ ],
3227
+ responses: {
3228
+ 200: {
3229
+ description: "Workflow transition history",
3230
+ content: {
3231
+ "application/json": {
3232
+ schema: {
3233
+ type: "object",
3234
+ properties: {
3235
+ docs: {
3236
+ type: "array",
3237
+ items: {
3238
+ $ref: "#/components/schemas/WorkflowHistoryEntry"
3239
+ }
3240
+ },
3241
+ total: { type: "integer" },
3242
+ limit: { type: "integer" },
3243
+ page: { type: "integer" }
3244
+ }
3245
+ }
3246
+ }
3247
+ }
3248
+ },
3249
+ 403: { description: "Collection read access denied" }
3250
+ }
3251
+ }
3252
+ };
3253
+ }
3254
+ }
3255
+ for (const global of config.globals) {
3256
+ const slug = global.slug;
3257
+ const path = `/api/globals/${slug}`;
3258
+ const globalTag = getGlobalTag(global);
3259
+ spec.paths[path] = {
3260
+ get: {
3261
+ tags: [globalTag],
3262
+ summary: `Get ${global.label || slug}`,
3263
+ responses: {
3264
+ 200: {
3265
+ description: "Success",
3266
+ content: {
3267
+ "application/json": {
3268
+ schema: { $ref: `#/components/schemas/${slug}` }
3269
+ }
3270
+ }
3271
+ }
3272
+ }
3273
+ },
3274
+ patch: {
3275
+ tags: [globalTag],
3276
+ summary: `Update ${global.label || slug}`,
3277
+ requestBody: {
3278
+ required: true,
3279
+ content: {
3280
+ "application/json": {
3281
+ schema: { $ref: `#/components/schemas/${slug}` }
3282
+ }
3283
+ }
3284
+ },
3285
+ responses: {
3286
+ 200: {
3287
+ description: "Updated",
3288
+ content: {
3289
+ "application/json": {
3290
+ schema: { $ref: `#/components/schemas/${slug}` }
3291
+ }
3292
+ }
3293
+ }
3294
+ }
3295
+ }
3296
+ };
3297
+ }
3298
+ if (config.storage) {
3299
+ spec.paths["/api/media/{filename}"] = {
3300
+ get: {
3301
+ tags: ["Media"],
3302
+ summary: "Serve a stored file",
3303
+ security: [],
3304
+ parameters: [
3305
+ {
3306
+ name: "filename",
3307
+ in: "path",
3308
+ required: true,
3309
+ schema: { type: "string" }
3310
+ }
3311
+ ],
3312
+ responses: {
3313
+ 200: { description: "Stored file bytes" },
3314
+ 404: { description: "File not found" }
3315
+ }
3316
+ }
3317
+ };
3318
+ }
3319
+ return spec;
3320
+ }
3321
+ function collectionToSchema(collection) {
3322
+ const { properties, required } = fieldsToProperties(collection.fields);
3323
+ return {
3324
+ type: "object",
3325
+ properties: {
3326
+ id: { type: "string" },
3327
+ createdAt: { type: "string", format: "date-time" },
3328
+ updatedAt: { type: "string", format: "date-time" },
3329
+ ...collection.workflow ? { _workflow: { $ref: "#/components/schemas/WorkflowMetadata" } } : {},
3330
+ ...properties
3331
+ },
3332
+ required: ["id", ...required]
3333
+ };
3334
+ }
3335
+ function globalToSchema(global) {
3336
+ const { properties, required } = fieldsToProperties(global.fields);
3337
+ return {
3338
+ type: "object",
3339
+ properties,
3340
+ required
3341
+ };
3342
+ }
3343
+ function fieldsToProperties(fields) {
3344
+ const props = {};
3345
+ const required = [];
3346
+ for (const field of fields) {
3347
+ if (field.type === "row") {
3348
+ const nested = fieldsToProperties(field.fields || []);
3349
+ Object.assign(props, nested.properties);
3350
+ required.push(...nested.required);
3351
+ continue;
3352
+ }
3353
+ if (!field.name) continue;
3354
+ props[field.name] = fieldToSchema(field);
3355
+ if (field.required) {
3356
+ required.push(field.name);
3357
+ }
3358
+ }
3359
+ return { properties: props, required };
3360
+ }
3361
+ function fieldToSchema(field) {
3362
+ let schema;
3363
+ switch (field.type) {
3364
+ case "text":
3365
+ case "textarea":
3366
+ case "email":
3367
+ schema = { type: "string" };
3368
+ break;
3369
+ case "url":
3370
+ schema = {
3371
+ oneOf: [
3372
+ { type: "string" },
3373
+ { type: "object", additionalProperties: true }
3374
+ ]
3375
+ };
3376
+ break;
3377
+ case "icon":
3378
+ schema = { type: "string" };
3379
+ break;
3380
+ case "number":
3381
+ schema = { type: "number" };
3382
+ break;
3383
+ case "boolean":
3384
+ schema = { type: "boolean" };
3385
+ break;
3386
+ case "date":
3387
+ schema = { type: "string", format: "date" };
3388
+ break;
3389
+ case "datetime":
3390
+ schema = { type: "string", format: "date-time" };
3391
+ break;
3392
+ case "time":
3393
+ schema = { type: "string", format: "time" };
3394
+ break;
3395
+ case "select":
3396
+ case "radio":
3397
+ schema = {
3398
+ type: "string",
3399
+ enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0
3400
+ };
3401
+ break;
3402
+ case "multiSelect":
3403
+ schema = {
3404
+ type: "array",
3405
+ items: {
3406
+ type: "string",
3407
+ enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0
3408
+ }
3409
+ };
3410
+ break;
3411
+ case "relationship":
3412
+ case "image": {
3413
+ const valueSchema = {
3414
+ type: "string",
3415
+ description: `ID of a ${field.relationTo} record`
3416
+ };
3417
+ schema = field.hasMany ? { type: "array", items: valueSchema } : valueSchema;
3418
+ break;
3419
+ }
3420
+ case "join":
3421
+ schema = {
3422
+ type: "array",
3423
+ readOnly: true,
3424
+ items: { type: "object", additionalProperties: true }
3425
+ };
3426
+ break;
3427
+ case "object": {
3428
+ const { properties, required } = fieldsToProperties(field.fields || []);
3429
+ schema = { type: "object", properties, required };
3430
+ break;
3431
+ }
3432
+ case "array": {
3433
+ const { properties, required } = fieldsToProperties(field.fields || []);
3434
+ schema = {
3435
+ type: "array",
3436
+ items: { type: "object", properties, required }
3437
+ };
3438
+ break;
3439
+ }
3440
+ case "json":
3441
+ case "richText":
3442
+ schema = { type: "object", additionalProperties: true };
3443
+ break;
3444
+ case "blocks":
3445
+ schema = {
3446
+ type: "array",
3447
+ items: {
3448
+ oneOf: field.blocks?.map((block) => {
3449
+ const { properties, required } = fieldsToProperties(block.fields);
3450
+ return {
3451
+ type: "object",
3452
+ properties: {
3453
+ blockType: { type: "string", enum: [block.slug] },
3454
+ ...properties
3455
+ },
3456
+ required: ["blockType", ...required]
3457
+ };
3458
+ })
3459
+ }
3460
+ };
3461
+ break;
3462
+ default:
3463
+ schema = { type: "string" };
3464
+ }
3465
+ if (field.label) schema.description = field.label;
3466
+ return schema;
3467
+ }
3468
+
3469
+ export {
3470
+ signCollectionToken,
3471
+ verifyCollectionToken,
3472
+ issueAuthSessionToken,
3473
+ getAuthSession,
3474
+ isAuthSessionActive,
3475
+ touchAuthSession,
3476
+ revokeAuthSession,
3477
+ revokeAllAuthSessions,
3478
+ createObservabilityRuntime,
3479
+ bindObservabilityRuntime,
3480
+ getObservabilityRuntime,
3481
+ getConfigLogger,
3482
+ getRequestLogger,
3483
+ buildRequestLogger,
3484
+ shouldSampleRequest,
3485
+ redactHeaders,
3486
+ captureRequestBody,
3487
+ createRequestSpan,
3488
+ endRequestSpan,
3489
+ attachRequestMetrics,
3490
+ renderPrometheusMetrics,
3491
+ WORKFLOW_HISTORY_COLLECTION,
3492
+ LIFECYCLE_EVENTS_COLLECTION,
3493
+ definePublishingWorkflow,
3494
+ publishingWorkflow,
3495
+ simplePublishingWorkflow,
3496
+ workflowCapabilities,
3497
+ canViewWorkflowDraft,
3498
+ availableWorkflowTransitions,
3499
+ initializeWorkflowDocument,
3500
+ publishedStateName,
3501
+ materializeWorkflowDocument,
3502
+ createLifecycleEvent,
3503
+ dispatchLifecycleEvent,
3504
+ dispatchPendingLifecycleEvents,
3505
+ saveWorkflowDraft,
3506
+ createWorkflowDocument,
3507
+ transitionWorkflow,
3508
+ getAdminAuthCollection,
3509
+ resolveAdminAuthCollection,
3510
+ getPublicAdminAuthConfig,
3511
+ mergeDynamicConfig,
3512
+ registerJexlHelpers,
3513
+ BUILTIN_JEXL_HELPERS,
3514
+ validateDeclarativeHookExpression,
3515
+ validateDeclarativeAccessExpression,
3516
+ validateAdminConditionExpression,
3517
+ validatePreviewUrlExpression,
3518
+ assertValidDeclarativeHookExpression,
3519
+ assertValidDeclarativeHookResult,
3520
+ collectDeclarativeHookValidationIssues,
3521
+ collectDeclarativeAccessValidationIssues,
3522
+ collectAdminConditionValidationIssues,
3523
+ collectPreviewUrlValidationIssues,
3524
+ assertValidAdminConditionsInConfig,
3525
+ assertValidPreviewUrlsInConfig,
3526
+ collectConfigDiagnostics,
3527
+ formatConfigDiagnostics,
3528
+ ConfigValidationError,
3529
+ isConfigValidationError,
3530
+ assertValidDeclarativeHooksInConfig,
3531
+ assertValidDeclarativeAccessInConfig,
3532
+ normalizeConfig,
3533
+ runCollectionHooks,
3534
+ executeFieldBeforeChange,
3535
+ executeFieldAfterRead,
3536
+ generateOpenApi
3537
+ };