@dyrected/core 2.5.61 → 2.5.63
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app-config-BcuZIpvL.d.cts +1951 -0
- package/dist/app-config-BcuZIpvL.d.ts +1951 -0
- package/dist/app-config-Bm9-2Am6.d.cts +1875 -0
- package/dist/app-config-Bm9-2Am6.d.ts +1875 -0
- package/dist/app-config-CJAGGPrk.d.cts +1900 -0
- package/dist/app-config-CJAGGPrk.d.ts +1900 -0
- package/dist/app-config-CiEDJm0e.d.cts +1912 -0
- package/dist/app-config-CiEDJm0e.d.ts +1912 -0
- package/dist/app-config-DCDh8Gbx.d.cts +1926 -0
- package/dist/app-config-DCDh8Gbx.d.ts +1926 -0
- package/dist/app-config-Dv5XACR4.d.cts +2065 -0
- package/dist/app-config-Dv5XACR4.d.ts +2065 -0
- package/dist/app-config-_kkj71CB.d.cts +2010 -0
- package/dist/app-config-_kkj71CB.d.ts +2010 -0
- package/dist/app-config-tITj_0sn.d.cts +1926 -0
- package/dist/app-config-tITj_0sn.d.ts +1926 -0
- package/dist/chunk-57FNM42D.js +2392 -0
- package/dist/chunk-BAMX7YUC.js +1815 -0
- package/dist/chunk-BQV3QW3Y.js +2588 -0
- package/dist/chunk-EH3MJGB5.js +2571 -0
- package/dist/chunk-M3HKRN7E.js +1665 -0
- package/dist/chunk-MQZH7RQC.js +1667 -0
- package/dist/chunk-T626OZMH.js +2602 -0
- package/dist/chunk-TEGRS6J7.js +2609 -0
- package/dist/chunk-VCYYBN5J.js +1873 -0
- package/dist/chunk-WVD7PORQ.js +1672 -0
- package/dist/chunk-XZLIBQSO.js +2397 -0
- package/dist/index.cjs +364 -45
- package/dist/index.d.cts +36 -4
- package/dist/index.d.ts +36 -4
- package/dist/index.js +5 -1
- package/dist/server.cjs +2981 -716
- package/dist/server.d.cts +124 -12
- package/dist/server.d.ts +124 -12
- package/dist/server.js +2085 -703
- package/package.json +10 -1
|
@@ -0,0 +1,2609 @@
|
|
|
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 now = Date.now();
|
|
675
|
+
const due = result.docs.filter(
|
|
676
|
+
(doc) => Number(doc.attempts ?? 0) < maxAttempts && (!doc.nextAttemptAt || new Date(doc.nextAttemptAt).getTime() <= now)
|
|
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 now = (/* @__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: now, 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: now }
|
|
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: now, 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/auth/token.ts
|
|
865
|
+
import { SignJWT, jwtVerify, decodeJwt } from "jose";
|
|
866
|
+
import { TextEncoder } from "util";
|
|
867
|
+
function getSecret() {
|
|
868
|
+
const secret = process.env.DYRECTED_JWT_SECRET;
|
|
869
|
+
if (!secret) {
|
|
870
|
+
throw new Error(
|
|
871
|
+
"[dyrected/core] DYRECTED_JWT_SECRET is not set. Add it to your environment variables to enable auth collections."
|
|
872
|
+
);
|
|
873
|
+
}
|
|
874
|
+
return new TextEncoder().encode(secret);
|
|
875
|
+
}
|
|
876
|
+
var DEFAULT_EXPIRY = "7d";
|
|
877
|
+
async function signCollectionToken(payload, expiresIn = DEFAULT_EXPIRY) {
|
|
878
|
+
return new SignJWT({ ...payload }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(expiresIn).sign(getSecret());
|
|
879
|
+
}
|
|
880
|
+
async function verifyCollectionToken(token) {
|
|
881
|
+
const { payload } = await jwtVerify(token, getSecret());
|
|
882
|
+
return payload;
|
|
883
|
+
}
|
|
884
|
+
function decodeCollectionToken(token) {
|
|
885
|
+
try {
|
|
886
|
+
return decodeJwt(token);
|
|
887
|
+
} catch {
|
|
888
|
+
return null;
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
// src/auth/sessions.ts
|
|
893
|
+
var AUTH_SESSIONS_COLLECTION = "__auth_sessions";
|
|
894
|
+
async function issueAuthSessionToken(args) {
|
|
895
|
+
const sessionId = createSessionId();
|
|
896
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
897
|
+
const db = args.config.db;
|
|
898
|
+
if (db) {
|
|
899
|
+
await db.create({
|
|
900
|
+
collection: AUTH_SESSIONS_COLLECTION,
|
|
901
|
+
data: {
|
|
902
|
+
id: sessionId,
|
|
903
|
+
userId: args.userId,
|
|
904
|
+
email: args.email,
|
|
905
|
+
collection: args.collection,
|
|
906
|
+
authSource: args.authSource ?? "local",
|
|
907
|
+
providerId: args.providerId,
|
|
908
|
+
lastIp: args.ip,
|
|
909
|
+
lastSeenAt: now,
|
|
910
|
+
revokedAt: null,
|
|
911
|
+
expiresAt: null
|
|
912
|
+
}
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
const token = await signCollectionToken(
|
|
916
|
+
{
|
|
917
|
+
sub: args.userId,
|
|
918
|
+
email: args.email,
|
|
919
|
+
collection: args.collection,
|
|
920
|
+
authSource: args.authSource,
|
|
921
|
+
providerId: args.providerId,
|
|
922
|
+
sid: sessionId
|
|
923
|
+
},
|
|
924
|
+
args.expiresIn
|
|
925
|
+
);
|
|
926
|
+
const payload = decodeCollectionToken(token);
|
|
927
|
+
const expiresAt = payload?.exp != null ? new Date(payload.exp * 1e3).toISOString() : null;
|
|
928
|
+
if (db && expiresAt) {
|
|
929
|
+
await db.update({
|
|
930
|
+
collection: AUTH_SESSIONS_COLLECTION,
|
|
931
|
+
id: sessionId,
|
|
932
|
+
data: {
|
|
933
|
+
expiresAt,
|
|
934
|
+
lastSeenAt: now,
|
|
935
|
+
lastIp: args.ip
|
|
936
|
+
}
|
|
937
|
+
});
|
|
938
|
+
}
|
|
939
|
+
return token;
|
|
940
|
+
}
|
|
941
|
+
async function getAuthSession(config, sessionId) {
|
|
942
|
+
const db = config.db;
|
|
943
|
+
if (!db) return null;
|
|
944
|
+
return await db.findOne({
|
|
945
|
+
collection: AUTH_SESSIONS_COLLECTION,
|
|
946
|
+
id: sessionId
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
function isAuthSessionActive(session) {
|
|
950
|
+
if (!session) return false;
|
|
951
|
+
if (session.revokedAt) return false;
|
|
952
|
+
if (session.expiresAt && new Date(session.expiresAt).getTime() <= Date.now()) {
|
|
953
|
+
return false;
|
|
954
|
+
}
|
|
955
|
+
return true;
|
|
956
|
+
}
|
|
957
|
+
async function touchAuthSession(config, sessionId, args) {
|
|
958
|
+
const db = config.db;
|
|
959
|
+
if (!db) return;
|
|
960
|
+
await db.update({
|
|
961
|
+
collection: AUTH_SESSIONS_COLLECTION,
|
|
962
|
+
id: sessionId,
|
|
963
|
+
data: {
|
|
964
|
+
lastSeenAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
965
|
+
...args.ip ? { lastIp: args.ip } : {}
|
|
966
|
+
}
|
|
967
|
+
});
|
|
968
|
+
}
|
|
969
|
+
async function revokeAuthSession(config, sessionId) {
|
|
970
|
+
const db = config.db;
|
|
971
|
+
if (!db) return;
|
|
972
|
+
await db.update({
|
|
973
|
+
collection: AUTH_SESSIONS_COLLECTION,
|
|
974
|
+
id: sessionId,
|
|
975
|
+
data: {
|
|
976
|
+
revokedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
977
|
+
}
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
async function revokeAllAuthSessions(config, args) {
|
|
981
|
+
const db = config.db;
|
|
982
|
+
if (!db) return 0;
|
|
983
|
+
let page = 1;
|
|
984
|
+
let revoked = 0;
|
|
985
|
+
while (true) {
|
|
986
|
+
const result = await db.find({
|
|
987
|
+
collection: AUTH_SESSIONS_COLLECTION,
|
|
988
|
+
where: {
|
|
989
|
+
userId: { equals: args.userId },
|
|
990
|
+
collection: { equals: args.collection }
|
|
991
|
+
},
|
|
992
|
+
page,
|
|
993
|
+
limit: 100
|
|
994
|
+
});
|
|
995
|
+
for (const session of result.docs) {
|
|
996
|
+
if (session.revokedAt) continue;
|
|
997
|
+
await revokeAuthSession(config, session.id);
|
|
998
|
+
revoked += 1;
|
|
999
|
+
}
|
|
1000
|
+
if (!result.hasNextPage) break;
|
|
1001
|
+
page += 1;
|
|
1002
|
+
}
|
|
1003
|
+
return revoked;
|
|
1004
|
+
}
|
|
1005
|
+
function createSessionId() {
|
|
1006
|
+
return globalThis.crypto?.randomUUID?.() ? globalThis.crypto.randomUUID() : `sess_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
// src/utils/block-references.ts
|
|
1010
|
+
function mergeUniqueBlocks(blocks) {
|
|
1011
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1012
|
+
for (const block of blocks) {
|
|
1013
|
+
const existing = seen.get(block.slug);
|
|
1014
|
+
if (existing && existing !== block) {
|
|
1015
|
+
throw new Error(
|
|
1016
|
+
`Duplicate block slug "${block.slug}" found in the reusable block registry. Block slugs must be unique.`
|
|
1017
|
+
);
|
|
1018
|
+
}
|
|
1019
|
+
if (!existing) seen.set(block.slug, block);
|
|
1020
|
+
}
|
|
1021
|
+
return Array.from(seen.values());
|
|
1022
|
+
}
|
|
1023
|
+
function buildRegistry(blocks) {
|
|
1024
|
+
return new Map(blocks.map((block) => [block.slug, block]));
|
|
1025
|
+
}
|
|
1026
|
+
function resolveField(field, registry, blockCache) {
|
|
1027
|
+
const next = { ...field };
|
|
1028
|
+
if (next.fields) {
|
|
1029
|
+
next.fields = next.fields.map(
|
|
1030
|
+
(child) => resolveField(child, registry, blockCache)
|
|
1031
|
+
);
|
|
1032
|
+
}
|
|
1033
|
+
if (next.type !== "blocks") return next;
|
|
1034
|
+
const hasInlineBlocks = Array.isArray(next.blocks) && next.blocks.length > 0;
|
|
1035
|
+
const hasReferences = Array.isArray(next.blockReferences) && next.blockReferences.length > 0;
|
|
1036
|
+
if (hasInlineBlocks && hasReferences) {
|
|
1037
|
+
throw new Error(
|
|
1038
|
+
`Blocks field "${next.name ?? "(unnamed)"}" cannot define both "blocks" and "blockReferences". Use one or the other.`
|
|
1039
|
+
);
|
|
1040
|
+
}
|
|
1041
|
+
if (hasReferences) {
|
|
1042
|
+
next.blocks = next.blockReferences.map((slug) => {
|
|
1043
|
+
const block = registry.get(slug);
|
|
1044
|
+
if (!block) {
|
|
1045
|
+
throw new Error(
|
|
1046
|
+
`Unknown block reference "${slug}" on blocks field "${next.name ?? "(unnamed)"}". Add it to defineConfig({ blocks: [...] }).`
|
|
1047
|
+
);
|
|
1048
|
+
}
|
|
1049
|
+
return resolveBlock(block, registry, blockCache);
|
|
1050
|
+
});
|
|
1051
|
+
return next;
|
|
1052
|
+
}
|
|
1053
|
+
if (hasInlineBlocks) {
|
|
1054
|
+
next.blocks = next.blocks.map(
|
|
1055
|
+
(block) => resolveBlock(block, registry, blockCache)
|
|
1056
|
+
);
|
|
1057
|
+
}
|
|
1058
|
+
return next;
|
|
1059
|
+
}
|
|
1060
|
+
function resolveBlock(block, registry, blockCache) {
|
|
1061
|
+
const cached = blockCache.get(block);
|
|
1062
|
+
if (cached) return cached;
|
|
1063
|
+
const resolved = {
|
|
1064
|
+
...block,
|
|
1065
|
+
fields: []
|
|
1066
|
+
};
|
|
1067
|
+
blockCache.set(block, resolved);
|
|
1068
|
+
resolved.fields = block.fields.map(
|
|
1069
|
+
(field) => resolveField(field, registry, blockCache)
|
|
1070
|
+
);
|
|
1071
|
+
return resolved;
|
|
1072
|
+
}
|
|
1073
|
+
function resolveFields(fields, registry, blockCache) {
|
|
1074
|
+
return fields.map((field) => resolveField(field, registry, blockCache));
|
|
1075
|
+
}
|
|
1076
|
+
function normalizeSchemaFragment(fragment) {
|
|
1077
|
+
const reusableBlocks = mergeUniqueBlocks(fragment.blocks ?? []);
|
|
1078
|
+
const registry = buildRegistry(reusableBlocks);
|
|
1079
|
+
const blockCache = /* @__PURE__ */ new WeakMap();
|
|
1080
|
+
const resolvedBlocks = reusableBlocks.map(
|
|
1081
|
+
(block) => resolveBlock(block, registry, blockCache)
|
|
1082
|
+
);
|
|
1083
|
+
const resolvedCollections = (fragment.collections ?? []).map(
|
|
1084
|
+
(collection) => ({
|
|
1085
|
+
...collection,
|
|
1086
|
+
fields: resolveFields(collection.fields ?? [], registry, blockCache)
|
|
1087
|
+
})
|
|
1088
|
+
);
|
|
1089
|
+
const resolvedGlobals = (fragment.globals ?? []).map((global) => ({
|
|
1090
|
+
...global,
|
|
1091
|
+
fields: resolveFields(global.fields ?? [], registry, blockCache)
|
|
1092
|
+
}));
|
|
1093
|
+
return {
|
|
1094
|
+
...fragment,
|
|
1095
|
+
...fragment.blocks ? { blocks: resolvedBlocks } : {},
|
|
1096
|
+
...fragment.collections ? { collections: resolvedCollections } : {},
|
|
1097
|
+
...fragment.globals ? { globals: resolvedGlobals } : {}
|
|
1098
|
+
};
|
|
1099
|
+
}
|
|
1100
|
+
function mergeDynamicConfig(baseConfig, dynamic) {
|
|
1101
|
+
const normalizedDynamic = normalizeSchemaFragment({
|
|
1102
|
+
...dynamic,
|
|
1103
|
+
blocks: [...baseConfig.blocks ?? [], ...dynamic.blocks ?? []]
|
|
1104
|
+
});
|
|
1105
|
+
return {
|
|
1106
|
+
...baseConfig,
|
|
1107
|
+
...normalizedDynamic.blocks ? { blocks: normalizedDynamic.blocks } : {},
|
|
1108
|
+
...dynamic.admin ? { admin: { ...baseConfig.admin, ...dynamic.admin } } : {},
|
|
1109
|
+
...dynamic.adminAuth ? { adminAuth: { ...baseConfig.adminAuth, ...dynamic.adminAuth } } : {},
|
|
1110
|
+
collections: normalizedDynamic.collections ? [...baseConfig.collections, ...normalizedDynamic.collections] : baseConfig.collections,
|
|
1111
|
+
globals: normalizedDynamic.globals ? [...baseConfig.globals, ...normalizedDynamic.globals] : baseConfig.globals
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
// src/utils/config.ts
|
|
1116
|
+
var AUDIT_COLLECTION_SLUG = "__audit";
|
|
1117
|
+
var SYSTEM_FIELDS = [
|
|
1118
|
+
{
|
|
1119
|
+
name: "createdAt",
|
|
1120
|
+
type: "date",
|
|
1121
|
+
label: "Created At",
|
|
1122
|
+
admin: { readOnly: true, hidden: true }
|
|
1123
|
+
},
|
|
1124
|
+
{
|
|
1125
|
+
name: "updatedAt",
|
|
1126
|
+
type: "date",
|
|
1127
|
+
label: "Updated At",
|
|
1128
|
+
admin: { readOnly: true, hidden: true }
|
|
1129
|
+
},
|
|
1130
|
+
{
|
|
1131
|
+
name: "createdBy",
|
|
1132
|
+
type: "text",
|
|
1133
|
+
label: "Created By",
|
|
1134
|
+
admin: { readOnly: true, hidden: true }
|
|
1135
|
+
},
|
|
1136
|
+
{
|
|
1137
|
+
name: "updatedBy",
|
|
1138
|
+
type: "text",
|
|
1139
|
+
label: "Updated By",
|
|
1140
|
+
admin: { readOnly: true, hidden: true }
|
|
1141
|
+
}
|
|
1142
|
+
];
|
|
1143
|
+
var AUDIT_COLLECTION = {
|
|
1144
|
+
slug: AUDIT_COLLECTION_SLUG,
|
|
1145
|
+
labels: { singular: "Audit Log", plural: "Audit Logs" },
|
|
1146
|
+
fields: [
|
|
1147
|
+
{ name: "collection", type: "text", label: "Collection", required: true },
|
|
1148
|
+
{ name: "documentId", type: "text", label: "Document ID" },
|
|
1149
|
+
{
|
|
1150
|
+
name: "operation",
|
|
1151
|
+
type: "select",
|
|
1152
|
+
label: "Operation",
|
|
1153
|
+
options: ["create", "update", "delete"],
|
|
1154
|
+
required: true
|
|
1155
|
+
},
|
|
1156
|
+
{ name: "user", type: "text", label: "User ID" },
|
|
1157
|
+
{ name: "timestamp", type: "date", label: "Timestamp", required: true },
|
|
1158
|
+
{ name: "changes", type: "json", label: "Changes" }
|
|
1159
|
+
],
|
|
1160
|
+
access: {
|
|
1161
|
+
read: () => false,
|
|
1162
|
+
create: () => false,
|
|
1163
|
+
update: () => false,
|
|
1164
|
+
delete: () => false
|
|
1165
|
+
},
|
|
1166
|
+
admin: { hidden: true }
|
|
1167
|
+
};
|
|
1168
|
+
var WORKFLOW_HISTORY_COLLECTION_CONFIG = {
|
|
1169
|
+
slug: WORKFLOW_HISTORY_COLLECTION,
|
|
1170
|
+
labels: { singular: "Workflow transition", plural: "Workflow transitions" },
|
|
1171
|
+
fields: [
|
|
1172
|
+
{ name: "collection", type: "text", required: true },
|
|
1173
|
+
{ name: "documentId", type: "text", required: true },
|
|
1174
|
+
{ name: "transition", type: "text", required: true },
|
|
1175
|
+
{ name: "from", type: "text", required: true },
|
|
1176
|
+
{ name: "to", type: "text", required: true },
|
|
1177
|
+
{ name: "revision", type: "number", required: true },
|
|
1178
|
+
{ name: "comment", type: "textarea" },
|
|
1179
|
+
{ name: "actorId", type: "text" },
|
|
1180
|
+
{ name: "createdAt", type: "date", required: true }
|
|
1181
|
+
],
|
|
1182
|
+
access: {
|
|
1183
|
+
read: ({ user }) => !!user,
|
|
1184
|
+
create: () => false,
|
|
1185
|
+
update: () => false,
|
|
1186
|
+
delete: () => false
|
|
1187
|
+
},
|
|
1188
|
+
admin: { hidden: true }
|
|
1189
|
+
};
|
|
1190
|
+
var LIFECYCLE_EVENTS_COLLECTION_CONFIG = {
|
|
1191
|
+
slug: LIFECYCLE_EVENTS_COLLECTION,
|
|
1192
|
+
labels: { singular: "Lifecycle event", plural: "Lifecycle events" },
|
|
1193
|
+
fields: [
|
|
1194
|
+
{ name: "name", type: "text", required: true },
|
|
1195
|
+
{ name: "collection", type: "text", required: true },
|
|
1196
|
+
{ name: "documentId", type: "text", required: true },
|
|
1197
|
+
{ name: "occurredAt", type: "date", required: true },
|
|
1198
|
+
{ name: "actorId", type: "text" },
|
|
1199
|
+
{ name: "payload", type: "json", required: true },
|
|
1200
|
+
{ name: "attempts", type: "number", required: true },
|
|
1201
|
+
{
|
|
1202
|
+
name: "status",
|
|
1203
|
+
type: "select",
|
|
1204
|
+
options: ["pending", "processing", "delivered", "failed"],
|
|
1205
|
+
required: true
|
|
1206
|
+
},
|
|
1207
|
+
{ name: "nextAttemptAt", type: "date" },
|
|
1208
|
+
{ name: "deliveredAt", type: "date" },
|
|
1209
|
+
{ name: "lastError", type: "textarea" }
|
|
1210
|
+
],
|
|
1211
|
+
access: {
|
|
1212
|
+
read: ({ user }) => !!user?.roles?.includes("admin"),
|
|
1213
|
+
create: () => false,
|
|
1214
|
+
update: () => false,
|
|
1215
|
+
delete: () => false
|
|
1216
|
+
},
|
|
1217
|
+
admin: { hidden: true }
|
|
1218
|
+
};
|
|
1219
|
+
var AUTH_SESSIONS_COLLECTION_CONFIG = {
|
|
1220
|
+
slug: AUTH_SESSIONS_COLLECTION,
|
|
1221
|
+
labels: { singular: "Auth session", plural: "Auth sessions" },
|
|
1222
|
+
fields: [
|
|
1223
|
+
{ name: "userId", type: "text", required: true },
|
|
1224
|
+
{ name: "email", type: "email", required: true },
|
|
1225
|
+
{ name: "collection", type: "text", required: true },
|
|
1226
|
+
{ name: "authSource", type: "text" },
|
|
1227
|
+
{ name: "providerId", type: "text" },
|
|
1228
|
+
{ name: "lastIp", type: "text" },
|
|
1229
|
+
{ name: "lastSeenAt", type: "date" },
|
|
1230
|
+
{ name: "expiresAt", type: "date" },
|
|
1231
|
+
{ name: "revokedAt", type: "date" }
|
|
1232
|
+
],
|
|
1233
|
+
access: {
|
|
1234
|
+
read: () => false,
|
|
1235
|
+
create: () => false,
|
|
1236
|
+
update: () => false,
|
|
1237
|
+
delete: () => false
|
|
1238
|
+
},
|
|
1239
|
+
admin: { hidden: true }
|
|
1240
|
+
};
|
|
1241
|
+
function normalizeConfig(config) {
|
|
1242
|
+
const schemaAwareConfig = normalizeSchemaFragment(config);
|
|
1243
|
+
const collections = schemaAwareConfig?.collections || [];
|
|
1244
|
+
const globals = schemaAwareConfig?.globals || [];
|
|
1245
|
+
const needsAudit = collections.some((col) => col.audit);
|
|
1246
|
+
const needsWorkflow = collections.some((col) => col.workflow || col.drafts);
|
|
1247
|
+
const needsAuthSessions = collections.some((col) => !!col.auth);
|
|
1248
|
+
const adminAuthCollectionSlug = getAdminAuthCollection({
|
|
1249
|
+
collections,
|
|
1250
|
+
adminAuth: schemaAwareConfig.adminAuth
|
|
1251
|
+
})?.slug;
|
|
1252
|
+
const normalizedCollections = collections.map((col) => {
|
|
1253
|
+
let fields = col.fields || [];
|
|
1254
|
+
const existingFieldNames = new Set(fields.map((f) => f.name));
|
|
1255
|
+
if (col.auth) {
|
|
1256
|
+
if (!existingFieldNames.has("email")) {
|
|
1257
|
+
fields = [
|
|
1258
|
+
...fields,
|
|
1259
|
+
{
|
|
1260
|
+
name: "email",
|
|
1261
|
+
type: "email",
|
|
1262
|
+
label: "Email",
|
|
1263
|
+
required: true,
|
|
1264
|
+
unique: true,
|
|
1265
|
+
promoted: true,
|
|
1266
|
+
access: {
|
|
1267
|
+
update: "!id"
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
];
|
|
1271
|
+
}
|
|
1272
|
+
if (!existingFieldNames.has("password")) {
|
|
1273
|
+
fields = [
|
|
1274
|
+
...fields,
|
|
1275
|
+
{
|
|
1276
|
+
name: "password",
|
|
1277
|
+
type: "text",
|
|
1278
|
+
label: "Password",
|
|
1279
|
+
required: true,
|
|
1280
|
+
access: {
|
|
1281
|
+
update: "!id || user.id == id"
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
];
|
|
1285
|
+
}
|
|
1286
|
+
if (!existingFieldNames.has("roles")) {
|
|
1287
|
+
fields = [
|
|
1288
|
+
...fields,
|
|
1289
|
+
{
|
|
1290
|
+
name: "roles",
|
|
1291
|
+
type: "select",
|
|
1292
|
+
label: "Roles",
|
|
1293
|
+
defaultValue: [],
|
|
1294
|
+
options: [
|
|
1295
|
+
{ value: "admin", label: "Admin" },
|
|
1296
|
+
{ value: "editor", label: "Editor" },
|
|
1297
|
+
{ value: "viewer", label: "Viewer" }
|
|
1298
|
+
],
|
|
1299
|
+
access: {
|
|
1300
|
+
update: "user.roles && 'admin' in user.roles"
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
];
|
|
1304
|
+
}
|
|
1305
|
+
fields = fields.map((field) => {
|
|
1306
|
+
if (field.name === "email") {
|
|
1307
|
+
return {
|
|
1308
|
+
...field,
|
|
1309
|
+
// Email is the login identifier. Keep the integrity constraints
|
|
1310
|
+
// auth relies on even when the field is explicitly redefined, so a
|
|
1311
|
+
// custom `email` field can never silently drop uniqueness.
|
|
1312
|
+
required: true,
|
|
1313
|
+
unique: true,
|
|
1314
|
+
promoted: true,
|
|
1315
|
+
access: {
|
|
1316
|
+
...field.access || {},
|
|
1317
|
+
update: "!id"
|
|
1318
|
+
}
|
|
1319
|
+
};
|
|
1320
|
+
}
|
|
1321
|
+
if (field.name === "password") {
|
|
1322
|
+
return {
|
|
1323
|
+
...field,
|
|
1324
|
+
// Password is required to authenticate; enforce it regardless of
|
|
1325
|
+
// how the field was declared.
|
|
1326
|
+
required: true,
|
|
1327
|
+
admin: { ...field.admin || {} },
|
|
1328
|
+
access: {
|
|
1329
|
+
...field.access || {},
|
|
1330
|
+
update: "!id || user.id == id"
|
|
1331
|
+
}
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
if (field.name === "roles") {
|
|
1335
|
+
return {
|
|
1336
|
+
...field,
|
|
1337
|
+
access: {
|
|
1338
|
+
...field.access || {},
|
|
1339
|
+
// Must be an admin; cannot edit own roles (no self-elevation).
|
|
1340
|
+
update: "user.roles && 'admin' in user.roles && user.id != id"
|
|
1341
|
+
}
|
|
1342
|
+
};
|
|
1343
|
+
}
|
|
1344
|
+
return field;
|
|
1345
|
+
});
|
|
1346
|
+
}
|
|
1347
|
+
if (adminAuthCollectionSlug && col.slug === adminAuthCollectionSlug && schemaAwareConfig.adminAuth?.mode === "external") {
|
|
1348
|
+
const externalAdminFields = [
|
|
1349
|
+
{
|
|
1350
|
+
name: "authProvider",
|
|
1351
|
+
type: "text",
|
|
1352
|
+
label: "Auth Provider",
|
|
1353
|
+
admin: { readOnly: true, hidden: true }
|
|
1354
|
+
},
|
|
1355
|
+
{
|
|
1356
|
+
name: "externalSubject",
|
|
1357
|
+
type: "text",
|
|
1358
|
+
label: "External Subject",
|
|
1359
|
+
admin: { readOnly: true, hidden: true }
|
|
1360
|
+
},
|
|
1361
|
+
{
|
|
1362
|
+
name: "authSource",
|
|
1363
|
+
type: "text",
|
|
1364
|
+
label: "Auth Source",
|
|
1365
|
+
admin: { readOnly: true, hidden: true }
|
|
1366
|
+
},
|
|
1367
|
+
{
|
|
1368
|
+
name: "lastLoginAt",
|
|
1369
|
+
type: "date",
|
|
1370
|
+
label: "Last Login At",
|
|
1371
|
+
admin: { readOnly: true, hidden: true }
|
|
1372
|
+
}
|
|
1373
|
+
];
|
|
1374
|
+
for (const field of externalAdminFields) {
|
|
1375
|
+
if (!existingFieldNames.has(field.name)) {
|
|
1376
|
+
fields = [...fields, field];
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
const updatedFieldNames = new Set(fields.map((f) => f.name));
|
|
1381
|
+
const fieldsToInject = SYSTEM_FIELDS.filter(
|
|
1382
|
+
(f) => !updatedFieldNames.has(f.name)
|
|
1383
|
+
);
|
|
1384
|
+
const workflow = col.workflow || (col.drafts ? simplePublishingWorkflow() : void 0);
|
|
1385
|
+
return {
|
|
1386
|
+
...col,
|
|
1387
|
+
workflow,
|
|
1388
|
+
fields: [...fields, ...fieldsToInject]
|
|
1389
|
+
};
|
|
1390
|
+
});
|
|
1391
|
+
const hasAuditCollection = normalizedCollections.some(
|
|
1392
|
+
(col) => col.slug === AUDIT_COLLECTION_SLUG
|
|
1393
|
+
);
|
|
1394
|
+
const systemCollections = [];
|
|
1395
|
+
if (needsAudit && !hasAuditCollection)
|
|
1396
|
+
systemCollections.push(AUDIT_COLLECTION);
|
|
1397
|
+
if (needsWorkflow && !normalizedCollections.some(
|
|
1398
|
+
(col) => col.slug === WORKFLOW_HISTORY_COLLECTION
|
|
1399
|
+
)) {
|
|
1400
|
+
systemCollections.push(WORKFLOW_HISTORY_COLLECTION_CONFIG);
|
|
1401
|
+
}
|
|
1402
|
+
if (needsWorkflow && !normalizedCollections.some(
|
|
1403
|
+
(col) => col.slug === LIFECYCLE_EVENTS_COLLECTION
|
|
1404
|
+
)) {
|
|
1405
|
+
systemCollections.push(LIFECYCLE_EVENTS_COLLECTION_CONFIG);
|
|
1406
|
+
}
|
|
1407
|
+
if (needsAuthSessions && !normalizedCollections.some((col) => col.slug === AUTH_SESSIONS_COLLECTION)) {
|
|
1408
|
+
systemCollections.push(AUTH_SESSIONS_COLLECTION_CONFIG);
|
|
1409
|
+
}
|
|
1410
|
+
return {
|
|
1411
|
+
...schemaAwareConfig,
|
|
1412
|
+
collections: [...normalizedCollections, ...systemCollections],
|
|
1413
|
+
globals
|
|
1414
|
+
};
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
// src/utils/hooks.ts
|
|
1418
|
+
async function runCollectionHooks(hooks, args, options = {}) {
|
|
1419
|
+
if (!hooks || hooks.length === 0) {
|
|
1420
|
+
return args.data ?? args.doc ?? void 0;
|
|
1421
|
+
}
|
|
1422
|
+
let currentPayload = args.data ?? args.doc ?? void 0;
|
|
1423
|
+
for (const hook of hooks) {
|
|
1424
|
+
try {
|
|
1425
|
+
const result = await hook({
|
|
1426
|
+
...args,
|
|
1427
|
+
data: args.data !== void 0 ? currentPayload : void 0,
|
|
1428
|
+
doc: args.doc !== void 0 ? currentPayload : void 0
|
|
1429
|
+
});
|
|
1430
|
+
if (result !== void 0) {
|
|
1431
|
+
currentPayload = result;
|
|
1432
|
+
}
|
|
1433
|
+
} catch (err) {
|
|
1434
|
+
if (options.isolated) {
|
|
1435
|
+
getConfigLogger(void 0, "hooks").error({
|
|
1436
|
+
err,
|
|
1437
|
+
msg: "Side-effect hook failed after a successful write"
|
|
1438
|
+
});
|
|
1439
|
+
} else {
|
|
1440
|
+
throw err;
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
return currentPayload;
|
|
1445
|
+
}
|
|
1446
|
+
async function executeFieldBeforeChange(fields, data, originalDoc, user, db) {
|
|
1447
|
+
if (!data || typeof data !== "object") return data;
|
|
1448
|
+
const result = { ...data };
|
|
1449
|
+
for (const field of fields) {
|
|
1450
|
+
if (!field.name) continue;
|
|
1451
|
+
const value = result[field.name];
|
|
1452
|
+
const origValue = originalDoc?.[field.name];
|
|
1453
|
+
let updatedValue = value;
|
|
1454
|
+
if (field.hooks?.beforeChange) {
|
|
1455
|
+
for (const hook of field.hooks.beforeChange) {
|
|
1456
|
+
const typedHook = hook;
|
|
1457
|
+
const hookArgs = {
|
|
1458
|
+
value: updatedValue,
|
|
1459
|
+
originalDoc: originalDoc ?? void 0,
|
|
1460
|
+
data: result,
|
|
1461
|
+
user,
|
|
1462
|
+
db
|
|
1463
|
+
};
|
|
1464
|
+
updatedValue = await typedHook(hookArgs);
|
|
1465
|
+
}
|
|
1466
|
+
result[field.name] = updatedValue;
|
|
1467
|
+
}
|
|
1468
|
+
if (updatedValue !== void 0 && updatedValue !== null) {
|
|
1469
|
+
if (field.type === "object" && field.fields) {
|
|
1470
|
+
result[field.name] = await executeFieldBeforeChange(
|
|
1471
|
+
field.fields,
|
|
1472
|
+
updatedValue,
|
|
1473
|
+
origValue,
|
|
1474
|
+
user,
|
|
1475
|
+
db
|
|
1476
|
+
);
|
|
1477
|
+
} else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
|
|
1478
|
+
const arrayResult = [];
|
|
1479
|
+
for (let i = 0; i < updatedValue.length; i++) {
|
|
1480
|
+
const item = updatedValue[i];
|
|
1481
|
+
const origItem = Array.isArray(origValue) ? origValue[i] : null;
|
|
1482
|
+
arrayResult.push(
|
|
1483
|
+
await executeFieldBeforeChange(
|
|
1484
|
+
field.fields,
|
|
1485
|
+
item,
|
|
1486
|
+
origItem,
|
|
1487
|
+
user,
|
|
1488
|
+
db
|
|
1489
|
+
)
|
|
1490
|
+
);
|
|
1491
|
+
}
|
|
1492
|
+
result[field.name] = arrayResult;
|
|
1493
|
+
} else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
|
|
1494
|
+
const blocksResult = [];
|
|
1495
|
+
for (let i = 0; i < updatedValue.length; i++) {
|
|
1496
|
+
const blockData = updatedValue[i];
|
|
1497
|
+
const origBlock = Array.isArray(origValue) ? origValue[i] : null;
|
|
1498
|
+
const blockConfig = field.blocks.find(
|
|
1499
|
+
(b) => b.slug === blockData.blockType
|
|
1500
|
+
);
|
|
1501
|
+
if (blockConfig) {
|
|
1502
|
+
blocksResult.push(
|
|
1503
|
+
await executeFieldBeforeChange(
|
|
1504
|
+
blockConfig.fields,
|
|
1505
|
+
blockData,
|
|
1506
|
+
origBlock,
|
|
1507
|
+
user,
|
|
1508
|
+
db
|
|
1509
|
+
)
|
|
1510
|
+
);
|
|
1511
|
+
} else {
|
|
1512
|
+
blocksResult.push(blockData);
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
result[field.name] = blocksResult;
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
return result;
|
|
1520
|
+
}
|
|
1521
|
+
async function executeFieldAfterRead(fields, doc, user, db) {
|
|
1522
|
+
if (!doc || typeof doc !== "object") return doc;
|
|
1523
|
+
const result = { ...doc };
|
|
1524
|
+
for (const field of fields) {
|
|
1525
|
+
if (!field.name) continue;
|
|
1526
|
+
const value = result[field.name];
|
|
1527
|
+
let updatedValue = value;
|
|
1528
|
+
if (field.hooks?.afterRead) {
|
|
1529
|
+
for (const hook of field.hooks.afterRead) {
|
|
1530
|
+
const typedHook = hook;
|
|
1531
|
+
const hookArgs = {
|
|
1532
|
+
value: updatedValue,
|
|
1533
|
+
doc: result,
|
|
1534
|
+
user,
|
|
1535
|
+
db
|
|
1536
|
+
};
|
|
1537
|
+
updatedValue = await typedHook(hookArgs);
|
|
1538
|
+
}
|
|
1539
|
+
result[field.name] = updatedValue;
|
|
1540
|
+
}
|
|
1541
|
+
if (updatedValue !== void 0 && updatedValue !== null) {
|
|
1542
|
+
if (field.type === "object" && field.fields) {
|
|
1543
|
+
result[field.name] = await executeFieldAfterRead(
|
|
1544
|
+
field.fields,
|
|
1545
|
+
updatedValue,
|
|
1546
|
+
user,
|
|
1547
|
+
db
|
|
1548
|
+
);
|
|
1549
|
+
} else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
|
|
1550
|
+
const arrayResult = [];
|
|
1551
|
+
for (const item of updatedValue) {
|
|
1552
|
+
arrayResult.push(
|
|
1553
|
+
await executeFieldAfterRead(
|
|
1554
|
+
field.fields,
|
|
1555
|
+
item,
|
|
1556
|
+
user,
|
|
1557
|
+
db
|
|
1558
|
+
)
|
|
1559
|
+
);
|
|
1560
|
+
}
|
|
1561
|
+
result[field.name] = arrayResult;
|
|
1562
|
+
} else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
|
|
1563
|
+
const blocksResult = [];
|
|
1564
|
+
for (const blockData of updatedValue) {
|
|
1565
|
+
const typedBlock = blockData;
|
|
1566
|
+
const blockConfig = field.blocks.find(
|
|
1567
|
+
(b) => b.slug === typedBlock.blockType
|
|
1568
|
+
);
|
|
1569
|
+
if (blockConfig) {
|
|
1570
|
+
blocksResult.push(
|
|
1571
|
+
await executeFieldAfterRead(
|
|
1572
|
+
blockConfig.fields,
|
|
1573
|
+
typedBlock,
|
|
1574
|
+
user,
|
|
1575
|
+
db
|
|
1576
|
+
)
|
|
1577
|
+
);
|
|
1578
|
+
} else {
|
|
1579
|
+
blocksResult.push(blockData);
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
result[field.name] = blocksResult;
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
return result;
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
// src/utils/openapi.ts
|
|
1590
|
+
function getCollectionLabels(collection) {
|
|
1591
|
+
return collection.labels || { singular: collection.slug, plural: collection.slug };
|
|
1592
|
+
}
|
|
1593
|
+
function getCollectionTag(collection) {
|
|
1594
|
+
return `Collection: ${getCollectionLabels(collection).plural}`;
|
|
1595
|
+
}
|
|
1596
|
+
function getGlobalTag(global) {
|
|
1597
|
+
return `Global: ${global.label || global.slug}`;
|
|
1598
|
+
}
|
|
1599
|
+
function generateOpenApi(config) {
|
|
1600
|
+
const spec = {
|
|
1601
|
+
openapi: "3.0.0",
|
|
1602
|
+
info: {
|
|
1603
|
+
title: "Dyrected API",
|
|
1604
|
+
version: "1.0.0",
|
|
1605
|
+
description: "Automatically generated OpenAPI specification for the Dyrected project."
|
|
1606
|
+
},
|
|
1607
|
+
components: {
|
|
1608
|
+
schemas: {
|
|
1609
|
+
WorkflowMetadata: {
|
|
1610
|
+
type: "object",
|
|
1611
|
+
required: ["state", "revision"],
|
|
1612
|
+
properties: {
|
|
1613
|
+
state: { type: "string" },
|
|
1614
|
+
revision: { type: "integer", minimum: 1 },
|
|
1615
|
+
publishedRevision: { type: "integer", minimum: 1 },
|
|
1616
|
+
publishedAt: { type: "string", format: "date-time" },
|
|
1617
|
+
publishedBy: { type: "string" },
|
|
1618
|
+
availableTransitions: { type: "array", items: { type: "string" } }
|
|
1619
|
+
}
|
|
1620
|
+
},
|
|
1621
|
+
WorkflowTransitionRequest: {
|
|
1622
|
+
type: "object",
|
|
1623
|
+
properties: {
|
|
1624
|
+
expectedRevision: { type: "integer", minimum: 1 },
|
|
1625
|
+
comment: { type: "string" }
|
|
1626
|
+
}
|
|
1627
|
+
},
|
|
1628
|
+
WorkflowHistoryEntry: {
|
|
1629
|
+
type: "object",
|
|
1630
|
+
required: [
|
|
1631
|
+
"collection",
|
|
1632
|
+
"documentId",
|
|
1633
|
+
"transition",
|
|
1634
|
+
"from",
|
|
1635
|
+
"to",
|
|
1636
|
+
"revision",
|
|
1637
|
+
"createdAt"
|
|
1638
|
+
],
|
|
1639
|
+
properties: {
|
|
1640
|
+
id: { type: "string" },
|
|
1641
|
+
collection: { type: "string" },
|
|
1642
|
+
documentId: { type: "string" },
|
|
1643
|
+
transition: { type: "string" },
|
|
1644
|
+
from: { type: "string" },
|
|
1645
|
+
to: { type: "string" },
|
|
1646
|
+
revision: { type: "integer" },
|
|
1647
|
+
comment: { type: "string", nullable: true },
|
|
1648
|
+
actorId: { type: "string", nullable: true },
|
|
1649
|
+
createdAt: { type: "string", format: "date-time" }
|
|
1650
|
+
}
|
|
1651
|
+
},
|
|
1652
|
+
AuditEntry: {
|
|
1653
|
+
type: "object",
|
|
1654
|
+
required: ["collection", "operation", "timestamp"],
|
|
1655
|
+
properties: {
|
|
1656
|
+
id: { type: "string" },
|
|
1657
|
+
collection: { type: "string" },
|
|
1658
|
+
documentId: { type: "string", nullable: true },
|
|
1659
|
+
operation: { type: "string" },
|
|
1660
|
+
user: { type: "string", nullable: true },
|
|
1661
|
+
timestamp: { type: "string", format: "date-time" },
|
|
1662
|
+
changes: {
|
|
1663
|
+
oneOf: [
|
|
1664
|
+
{ type: "string" },
|
|
1665
|
+
{ type: "object", additionalProperties: true },
|
|
1666
|
+
{ type: "null" }
|
|
1667
|
+
]
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
},
|
|
1671
|
+
Error: {
|
|
1672
|
+
type: "object",
|
|
1673
|
+
properties: {
|
|
1674
|
+
message: { type: "string" },
|
|
1675
|
+
errors: {
|
|
1676
|
+
type: "array",
|
|
1677
|
+
items: { type: "object", additionalProperties: true }
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
},
|
|
1681
|
+
AuthCredentials: {
|
|
1682
|
+
type: "object",
|
|
1683
|
+
required: ["email", "password"],
|
|
1684
|
+
properties: {
|
|
1685
|
+
email: { type: "string", format: "email" },
|
|
1686
|
+
password: { type: "string" }
|
|
1687
|
+
}
|
|
1688
|
+
},
|
|
1689
|
+
TokenResponse: {
|
|
1690
|
+
type: "object",
|
|
1691
|
+
properties: {
|
|
1692
|
+
token: { type: "string" },
|
|
1693
|
+
user: { type: "object", additionalProperties: true }
|
|
1694
|
+
}
|
|
1695
|
+
}
|
|
1696
|
+
},
|
|
1697
|
+
securitySchemes: {
|
|
1698
|
+
ApiKeyAuth: {
|
|
1699
|
+
type: "apiKey",
|
|
1700
|
+
in: "header",
|
|
1701
|
+
name: "x-api-key"
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
},
|
|
1705
|
+
paths: {},
|
|
1706
|
+
security: [{ ApiKeyAuth: [] }]
|
|
1707
|
+
};
|
|
1708
|
+
spec.paths["/api/schemas"] = {
|
|
1709
|
+
get: {
|
|
1710
|
+
tags: ["System"],
|
|
1711
|
+
summary: "Get the serialized Dyrected schema",
|
|
1712
|
+
security: [],
|
|
1713
|
+
responses: {
|
|
1714
|
+
200: { description: "Collection and global schema definitions" }
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
};
|
|
1718
|
+
spec.paths["/api/openapi.json"] = {
|
|
1719
|
+
get: {
|
|
1720
|
+
tags: ["System"],
|
|
1721
|
+
summary: "Get the OpenAPI specification",
|
|
1722
|
+
security: [],
|
|
1723
|
+
responses: { 200: { description: "OpenAPI 3.0 document" } }
|
|
1724
|
+
}
|
|
1725
|
+
};
|
|
1726
|
+
spec.paths["/api/docs"] = {
|
|
1727
|
+
get: {
|
|
1728
|
+
tags: ["System"],
|
|
1729
|
+
summary: "Open interactive API documentation",
|
|
1730
|
+
security: [],
|
|
1731
|
+
responses: { 200: { description: "Swagger UI HTML" } }
|
|
1732
|
+
}
|
|
1733
|
+
};
|
|
1734
|
+
spec.paths["/api/dyrected/options/{collection}/{field}"] = {
|
|
1735
|
+
get: {
|
|
1736
|
+
tags: ["System"],
|
|
1737
|
+
summary: "Resolve dynamic field options",
|
|
1738
|
+
parameters: [
|
|
1739
|
+
{
|
|
1740
|
+
name: "collection",
|
|
1741
|
+
in: "path",
|
|
1742
|
+
required: true,
|
|
1743
|
+
schema: { type: "string" }
|
|
1744
|
+
},
|
|
1745
|
+
{
|
|
1746
|
+
name: "field",
|
|
1747
|
+
in: "path",
|
|
1748
|
+
required: true,
|
|
1749
|
+
schema: { type: "string" }
|
|
1750
|
+
}
|
|
1751
|
+
],
|
|
1752
|
+
responses: { 200: { description: "Resolved option items" } }
|
|
1753
|
+
}
|
|
1754
|
+
};
|
|
1755
|
+
spec.paths["/api/preferences/{key}"] = {
|
|
1756
|
+
get: {
|
|
1757
|
+
tags: ["Preferences"],
|
|
1758
|
+
summary: "Get an authenticated user preference",
|
|
1759
|
+
parameters: [
|
|
1760
|
+
{ name: "key", in: "path", required: true, schema: { type: "string" } }
|
|
1761
|
+
],
|
|
1762
|
+
responses: { 200: { description: "Preference value" } }
|
|
1763
|
+
},
|
|
1764
|
+
put: {
|
|
1765
|
+
tags: ["Preferences"],
|
|
1766
|
+
summary: "Set an authenticated user preference",
|
|
1767
|
+
parameters: [
|
|
1768
|
+
{ name: "key", in: "path", required: true, schema: { type: "string" } }
|
|
1769
|
+
],
|
|
1770
|
+
requestBody: {
|
|
1771
|
+
required: true,
|
|
1772
|
+
content: { "application/json": { schema: { type: "object" } } }
|
|
1773
|
+
},
|
|
1774
|
+
responses: { 200: { description: "Updated preference" } }
|
|
1775
|
+
}
|
|
1776
|
+
};
|
|
1777
|
+
spec.paths["/api/preview-token"] = {
|
|
1778
|
+
post: {
|
|
1779
|
+
tags: ["Preview"],
|
|
1780
|
+
summary: "Create a preview token",
|
|
1781
|
+
responses: { 200: { description: "Short-lived preview token" } }
|
|
1782
|
+
}
|
|
1783
|
+
};
|
|
1784
|
+
spec.paths["/api/preview-data"] = {
|
|
1785
|
+
get: {
|
|
1786
|
+
tags: ["Preview"],
|
|
1787
|
+
summary: "Resolve preview data from a token",
|
|
1788
|
+
security: [],
|
|
1789
|
+
parameters: [
|
|
1790
|
+
{
|
|
1791
|
+
name: "token",
|
|
1792
|
+
in: "query",
|
|
1793
|
+
required: true,
|
|
1794
|
+
schema: { type: "string" }
|
|
1795
|
+
}
|
|
1796
|
+
],
|
|
1797
|
+
responses: { 200: { description: "Preview document data" } }
|
|
1798
|
+
}
|
|
1799
|
+
};
|
|
1800
|
+
spec.paths["/api/audit"] = {
|
|
1801
|
+
get: {
|
|
1802
|
+
tags: ["Audit"],
|
|
1803
|
+
summary: "Get audit entries across all readable audited collections",
|
|
1804
|
+
parameters: [
|
|
1805
|
+
{
|
|
1806
|
+
name: "limit",
|
|
1807
|
+
in: "query",
|
|
1808
|
+
schema: { type: "integer", default: 50, maximum: 100 }
|
|
1809
|
+
},
|
|
1810
|
+
{ name: "page", in: "query", schema: { type: "integer", default: 1 } },
|
|
1811
|
+
{
|
|
1812
|
+
name: "where",
|
|
1813
|
+
in: "query",
|
|
1814
|
+
schema: { type: "string" },
|
|
1815
|
+
description: "JSON filter"
|
|
1816
|
+
},
|
|
1817
|
+
{
|
|
1818
|
+
name: "sort",
|
|
1819
|
+
in: "query",
|
|
1820
|
+
schema: { type: "string", default: "-timestamp" }
|
|
1821
|
+
}
|
|
1822
|
+
],
|
|
1823
|
+
responses: {
|
|
1824
|
+
200: {
|
|
1825
|
+
description: "Audit entries",
|
|
1826
|
+
content: {
|
|
1827
|
+
"application/json": {
|
|
1828
|
+
schema: {
|
|
1829
|
+
type: "object",
|
|
1830
|
+
properties: {
|
|
1831
|
+
docs: {
|
|
1832
|
+
type: "array",
|
|
1833
|
+
items: { $ref: "#/components/schemas/AuditEntry" }
|
|
1834
|
+
},
|
|
1835
|
+
total: { type: "integer" },
|
|
1836
|
+
limit: { type: "integer" },
|
|
1837
|
+
page: { type: "integer" }
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
};
|
|
1846
|
+
for (const collection of config.collections) {
|
|
1847
|
+
spec.components.schemas[collection.slug] = collectionToSchema(collection);
|
|
1848
|
+
}
|
|
1849
|
+
for (const global of config.globals) {
|
|
1850
|
+
spec.components.schemas[global.slug] = globalToSchema(global);
|
|
1851
|
+
}
|
|
1852
|
+
for (const collection of config.collections) {
|
|
1853
|
+
const slug = collection.slug;
|
|
1854
|
+
const path = `/api/collections/${slug}`;
|
|
1855
|
+
const labels = getCollectionLabels(collection);
|
|
1856
|
+
const collectionTag = getCollectionTag(collection);
|
|
1857
|
+
spec.paths[path] = {
|
|
1858
|
+
get: {
|
|
1859
|
+
tags: [collectionTag],
|
|
1860
|
+
summary: `Find ${labels.plural}`,
|
|
1861
|
+
parameters: [
|
|
1862
|
+
{
|
|
1863
|
+
name: "limit",
|
|
1864
|
+
in: "query",
|
|
1865
|
+
schema: { type: "integer", default: 10 }
|
|
1866
|
+
},
|
|
1867
|
+
{
|
|
1868
|
+
name: "page",
|
|
1869
|
+
in: "query",
|
|
1870
|
+
schema: { type: "integer", default: 1 }
|
|
1871
|
+
},
|
|
1872
|
+
{
|
|
1873
|
+
name: "where",
|
|
1874
|
+
in: "query",
|
|
1875
|
+
schema: { type: "string" },
|
|
1876
|
+
description: "JSON filter"
|
|
1877
|
+
},
|
|
1878
|
+
{
|
|
1879
|
+
name: "sort",
|
|
1880
|
+
in: "query",
|
|
1881
|
+
schema: { type: "string" },
|
|
1882
|
+
description: "Sort field (e.g. -createdAt)"
|
|
1883
|
+
}
|
|
1884
|
+
],
|
|
1885
|
+
responses: {
|
|
1886
|
+
200: {
|
|
1887
|
+
description: "Success",
|
|
1888
|
+
content: {
|
|
1889
|
+
"application/json": {
|
|
1890
|
+
schema: {
|
|
1891
|
+
type: "object",
|
|
1892
|
+
properties: {
|
|
1893
|
+
docs: {
|
|
1894
|
+
type: "array",
|
|
1895
|
+
items: { $ref: `#/components/schemas/${slug}` }
|
|
1896
|
+
},
|
|
1897
|
+
total: { type: "integer" },
|
|
1898
|
+
limit: { type: "integer" },
|
|
1899
|
+
page: { type: "integer" }
|
|
1900
|
+
}
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
},
|
|
1907
|
+
post: {
|
|
1908
|
+
tags: [collectionTag],
|
|
1909
|
+
summary: `Create ${labels.singular}`,
|
|
1910
|
+
requestBody: {
|
|
1911
|
+
required: true,
|
|
1912
|
+
content: {
|
|
1913
|
+
"application/json": {
|
|
1914
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
},
|
|
1918
|
+
responses: {
|
|
1919
|
+
201: {
|
|
1920
|
+
description: "Created",
|
|
1921
|
+
content: {
|
|
1922
|
+
"application/json": {
|
|
1923
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
};
|
|
1930
|
+
spec.paths[`${path}/{id}`] = {
|
|
1931
|
+
get: {
|
|
1932
|
+
tags: [collectionTag],
|
|
1933
|
+
summary: `Get a single ${labels.singular}`,
|
|
1934
|
+
parameters: [
|
|
1935
|
+
{
|
|
1936
|
+
name: "id",
|
|
1937
|
+
in: "path",
|
|
1938
|
+
required: true,
|
|
1939
|
+
schema: { type: "string" }
|
|
1940
|
+
}
|
|
1941
|
+
],
|
|
1942
|
+
responses: {
|
|
1943
|
+
200: {
|
|
1944
|
+
description: "Success",
|
|
1945
|
+
content: {
|
|
1946
|
+
"application/json": {
|
|
1947
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
},
|
|
1953
|
+
patch: {
|
|
1954
|
+
tags: [collectionTag],
|
|
1955
|
+
summary: `Update ${labels.singular}`,
|
|
1956
|
+
parameters: [
|
|
1957
|
+
{
|
|
1958
|
+
name: "id",
|
|
1959
|
+
in: "path",
|
|
1960
|
+
required: true,
|
|
1961
|
+
schema: { type: "string" }
|
|
1962
|
+
}
|
|
1963
|
+
],
|
|
1964
|
+
requestBody: {
|
|
1965
|
+
required: true,
|
|
1966
|
+
content: {
|
|
1967
|
+
"application/json": {
|
|
1968
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
},
|
|
1972
|
+
responses: {
|
|
1973
|
+
200: {
|
|
1974
|
+
description: "Updated",
|
|
1975
|
+
content: {
|
|
1976
|
+
"application/json": {
|
|
1977
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
},
|
|
1983
|
+
delete: {
|
|
1984
|
+
tags: [collectionTag],
|
|
1985
|
+
summary: `Delete ${labels.singular}`,
|
|
1986
|
+
parameters: [
|
|
1987
|
+
{
|
|
1988
|
+
name: "id",
|
|
1989
|
+
in: "path",
|
|
1990
|
+
required: true,
|
|
1991
|
+
schema: { type: "string" }
|
|
1992
|
+
}
|
|
1993
|
+
],
|
|
1994
|
+
responses: {
|
|
1995
|
+
204: { description: "Deleted" }
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
};
|
|
1999
|
+
spec.paths[`${path}/delete-many`] = {
|
|
2000
|
+
delete: {
|
|
2001
|
+
tags: [collectionTag],
|
|
2002
|
+
summary: `Delete multiple ${labels.plural}`,
|
|
2003
|
+
requestBody: {
|
|
2004
|
+
required: true,
|
|
2005
|
+
content: {
|
|
2006
|
+
"application/json": {
|
|
2007
|
+
schema: {
|
|
2008
|
+
type: "object",
|
|
2009
|
+
required: ["ids"],
|
|
2010
|
+
properties: {
|
|
2011
|
+
ids: { type: "array", items: { type: "string" } }
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
},
|
|
2017
|
+
responses: { 200: { description: "Deleted and failed document IDs" } }
|
|
2018
|
+
}
|
|
2019
|
+
};
|
|
2020
|
+
if (collection.audit) {
|
|
2021
|
+
spec.paths[`${path}/__audit`] = {
|
|
2022
|
+
get: {
|
|
2023
|
+
tags: [collectionTag],
|
|
2024
|
+
summary: `Get ${labels.singular} audit entries`,
|
|
2025
|
+
parameters: [
|
|
2026
|
+
{
|
|
2027
|
+
name: "limit",
|
|
2028
|
+
in: "query",
|
|
2029
|
+
schema: { type: "integer", default: 50, maximum: 100 }
|
|
2030
|
+
},
|
|
2031
|
+
{
|
|
2032
|
+
name: "page",
|
|
2033
|
+
in: "query",
|
|
2034
|
+
schema: { type: "integer", default: 1 }
|
|
2035
|
+
},
|
|
2036
|
+
{
|
|
2037
|
+
name: "where",
|
|
2038
|
+
in: "query",
|
|
2039
|
+
schema: { type: "string" },
|
|
2040
|
+
description: "JSON filter"
|
|
2041
|
+
},
|
|
2042
|
+
{
|
|
2043
|
+
name: "sort",
|
|
2044
|
+
in: "query",
|
|
2045
|
+
schema: { type: "string", default: "-timestamp" }
|
|
2046
|
+
}
|
|
2047
|
+
],
|
|
2048
|
+
responses: {
|
|
2049
|
+
200: {
|
|
2050
|
+
description: "Audit entries for this collection",
|
|
2051
|
+
content: {
|
|
2052
|
+
"application/json": {
|
|
2053
|
+
schema: {
|
|
2054
|
+
type: "object",
|
|
2055
|
+
properties: {
|
|
2056
|
+
docs: {
|
|
2057
|
+
type: "array",
|
|
2058
|
+
items: { $ref: "#/components/schemas/AuditEntry" }
|
|
2059
|
+
},
|
|
2060
|
+
total: { type: "integer" },
|
|
2061
|
+
limit: { type: "integer" },
|
|
2062
|
+
page: { type: "integer" }
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
},
|
|
2068
|
+
403: { description: "Collection read access denied" },
|
|
2069
|
+
404: { description: "Audit is not enabled for this collection" }
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
};
|
|
2073
|
+
}
|
|
2074
|
+
spec.paths[`${path}/seed`] = {
|
|
2075
|
+
post: {
|
|
2076
|
+
tags: [collectionTag],
|
|
2077
|
+
summary: `Seed initial ${labels.plural}`,
|
|
2078
|
+
responses: { 200: { description: "Seeded documents" } }
|
|
2079
|
+
}
|
|
2080
|
+
};
|
|
2081
|
+
if (collection.upload) {
|
|
2082
|
+
spec.paths[`${path}/media`] = {
|
|
2083
|
+
get: {
|
|
2084
|
+
tags: [collectionTag],
|
|
2085
|
+
summary: `List ${labels.plural}`,
|
|
2086
|
+
responses: { 200: { description: "Paginated media documents" } }
|
|
2087
|
+
},
|
|
2088
|
+
post: {
|
|
2089
|
+
tags: [collectionTag],
|
|
2090
|
+
summary: `Upload ${labels.singular}`,
|
|
2091
|
+
requestBody: {
|
|
2092
|
+
required: true,
|
|
2093
|
+
content: {
|
|
2094
|
+
"multipart/form-data": {
|
|
2095
|
+
schema: {
|
|
2096
|
+
type: "object",
|
|
2097
|
+
required: ["file"],
|
|
2098
|
+
properties: { file: { type: "string", format: "binary" } }
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
},
|
|
2103
|
+
responses: { 201: { description: "Uploaded media document" } }
|
|
2104
|
+
}
|
|
2105
|
+
};
|
|
2106
|
+
spec.paths[`${path}/media/{filename}`] = {
|
|
2107
|
+
get: {
|
|
2108
|
+
tags: [collectionTag],
|
|
2109
|
+
summary: `Serve ${labels.singular} bytes`,
|
|
2110
|
+
parameters: [
|
|
2111
|
+
{
|
|
2112
|
+
name: "filename",
|
|
2113
|
+
in: "path",
|
|
2114
|
+
required: true,
|
|
2115
|
+
schema: { type: "string" }
|
|
2116
|
+
}
|
|
2117
|
+
],
|
|
2118
|
+
security: [],
|
|
2119
|
+
responses: {
|
|
2120
|
+
200: { description: "Stored file" },
|
|
2121
|
+
404: { description: "File not found" }
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
};
|
|
2125
|
+
}
|
|
2126
|
+
if (collection.auth) {
|
|
2127
|
+
const publicAuthPost = (summary) => ({
|
|
2128
|
+
tags: [collectionTag],
|
|
2129
|
+
summary,
|
|
2130
|
+
security: [],
|
|
2131
|
+
requestBody: {
|
|
2132
|
+
required: true,
|
|
2133
|
+
content: {
|
|
2134
|
+
"application/json": {
|
|
2135
|
+
schema: { type: "object", additionalProperties: true }
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
},
|
|
2139
|
+
responses: {
|
|
2140
|
+
200: { description: "Success" },
|
|
2141
|
+
400: { description: "Invalid request" }
|
|
2142
|
+
}
|
|
2143
|
+
});
|
|
2144
|
+
spec.paths[`${path}/login`] = {
|
|
2145
|
+
post: {
|
|
2146
|
+
...publicAuthPost(`Log in to ${labels.plural}`),
|
|
2147
|
+
requestBody: {
|
|
2148
|
+
required: true,
|
|
2149
|
+
content: {
|
|
2150
|
+
"application/json": {
|
|
2151
|
+
schema: { $ref: "#/components/schemas/AuthCredentials" }
|
|
2152
|
+
}
|
|
2153
|
+
}
|
|
2154
|
+
},
|
|
2155
|
+
responses: {
|
|
2156
|
+
200: {
|
|
2157
|
+
description: "Authenticated",
|
|
2158
|
+
content: {
|
|
2159
|
+
"application/json": {
|
|
2160
|
+
schema: { $ref: "#/components/schemas/TokenResponse" }
|
|
2161
|
+
}
|
|
2162
|
+
}
|
|
2163
|
+
},
|
|
2164
|
+
401: { description: "Invalid credentials" }
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
};
|
|
2168
|
+
spec.paths[`${path}/logout`] = {
|
|
2169
|
+
post: {
|
|
2170
|
+
tags: [collectionTag],
|
|
2171
|
+
summary: `Log out of ${labels.plural}`,
|
|
2172
|
+
parameters: [
|
|
2173
|
+
{
|
|
2174
|
+
name: "allSessions",
|
|
2175
|
+
in: "query",
|
|
2176
|
+
required: false,
|
|
2177
|
+
schema: { type: "boolean" },
|
|
2178
|
+
description: "Revoke every active session for this account instead of only the current one."
|
|
2179
|
+
}
|
|
2180
|
+
],
|
|
2181
|
+
responses: { 200: { description: "Logged out" } }
|
|
2182
|
+
}
|
|
2183
|
+
};
|
|
2184
|
+
spec.paths[`${path}/init`] = {
|
|
2185
|
+
get: {
|
|
2186
|
+
tags: [collectionTag],
|
|
2187
|
+
summary: `Get ${labels.plural} initialization state`,
|
|
2188
|
+
security: [],
|
|
2189
|
+
responses: { 200: { description: "Initialization state" } }
|
|
2190
|
+
}
|
|
2191
|
+
};
|
|
2192
|
+
spec.paths[`${path}/first-user`] = {
|
|
2193
|
+
post: publicAuthPost(`Register the first ${labels.singular}`)
|
|
2194
|
+
};
|
|
2195
|
+
spec.paths[`${path}/me`] = {
|
|
2196
|
+
get: {
|
|
2197
|
+
tags: [collectionTag],
|
|
2198
|
+
summary: `Get the current ${labels.singular}`,
|
|
2199
|
+
responses: { 200: { description: "Authenticated user" } }
|
|
2200
|
+
}
|
|
2201
|
+
};
|
|
2202
|
+
spec.paths[`${path}/refresh-token`] = {
|
|
2203
|
+
post: {
|
|
2204
|
+
tags: [collectionTag],
|
|
2205
|
+
summary: "Refresh an authentication token",
|
|
2206
|
+
responses: {
|
|
2207
|
+
200: {
|
|
2208
|
+
description: "Refreshed token for the current active session"
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
2212
|
+
};
|
|
2213
|
+
spec.paths[`${path}/forgot-password`] = {
|
|
2214
|
+
post: publicAuthPost("Request a password reset")
|
|
2215
|
+
};
|
|
2216
|
+
spec.paths[`${path}/reset-password`] = {
|
|
2217
|
+
post: publicAuthPost("Reset a password")
|
|
2218
|
+
};
|
|
2219
|
+
spec.paths[`${path}/invite`] = {
|
|
2220
|
+
post: {
|
|
2221
|
+
tags: [collectionTag],
|
|
2222
|
+
summary: `Invite a ${labels.singular}`,
|
|
2223
|
+
responses: { 200: { description: "Invitation sent" } }
|
|
2224
|
+
}
|
|
2225
|
+
};
|
|
2226
|
+
spec.paths[`${path}/accept-invite`] = {
|
|
2227
|
+
post: publicAuthPost("Accept an invitation")
|
|
2228
|
+
};
|
|
2229
|
+
spec.paths[`${path}/{id}/change-password`] = {
|
|
2230
|
+
post: {
|
|
2231
|
+
tags: [collectionTag],
|
|
2232
|
+
summary: `Change a ${labels.singular} password`,
|
|
2233
|
+
parameters: [
|
|
2234
|
+
{
|
|
2235
|
+
name: "id",
|
|
2236
|
+
in: "path",
|
|
2237
|
+
required: true,
|
|
2238
|
+
schema: { type: "string" }
|
|
2239
|
+
}
|
|
2240
|
+
],
|
|
2241
|
+
responses: {
|
|
2242
|
+
200: {
|
|
2243
|
+
description: "Password changed and active sessions revoked"
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
};
|
|
2248
|
+
}
|
|
2249
|
+
if (collection.workflow) {
|
|
2250
|
+
spec.paths[`${path}/{id}/transitions/{transition}`] = {
|
|
2251
|
+
post: {
|
|
2252
|
+
tags: [collectionTag],
|
|
2253
|
+
summary: `Transition ${labels.singular} workflow`,
|
|
2254
|
+
parameters: [
|
|
2255
|
+
{
|
|
2256
|
+
name: "id",
|
|
2257
|
+
in: "path",
|
|
2258
|
+
required: true,
|
|
2259
|
+
schema: { type: "string" }
|
|
2260
|
+
},
|
|
2261
|
+
{
|
|
2262
|
+
name: "transition",
|
|
2263
|
+
in: "path",
|
|
2264
|
+
required: true,
|
|
2265
|
+
schema: {
|
|
2266
|
+
type: "string",
|
|
2267
|
+
enum: collection.workflow.transitions.map((item) => item.name)
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
2270
|
+
],
|
|
2271
|
+
requestBody: {
|
|
2272
|
+
content: {
|
|
2273
|
+
"application/json": {
|
|
2274
|
+
schema: {
|
|
2275
|
+
$ref: "#/components/schemas/WorkflowTransitionRequest"
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
2278
|
+
}
|
|
2279
|
+
},
|
|
2280
|
+
responses: {
|
|
2281
|
+
200: {
|
|
2282
|
+
description: "Transition applied",
|
|
2283
|
+
content: {
|
|
2284
|
+
"application/json": {
|
|
2285
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
},
|
|
2289
|
+
400: { description: "Required transition input is missing" },
|
|
2290
|
+
403: { description: "Transition capability denied" },
|
|
2291
|
+
409: { description: "Invalid state or stale revision" }
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
};
|
|
2295
|
+
spec.paths[`${path}/{id}/workflow-history`] = {
|
|
2296
|
+
get: {
|
|
2297
|
+
tags: [collectionTag],
|
|
2298
|
+
summary: `Get ${labels.singular} workflow history`,
|
|
2299
|
+
parameters: [
|
|
2300
|
+
{
|
|
2301
|
+
name: "id",
|
|
2302
|
+
in: "path",
|
|
2303
|
+
required: true,
|
|
2304
|
+
schema: { type: "string" }
|
|
2305
|
+
},
|
|
2306
|
+
{
|
|
2307
|
+
name: "limit",
|
|
2308
|
+
in: "query",
|
|
2309
|
+
schema: { type: "integer", default: 50, maximum: 100 }
|
|
2310
|
+
}
|
|
2311
|
+
],
|
|
2312
|
+
responses: {
|
|
2313
|
+
200: {
|
|
2314
|
+
description: "Workflow transition history",
|
|
2315
|
+
content: {
|
|
2316
|
+
"application/json": {
|
|
2317
|
+
schema: {
|
|
2318
|
+
type: "object",
|
|
2319
|
+
properties: {
|
|
2320
|
+
docs: {
|
|
2321
|
+
type: "array",
|
|
2322
|
+
items: {
|
|
2323
|
+
$ref: "#/components/schemas/WorkflowHistoryEntry"
|
|
2324
|
+
}
|
|
2325
|
+
},
|
|
2326
|
+
total: { type: "integer" },
|
|
2327
|
+
limit: { type: "integer" },
|
|
2328
|
+
page: { type: "integer" }
|
|
2329
|
+
}
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
}
|
|
2333
|
+
},
|
|
2334
|
+
403: { description: "Collection read access denied" }
|
|
2335
|
+
}
|
|
2336
|
+
}
|
|
2337
|
+
};
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
for (const global of config.globals) {
|
|
2341
|
+
const slug = global.slug;
|
|
2342
|
+
const path = `/api/globals/${slug}`;
|
|
2343
|
+
const globalTag = getGlobalTag(global);
|
|
2344
|
+
spec.paths[path] = {
|
|
2345
|
+
get: {
|
|
2346
|
+
tags: [globalTag],
|
|
2347
|
+
summary: `Get ${global.label || slug}`,
|
|
2348
|
+
responses: {
|
|
2349
|
+
200: {
|
|
2350
|
+
description: "Success",
|
|
2351
|
+
content: {
|
|
2352
|
+
"application/json": {
|
|
2353
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
}
|
|
2358
|
+
},
|
|
2359
|
+
patch: {
|
|
2360
|
+
tags: [globalTag],
|
|
2361
|
+
summary: `Update ${global.label || slug}`,
|
|
2362
|
+
requestBody: {
|
|
2363
|
+
required: true,
|
|
2364
|
+
content: {
|
|
2365
|
+
"application/json": {
|
|
2366
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
2367
|
+
}
|
|
2368
|
+
}
|
|
2369
|
+
},
|
|
2370
|
+
responses: {
|
|
2371
|
+
200: {
|
|
2372
|
+
description: "Updated",
|
|
2373
|
+
content: {
|
|
2374
|
+
"application/json": {
|
|
2375
|
+
schema: { $ref: `#/components/schemas/${slug}` }
|
|
2376
|
+
}
|
|
2377
|
+
}
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
}
|
|
2381
|
+
};
|
|
2382
|
+
spec.paths[`${path}/seed`] = {
|
|
2383
|
+
post: {
|
|
2384
|
+
tags: [globalTag],
|
|
2385
|
+
summary: `Seed ${global.label || slug}`,
|
|
2386
|
+
responses: { 200: { description: "Seeded global" } }
|
|
2387
|
+
}
|
|
2388
|
+
};
|
|
2389
|
+
}
|
|
2390
|
+
if (config.storage) {
|
|
2391
|
+
spec.paths["/api/media/{filename}"] = {
|
|
2392
|
+
get: {
|
|
2393
|
+
tags: ["Media"],
|
|
2394
|
+
summary: "Serve a stored file",
|
|
2395
|
+
security: [],
|
|
2396
|
+
parameters: [
|
|
2397
|
+
{
|
|
2398
|
+
name: "filename",
|
|
2399
|
+
in: "path",
|
|
2400
|
+
required: true,
|
|
2401
|
+
schema: { type: "string" }
|
|
2402
|
+
}
|
|
2403
|
+
],
|
|
2404
|
+
responses: {
|
|
2405
|
+
200: { description: "Stored file bytes" },
|
|
2406
|
+
404: { description: "File not found" }
|
|
2407
|
+
}
|
|
2408
|
+
}
|
|
2409
|
+
};
|
|
2410
|
+
}
|
|
2411
|
+
return spec;
|
|
2412
|
+
}
|
|
2413
|
+
function collectionToSchema(collection) {
|
|
2414
|
+
const { properties, required } = fieldsToProperties(collection.fields);
|
|
2415
|
+
return {
|
|
2416
|
+
type: "object",
|
|
2417
|
+
properties: {
|
|
2418
|
+
id: { type: "string" },
|
|
2419
|
+
createdAt: { type: "string", format: "date-time" },
|
|
2420
|
+
updatedAt: { type: "string", format: "date-time" },
|
|
2421
|
+
...collection.workflow ? { _workflow: { $ref: "#/components/schemas/WorkflowMetadata" } } : {},
|
|
2422
|
+
...properties
|
|
2423
|
+
},
|
|
2424
|
+
required: ["id", ...required]
|
|
2425
|
+
};
|
|
2426
|
+
}
|
|
2427
|
+
function globalToSchema(global) {
|
|
2428
|
+
const { properties, required } = fieldsToProperties(global.fields);
|
|
2429
|
+
return {
|
|
2430
|
+
type: "object",
|
|
2431
|
+
properties,
|
|
2432
|
+
required
|
|
2433
|
+
};
|
|
2434
|
+
}
|
|
2435
|
+
function fieldsToProperties(fields) {
|
|
2436
|
+
const props = {};
|
|
2437
|
+
const required = [];
|
|
2438
|
+
for (const field of fields) {
|
|
2439
|
+
if (field.type === "row") {
|
|
2440
|
+
const nested = fieldsToProperties(field.fields || []);
|
|
2441
|
+
Object.assign(props, nested.properties);
|
|
2442
|
+
required.push(...nested.required);
|
|
2443
|
+
continue;
|
|
2444
|
+
}
|
|
2445
|
+
if (!field.name) continue;
|
|
2446
|
+
props[field.name] = fieldToSchema(field);
|
|
2447
|
+
if (field.required) {
|
|
2448
|
+
required.push(field.name);
|
|
2449
|
+
}
|
|
2450
|
+
}
|
|
2451
|
+
return { properties: props, required };
|
|
2452
|
+
}
|
|
2453
|
+
function fieldToSchema(field) {
|
|
2454
|
+
let schema;
|
|
2455
|
+
switch (field.type) {
|
|
2456
|
+
case "text":
|
|
2457
|
+
case "textarea":
|
|
2458
|
+
case "email":
|
|
2459
|
+
schema = { type: "string" };
|
|
2460
|
+
break;
|
|
2461
|
+
case "url":
|
|
2462
|
+
schema = {
|
|
2463
|
+
oneOf: [
|
|
2464
|
+
{ type: "string" },
|
|
2465
|
+
{ type: "object", additionalProperties: true }
|
|
2466
|
+
]
|
|
2467
|
+
};
|
|
2468
|
+
break;
|
|
2469
|
+
case "icon":
|
|
2470
|
+
schema = { type: "string" };
|
|
2471
|
+
break;
|
|
2472
|
+
case "number":
|
|
2473
|
+
schema = { type: "number" };
|
|
2474
|
+
break;
|
|
2475
|
+
case "boolean":
|
|
2476
|
+
schema = { type: "boolean" };
|
|
2477
|
+
break;
|
|
2478
|
+
case "date":
|
|
2479
|
+
schema = { type: "string", format: "date" };
|
|
2480
|
+
break;
|
|
2481
|
+
case "datetime":
|
|
2482
|
+
schema = { type: "string", format: "date-time" };
|
|
2483
|
+
break;
|
|
2484
|
+
case "time":
|
|
2485
|
+
schema = { type: "string", format: "time" };
|
|
2486
|
+
break;
|
|
2487
|
+
case "select":
|
|
2488
|
+
case "radio":
|
|
2489
|
+
schema = {
|
|
2490
|
+
type: "string",
|
|
2491
|
+
enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0
|
|
2492
|
+
};
|
|
2493
|
+
break;
|
|
2494
|
+
case "multiSelect":
|
|
2495
|
+
schema = {
|
|
2496
|
+
type: "array",
|
|
2497
|
+
items: {
|
|
2498
|
+
type: "string",
|
|
2499
|
+
enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0
|
|
2500
|
+
}
|
|
2501
|
+
};
|
|
2502
|
+
break;
|
|
2503
|
+
case "relationship":
|
|
2504
|
+
case "image": {
|
|
2505
|
+
const valueSchema = {
|
|
2506
|
+
type: "string",
|
|
2507
|
+
description: `ID of a ${field.relationTo} record`
|
|
2508
|
+
};
|
|
2509
|
+
schema = field.hasMany ? { type: "array", items: valueSchema } : valueSchema;
|
|
2510
|
+
break;
|
|
2511
|
+
}
|
|
2512
|
+
case "join":
|
|
2513
|
+
schema = {
|
|
2514
|
+
type: "array",
|
|
2515
|
+
readOnly: true,
|
|
2516
|
+
items: { type: "object", additionalProperties: true }
|
|
2517
|
+
};
|
|
2518
|
+
break;
|
|
2519
|
+
case "object": {
|
|
2520
|
+
const { properties, required } = fieldsToProperties(field.fields || []);
|
|
2521
|
+
schema = { type: "object", properties, required };
|
|
2522
|
+
break;
|
|
2523
|
+
}
|
|
2524
|
+
case "array": {
|
|
2525
|
+
const { properties, required } = fieldsToProperties(field.fields || []);
|
|
2526
|
+
schema = {
|
|
2527
|
+
type: "array",
|
|
2528
|
+
items: { type: "object", properties, required }
|
|
2529
|
+
};
|
|
2530
|
+
break;
|
|
2531
|
+
}
|
|
2532
|
+
case "json":
|
|
2533
|
+
case "richText":
|
|
2534
|
+
schema = { type: "object", additionalProperties: true };
|
|
2535
|
+
break;
|
|
2536
|
+
case "blocks":
|
|
2537
|
+
schema = {
|
|
2538
|
+
type: "array",
|
|
2539
|
+
items: {
|
|
2540
|
+
oneOf: field.blocks?.map((block) => {
|
|
2541
|
+
const { properties, required } = fieldsToProperties(block.fields);
|
|
2542
|
+
return {
|
|
2543
|
+
type: "object",
|
|
2544
|
+
properties: {
|
|
2545
|
+
blockType: { type: "string", enum: [block.slug] },
|
|
2546
|
+
...properties
|
|
2547
|
+
},
|
|
2548
|
+
required: ["blockType", ...required]
|
|
2549
|
+
};
|
|
2550
|
+
})
|
|
2551
|
+
}
|
|
2552
|
+
};
|
|
2553
|
+
break;
|
|
2554
|
+
default:
|
|
2555
|
+
schema = { type: "string" };
|
|
2556
|
+
}
|
|
2557
|
+
if (field.label) schema.description = field.label;
|
|
2558
|
+
return schema;
|
|
2559
|
+
}
|
|
2560
|
+
|
|
2561
|
+
export {
|
|
2562
|
+
signCollectionToken,
|
|
2563
|
+
verifyCollectionToken,
|
|
2564
|
+
issueAuthSessionToken,
|
|
2565
|
+
getAuthSession,
|
|
2566
|
+
isAuthSessionActive,
|
|
2567
|
+
touchAuthSession,
|
|
2568
|
+
revokeAuthSession,
|
|
2569
|
+
revokeAllAuthSessions,
|
|
2570
|
+
createObservabilityRuntime,
|
|
2571
|
+
bindObservabilityRuntime,
|
|
2572
|
+
getObservabilityRuntime,
|
|
2573
|
+
getConfigLogger,
|
|
2574
|
+
getRequestLogger,
|
|
2575
|
+
buildRequestLogger,
|
|
2576
|
+
shouldSampleRequest,
|
|
2577
|
+
redactHeaders,
|
|
2578
|
+
captureRequestBody,
|
|
2579
|
+
createRequestSpan,
|
|
2580
|
+
endRequestSpan,
|
|
2581
|
+
attachRequestMetrics,
|
|
2582
|
+
renderPrometheusMetrics,
|
|
2583
|
+
WORKFLOW_HISTORY_COLLECTION,
|
|
2584
|
+
LIFECYCLE_EVENTS_COLLECTION,
|
|
2585
|
+
definePublishingWorkflow,
|
|
2586
|
+
publishingWorkflow,
|
|
2587
|
+
simplePublishingWorkflow,
|
|
2588
|
+
workflowCapabilities,
|
|
2589
|
+
canViewWorkflowDraft,
|
|
2590
|
+
availableWorkflowTransitions,
|
|
2591
|
+
initializeWorkflowDocument,
|
|
2592
|
+
publishedStateName,
|
|
2593
|
+
materializeWorkflowDocument,
|
|
2594
|
+
createLifecycleEvent,
|
|
2595
|
+
dispatchLifecycleEvent,
|
|
2596
|
+
dispatchPendingLifecycleEvents,
|
|
2597
|
+
saveWorkflowDraft,
|
|
2598
|
+
createWorkflowDocument,
|
|
2599
|
+
transitionWorkflow,
|
|
2600
|
+
getAdminAuthCollection,
|
|
2601
|
+
resolveAdminAuthCollection,
|
|
2602
|
+
getPublicAdminAuthConfig,
|
|
2603
|
+
mergeDynamicConfig,
|
|
2604
|
+
normalizeConfig,
|
|
2605
|
+
runCollectionHooks,
|
|
2606
|
+
executeFieldBeforeChange,
|
|
2607
|
+
executeFieldAfterRead,
|
|
2608
|
+
generateOpenApi
|
|
2609
|
+
};
|