@aphexcms/cms-core 11.1.1 → 11.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/api/docs-ui.d.ts +22 -0
  2. package/dist/api/docs-ui.d.ts.map +1 -0
  3. package/dist/api/docs-ui.js +19 -0
  4. package/dist/api/schemas/assets.d.ts +11 -0
  5. package/dist/api/schemas/assets.d.ts.map +1 -1
  6. package/dist/api/schemas/assets.js +24 -0
  7. package/dist/auth/auth-hooks.d.ts.map +1 -1
  8. package/dist/auth/auth-hooks.js +4 -1
  9. package/dist/server/api/index.d.ts.map +1 -1
  10. package/dist/server/api/index.js +7 -0
  11. package/dist/server/api/openapi/generate.d.ts +13 -0
  12. package/dist/server/api/openapi/generate.d.ts.map +1 -0
  13. package/dist/server/api/openapi/generate.js +529 -0
  14. package/dist/server/api/openapi/json-schema.d.ts +45 -0
  15. package/dist/server/api/openapi/json-schema.d.ts.map +1 -0
  16. package/dist/server/api/openapi/json-schema.js +206 -0
  17. package/dist/server/api/openapi/registry.d.ts +78 -0
  18. package/dist/server/api/openapi/registry.d.ts.map +1 -0
  19. package/dist/server/api/openapi/registry.js +628 -0
  20. package/dist/server/api/routes/agent-change-sets.d.ts +6 -0
  21. package/dist/server/api/routes/agent-change-sets.d.ts.map +1 -1
  22. package/dist/server/api/routes/agent-change-sets.js +2 -1
  23. package/dist/server/api/routes/jobs.d.ts +32 -0
  24. package/dist/server/api/routes/jobs.d.ts.map +1 -1
  25. package/dist/server/api/routes/jobs.js +7 -3
  26. package/dist/server/api/routes/openapi.d.ts +34 -0
  27. package/dist/server/api/routes/openapi.d.ts.map +1 -0
  28. package/dist/server/api/routes/openapi.js +97 -0
  29. package/dist/server/index.d.ts +1 -0
  30. package/dist/server/index.d.ts.map +1 -1
  31. package/dist/server/index.js +1 -0
  32. package/dist/types/config.d.ts +15 -0
  33. package/dist/types/config.d.ts.map +1 -1
  34. package/package.json +1 -1
@@ -0,0 +1,529 @@
1
+ /**
2
+ * Build the OpenAPI 3.1 document for *this* instance.
3
+ *
4
+ * Two halves, deliberately:
5
+ *
6
+ * - The **generic** half comes from the zod request/query contracts in
7
+ * `api/schemas/*`, via `z.toJSONSchema`. Nothing is retyped — a change to a
8
+ * contract changes the spec on the next request.
9
+ * - The **per-instance** half comes from `config.schemaTypes`. A static file can
10
+ * never say what goes in `draftData` for a `post`, because that only exists in
11
+ * this deployment. That's the reason this is generated at request time rather
12
+ * than checked in.
13
+ *
14
+ * Path params are read off the Hono path (`:id` → `{id}`) rather than declared,
15
+ * so a renamed param can't silently disagree with the route.
16
+ */
17
+ import { z } from 'zod';
18
+ import { cmsLogger } from '../../../utils/logger.js';
19
+ import { ROUTE_REGISTRY, TAG_DESCRIPTIONS } from './registry.js';
20
+ import { buildSchemaComponents, componentName, SHARED_VALUE_COMPONENTS } from './json-schema.js';
21
+ /**
22
+ * `z.toJSONSchema` emits a `$schema` key and, for `.refine()`-bearing objects,
23
+ * keeps input-side semantics only under `io: 'input'` — which is what a *request*
24
+ * body is. Strip `$schema`: it's valid JSON Schema but noise inside a component.
25
+ *
26
+ * Two guards, both learned the hard way:
27
+ *
28
+ * - **`unrepresentable: 'any'`.** `z.date()` has no JSON Schema equivalent, and
29
+ * the default is to *throw*. Several contracts legitimately accept
30
+ * `z.union([z.string(), z.date()])` because an adapter may hand back either, so
31
+ * the default would take the whole endpoint down over a field that serialises
32
+ * to a string anyway. The `override` below then restores the useful part by
33
+ * describing a Date as the ISO string it becomes on the wire.
34
+ * - **The try/catch.** A description endpoint must not be able to 500. If some
35
+ * future contract can't be converted at all, that one schema degrades to
36
+ * "unconstrained" and the rest of the document still renders.
37
+ */
38
+ function zodToJson(schema) {
39
+ try {
40
+ const out = z.toJSONSchema(schema, {
41
+ io: 'input',
42
+ unrepresentable: 'any',
43
+ override: (ctx) => {
44
+ if (ctx.zodSchema._zod.def.type === 'date') {
45
+ Object.assign(ctx.jsonSchema, {
46
+ type: 'string',
47
+ format: 'date-time',
48
+ description: 'ISO 8601 timestamp.'
49
+ });
50
+ }
51
+ }
52
+ });
53
+ delete out.$schema;
54
+ return out;
55
+ }
56
+ catch (error) {
57
+ cmsLogger.warn('[openapi]', 'Could not convert a zod contract to JSON Schema; describing it as unconstrained.', error);
58
+ return {
59
+ description: 'This contract could not be expressed as JSON Schema. See the endpoint documentation.'
60
+ };
61
+ }
62
+ }
63
+ /** `/api/documents/:id/versions/:version` → `/api/documents/{id}/versions/{version}`. */
64
+ function toOpenApiPath(honoPath) {
65
+ return honoPath.replace(/:([A-Za-z0-9_]+)/g, '{$1}');
66
+ }
67
+ /** Path parameters implied by the route's own path string. */
68
+ function pathParams(honoPath) {
69
+ const names = [...honoPath.matchAll(/:([A-Za-z0-9_]+)/g)].map((m) => m[1]);
70
+ return names.map((name) => ({
71
+ name,
72
+ in: 'path',
73
+ required: true,
74
+ schema: { type: 'string' },
75
+ description: name === 'id' ? 'Document, asset, organization or job id.' : undefined
76
+ }));
77
+ }
78
+ /**
79
+ * Query parameters from a zod object: one parameter per top-level property,
80
+ * `required` mirroring the schema's own required list.
81
+ */
82
+ function queryParams(schema) {
83
+ const json = zodToJson(schema);
84
+ const props = (json.properties ?? {});
85
+ const required = new Set(json.required ?? []);
86
+ return Object.entries(props).map(([name, propSchema]) => {
87
+ const { description, ...rest } = propSchema;
88
+ return {
89
+ name,
90
+ in: 'query',
91
+ required: required.has(name),
92
+ schema: rest,
93
+ ...(description ? { description } : {})
94
+ };
95
+ });
96
+ }
97
+ const AUTH_NOTES = {
98
+ read: 'Session or API key. A read-only API key is accepted.',
99
+ write: 'Session or API key with `write` permission. A read-only key receives 403.',
100
+ 'read-via-post': 'Read-only despite the POST method — accepted with a read-only API key. See the note on write protection.',
101
+ public: 'No credentials required.',
102
+ session: 'Session cookie only — API keys are rejected by this handler.',
103
+ secret: 'Shared-secret bearer token (`jobs.workerSecret`), not user auth. 404 when unset.'
104
+ };
105
+ /** Standard error responses every route can produce. */
106
+ function errorResponses(auth) {
107
+ const responses = {
108
+ '400': {
109
+ description: 'Request rejected. Two distinct shapes — see `ZodIssue` (malformed body) and `ValidationIssue` (valid body, invalid content).',
110
+ content: {
111
+ 'application/json': { schema: { $ref: '#/components/schemas/ErrorResponse' } }
112
+ }
113
+ }
114
+ };
115
+ if (auth !== 'public') {
116
+ responses['401'] = {
117
+ description: 'Missing or invalid credentials.',
118
+ content: { 'application/json': { schema: { $ref: '#/components/schemas/MiddlewareError' } } }
119
+ };
120
+ }
121
+ if (auth === 'write' || auth === 'session') {
122
+ responses['403'] = {
123
+ description: auth === 'session'
124
+ ? 'Authenticated, but this handler requires a session rather than an API key.'
125
+ : 'Authenticated without `write` permission.',
126
+ content: { 'application/json': { schema: { $ref: '#/components/schemas/MiddlewareError' } } }
127
+ };
128
+ }
129
+ return responses;
130
+ }
131
+ /**
132
+ * The request body for a document write, expanded per collection.
133
+ *
134
+ * `createDocumentRequest.draftData` is `Record<string, unknown>` — true, and
135
+ * useless. With the live schemas we can say: `type: "post"` means `draftData`
136
+ * matches `PostData`.
137
+ *
138
+ * The composition keyword differs by method, and the difference is real rather
139
+ * than cosmetic:
140
+ *
141
+ * - **POST** carries `type` in the body, so the variants *are* mutually
142
+ * exclusive and `oneOf` + a `discriminator` on `type` is exactly right. The
143
+ * discriminator is what lets a client generator emit a tagged union.
144
+ * - **PUT** targets an existing id and carries no `type`, so nothing in the body
145
+ * distinguishes a page write from a post write. `oneOf` would be a false claim
146
+ * (a validator must match exactly one, and an empty `{}` body matches all of
147
+ * them). `anyOf` says what is actually true: the payload matches at least one
148
+ * collection's shape, and which one is settled by the id in the path.
149
+ */
150
+ function expandedDocumentBody(base, documentTypes, method,
151
+ /** Variant schemas are registered here — a discriminator can only select `$ref`s. */
152
+ components) {
153
+ if (documentTypes.length === 0)
154
+ return base;
155
+ const baseProps = (base.properties ?? {});
156
+ const suffix = method === 'POST' ? 'CreateRequest' : 'UpdateRequest';
157
+ const refs = documentTypes.map((schema) => {
158
+ const name = `${componentName(schema.name)}${suffix}`;
159
+ const dataRef = { $ref: `#/components/schemas/${componentName(schema.name)}Data` };
160
+ const properties = {
161
+ ...baseProps,
162
+ draftData: dataRef,
163
+ data: dataRef
164
+ };
165
+ if (method === 'POST')
166
+ properties.type = { type: 'string', const: schema.name };
167
+ components[name] = {
168
+ title: `${schema.title ?? schema.name} — ${method === 'POST' ? 'create' : 'update'}`,
169
+ type: 'object',
170
+ properties,
171
+ ...(method === 'POST' ? { required: ['type'] } : {})
172
+ };
173
+ return { $ref: `#/components/schemas/${name}` };
174
+ });
175
+ const description = 'Exactly one of `draftData` or `data` is required; both carry the same per-collection shape.';
176
+ if (method === 'PUT') {
177
+ return {
178
+ anyOf: refs,
179
+ description: `${description} The collection is determined by the document id in the path, not by the body.`
180
+ };
181
+ }
182
+ return {
183
+ oneOf: refs,
184
+ discriminator: {
185
+ propertyName: 'type',
186
+ mapping: Object.fromEntries(documentTypes.map((s) => [s.name, `#/components/schemas/${componentName(s.name)}${suffix}`]))
187
+ },
188
+ description
189
+ };
190
+ }
191
+ function buildOperation(route, documentTypes, components) {
192
+ const parameters = [...pathParams(route.path), ...(route.query ? queryParams(route.query) : [])];
193
+ const operation = {
194
+ operationId: `${route.method.toLowerCase()}${toOpenApiPath(route.path)
195
+ .replace(/[{}]/g, '')
196
+ .split(/[/-]/)
197
+ .filter(Boolean)
198
+ .map((s) => s[0].toUpperCase() + s.slice(1))
199
+ .join('')}`,
200
+ summary: route.summary,
201
+ description: [route.description, `**Auth:** ${AUTH_NOTES[route.auth]}`]
202
+ .filter(Boolean)
203
+ .join('\n\n'),
204
+ tags: [route.tag],
205
+ responses: {
206
+ '200': {
207
+ description: 'Success.',
208
+ content: {
209
+ 'application/json': {
210
+ // Prefer the endpoint's own response contract. The generic
211
+ // envelope is a last resort and deliberately says nothing about
212
+ // `data` or pagination — claiming a `pagination` object on an
213
+ // endpoint that never returns one is worse than staying silent.
214
+ schema: route.response
215
+ ? zodToJson(route.response)
216
+ : { $ref: '#/components/schemas/SuccessResponse' }
217
+ }
218
+ }
219
+ },
220
+ ...errorResponses(route.auth)
221
+ }
222
+ };
223
+ if (route.method === 'POST' && route.path === '/api/documents') {
224
+ operation.responses['201'] = {
225
+ description: 'Created.',
226
+ content: { 'application/json': { schema: { $ref: '#/components/schemas/SuccessResponse' } } }
227
+ };
228
+ delete operation.responses['200'];
229
+ }
230
+ if (route.auth === 'write' || route.auth === 'read' || route.auth === 'read-via-post') {
231
+ operation.security = [{ apiKey: [] }, { session: [] }];
232
+ }
233
+ else if (route.auth === 'session') {
234
+ operation.security = [{ session: [] }];
235
+ }
236
+ else if (route.auth === 'secret') {
237
+ operation.security = [{ workerSecret: [] }];
238
+ }
239
+ else {
240
+ // An empty array is how OpenAPI spells "explicitly no auth". Omitting the
241
+ // key entirely means "inherit the root requirement", which is a different
242
+ // claim and reads as an oversight to any linter.
243
+ operation.security = [];
244
+ }
245
+ if (route.formData) {
246
+ operation.requestBody = {
247
+ required: true,
248
+ content: {
249
+ 'multipart/form-data': {
250
+ schema: {
251
+ type: 'object',
252
+ properties: route.formData.fields,
253
+ required: ['file']
254
+ }
255
+ }
256
+ }
257
+ };
258
+ }
259
+ else if (route.request) {
260
+ let schema = zodToJson(route.request);
261
+ if (route.expandDocumentData) {
262
+ schema = expandedDocumentBody(schema, documentTypes, route.method, components);
263
+ }
264
+ // Some fields are deliberately `z.unknown()` in the contract because they're
265
+ // validated further down (the filter DSL is parsed by `LocalAPI.find()`, not
266
+ // by zod). `z.unknown()` converts to `{}`, which tells a reader nothing and
267
+ // leads a UI to invent a plausible-looking example that doesn't work — so
268
+ // describe those fields here instead of leaving them blank.
269
+ if (route.bodyOverrides) {
270
+ const props = { ...(schema.properties ?? {}) };
271
+ for (const [name, override] of Object.entries(route.bodyOverrides)) {
272
+ if (name in props)
273
+ props[name] = override;
274
+ }
275
+ schema = { ...schema, properties: props };
276
+ }
277
+ operation.requestBody = {
278
+ required: true,
279
+ content: {
280
+ 'application/json': {
281
+ schema,
282
+ // A worked example beats a generated one: a UI faced with an
283
+ // unconstrained field will otherwise fill in something that parses
284
+ // but matches nothing.
285
+ ...(route.requestExample ? { example: route.requestExample } : {})
286
+ }
287
+ }
288
+ };
289
+ }
290
+ if (parameters.length > 0)
291
+ operation.parameters = parameters;
292
+ // CAS-bearing writes can conflict.
293
+ if (route.request && 'shape' in route.request) {
294
+ const shape = route.request.shape;
295
+ if (shape && 'expectedRevision' in shape) {
296
+ operation.responses['409'] = {
297
+ description: '`expectedRevision` did not match — the document changed since you read it. The body carries `currentRevision`.',
298
+ content: {
299
+ 'application/json': { schema: { $ref: '#/components/schemas/ErrorResponse' } }
300
+ }
301
+ };
302
+ }
303
+ }
304
+ return { method: route.method.toLowerCase(), operation };
305
+ }
306
+ /** Envelope and error components — the shapes every endpoint shares. */
307
+ const ENVELOPE_COMPONENTS = {
308
+ SuccessResponse: {
309
+ type: 'object',
310
+ description: 'The shared success envelope, for endpoints that have no more specific response contract yet. `data` is endpoint-dependent; list endpoints also carry `pagination`.',
311
+ properties: {
312
+ success: { type: 'boolean', const: true },
313
+ data: {}
314
+ },
315
+ required: ['success']
316
+ },
317
+ Pagination: {
318
+ type: 'object',
319
+ properties: {
320
+ total: { type: 'integer' },
321
+ page: { type: 'integer' },
322
+ pageSize: { type: 'integer' },
323
+ totalPages: { type: 'integer' },
324
+ hasNextPage: { type: 'boolean' },
325
+ hasPrevPage: { type: 'boolean' }
326
+ }
327
+ },
328
+ ErrorResponse: {
329
+ type: 'object',
330
+ description: 'Returned by a route handler. `issues` carries one of two shapes depending on which layer rejected the request.',
331
+ properties: {
332
+ success: { type: 'boolean', const: false },
333
+ error: { type: 'string' },
334
+ message: { type: 'string' },
335
+ currentRevision: { type: 'integer', description: 'Present on a 409 conflict.' },
336
+ issues: {
337
+ type: 'array',
338
+ items: {
339
+ oneOf: [
340
+ { $ref: '#/components/schemas/ZodIssue' },
341
+ { $ref: '#/components/schemas/ValidationIssue' }
342
+ ]
343
+ }
344
+ }
345
+ },
346
+ required: ['success', 'error']
347
+ },
348
+ ZodIssue: {
349
+ type: 'object',
350
+ title: 'Malformed request body',
351
+ description: 'The request did not parse against the endpoint contract.',
352
+ properties: {
353
+ code: { type: 'string' },
354
+ path: { type: 'array', items: { type: 'string' } },
355
+ message: { type: 'string' }
356
+ }
357
+ },
358
+ ValidationIssue: {
359
+ type: 'object',
360
+ title: 'Invalid document content',
361
+ description: 'The body parsed, but the document data failed schema validation. `kind: "structural"` means a wrong JSON shape (a field that isn’t declared, a string where an array belongs) rather than a failed rule.',
362
+ properties: {
363
+ field: { type: 'string' },
364
+ errors: { type: 'array', items: { type: 'string' } },
365
+ kind: { type: 'string', enum: ['structural', 'rule'] }
366
+ }
367
+ },
368
+ FieldFilter: {
369
+ type: 'object',
370
+ title: 'Field filter',
371
+ description: 'Operators for one field. Source of truth: `types/filters.ts`. Anything not listed here is silently ignored, which drops the whole clause.',
372
+ properties: {
373
+ equals: {},
374
+ not_equals: {},
375
+ in: { type: 'array', items: {} },
376
+ not_in: { type: 'array', items: {} },
377
+ exists: { type: 'boolean' },
378
+ greater_than: {},
379
+ greater_than_equal: {},
380
+ less_than: {},
381
+ less_than_equal: {},
382
+ like: { type: 'string' },
383
+ contains: { type: 'string' },
384
+ starts_with: { type: 'string' },
385
+ ends_with: { type: 'string' }
386
+ },
387
+ additionalProperties: false
388
+ },
389
+ WhereFilter: {
390
+ type: 'object',
391
+ title: 'Where clause',
392
+ description: 'Field name → operators. Multiple fields are ANDed. Dot-notation reaches nested fields ("seo.title"). `and`/`or` nest further clauses.',
393
+ properties: {
394
+ and: { type: 'array', items: { $ref: '#/components/schemas/WhereFilter' } },
395
+ or: { type: 'array', items: { $ref: '#/components/schemas/WhereFilter' } }
396
+ },
397
+ additionalProperties: { $ref: '#/components/schemas/FieldFilter' },
398
+ examples: [
399
+ { slug: { equals: 'contact' } },
400
+ { title: { contains: 'incident' }, 'seo.noIndex': { equals: false } },
401
+ { or: [{ slug: { equals: 'contact' } }, { slug: { equals: 'home' } }] }
402
+ ]
403
+ },
404
+ MiddlewareError: {
405
+ type: 'object',
406
+ description: 'Returned by the auth middleware, which short-circuits before the handler — so it carries neither `success` nor `message`.',
407
+ properties: { error: { type: 'string' } },
408
+ required: ['error']
409
+ }
410
+ };
411
+ /**
412
+ * Drop components nothing points at, following `$ref`s transitively from the
413
+ * paths so a component reachable only via another component survives.
414
+ *
415
+ * Without this, an instance whose schemas contain no `file` field still
416
+ * advertises `FileValue`, and a generated client ships a type for a value the
417
+ * API will never return here.
418
+ */
419
+ function pruneUnreferenced(schemas, paths) {
420
+ const refsIn = (value, out) => {
421
+ if (Array.isArray(value)) {
422
+ for (const item of value)
423
+ refsIn(item, out);
424
+ }
425
+ else if (value && typeof value === 'object') {
426
+ for (const [key, child] of Object.entries(value)) {
427
+ if (key === '$ref' && typeof child === 'string') {
428
+ const name = child.replace('#/components/schemas/', '');
429
+ if (name !== child)
430
+ out.add(name);
431
+ }
432
+ else {
433
+ refsIn(child, out);
434
+ }
435
+ }
436
+ }
437
+ return out;
438
+ };
439
+ const reachable = refsIn(paths, new Set());
440
+ // Transitive closure: a component referenced only by another component.
441
+ let frontier = [...reachable];
442
+ while (frontier.length > 0) {
443
+ const next = [];
444
+ for (const name of frontier) {
445
+ const schema = schemas[name];
446
+ if (!schema)
447
+ continue;
448
+ for (const ref of refsIn(schema, new Set())) {
449
+ if (!reachable.has(ref)) {
450
+ reachable.add(ref);
451
+ next.push(ref);
452
+ }
453
+ }
454
+ }
455
+ frontier = next;
456
+ }
457
+ return Object.fromEntries(Object.entries(schemas).filter(([name]) => reachable.has(name)));
458
+ }
459
+ /** Build the full OpenAPI document. */
460
+ export function generateOpenApiDocument(options = {}) {
461
+ const schemaTypes = options.schemaTypes ?? [];
462
+ const documentTypes = schemaTypes.filter((s) => s.type === 'document');
463
+ const paths = {};
464
+ // Filled as operations are built — the per-collection write variants a
465
+ // discriminator has to point at by `$ref`.
466
+ const writeVariants = {};
467
+ for (const route of ROUTE_REGISTRY) {
468
+ const path = toOpenApiPath(route.path);
469
+ const { method, operation } = buildOperation(route, documentTypes, writeVariants);
470
+ paths[path] ??= {};
471
+ paths[path][method] = operation;
472
+ }
473
+ // Tags in registry order, so the rendered doc opens on Documents rather than
474
+ // alphabetising Agent to the top.
475
+ const tags = [];
476
+ for (const route of ROUTE_REGISTRY) {
477
+ if (!tags.some((t) => t.name === route.tag)) {
478
+ tags.push({ name: route.tag, description: TAG_DESCRIPTIONS[route.tag] });
479
+ }
480
+ }
481
+ const schemas = {
482
+ ...ENVELOPE_COMPONENTS,
483
+ ...SHARED_VALUE_COMPONENTS,
484
+ ...buildSchemaComponents(schemaTypes),
485
+ ...writeVariants
486
+ };
487
+ return {
488
+ openapi: '3.1.0',
489
+ info: {
490
+ title: options.title ?? 'AphexCMS HTTP API',
491
+ version: options.version ?? '1.0.0',
492
+ license: { name: 'MIT', identifier: 'MIT' },
493
+ description: [
494
+ 'Generated from this instance: the endpoint contracts come from the zod schemas the handlers validate with, and the per-collection document shapes from the schema types this deployment is running.',
495
+ '',
496
+ '**Write protection.** `POST`, `PUT`, `PATCH` and `DELETE` under `/api/` require an API key with `write` permission. Two read-shaped exceptions pass with a read-only key: `POST /api/documents/query`, and GraphQL queries at the configured `graphql.path`. Note this check applies to *every* POST under `/api/`, including custom routes you mount yourself.',
497
+ '',
498
+ '**Organization scoping.** An API key is scoped to the organization active when it was created; every request with that key sees only that organization’s data.'
499
+ ].join('\n')
500
+ },
501
+ ...(options.serverUrl ? { servers: [{ url: options.serverUrl }] } : {}),
502
+ tags,
503
+ paths,
504
+ components: {
505
+ securitySchemes: {
506
+ apiKey: {
507
+ type: 'apiKey',
508
+ in: 'header',
509
+ name: 'x-api-key',
510
+ description: 'A CMS API key. Scoped to one organization.'
511
+ },
512
+ session: {
513
+ type: 'apiKey',
514
+ in: 'cookie',
515
+ name: 'session',
516
+ description: 'Admin session cookie. Used by the studio UI.'
517
+ },
518
+ workerSecret: {
519
+ type: 'http',
520
+ scheme: 'bearer',
521
+ description: '`jobs.workerSecret`. Machine-to-machine only.'
522
+ }
523
+ },
524
+ // Drop shared value components this instance never references — an
525
+ // instance with no `file` field anywhere shouldn't advertise FileValue.
526
+ schemas: pruneUnreferenced(schemas, paths)
527
+ }
528
+ };
529
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Field → JSON Schema, for the per-instance half of the OpenAPI document.
3
+ *
4
+ * The generic request contracts (`api/schemas/*.ts`) describe `draftData` as
5
+ * `Record<string, unknown>`, which is honest but useless to a reader: the whole
6
+ * question when you POST a document is *what goes in there*, and the answer only
7
+ * exists in this instance's `schemaTypes`. So the spec gets a real component per
8
+ * document type, generated at request time from the live config.
9
+ *
10
+ * This is the third walker over `Field` in the codebase — `type-gen.ts` emits
11
+ * TypeScript, `graphql/schema.ts` emits SDL, this emits JSON Schema. The *emit*
12
+ * genuinely differs each time (strings vs strings vs objects), but the
13
+ * classification underneath must not: required-ness comes from the canonical
14
+ * `isFieldRequired` in `field-validation/utils`, the same predicate the validator
15
+ * itself runs, so a field that the API will reject as missing is the same field
16
+ * the spec marks required.
17
+ *
18
+ * (Note: `graphql/schema.ts` has its own local `isFieldRequired` that string-matches
19
+ * the validation function source. It disagrees with this one on any rule that
20
+ * mentions "required" without being required. Not changed here — fixing it moves
21
+ * GraphQL non-null markers, which is a breaking change for clients and deserves
22
+ * its own decision.)
23
+ */
24
+ import type { Field, SchemaType } from '../../../types/schemas.js';
25
+ /** A JSON Schema object, loose enough for the subset OpenAPI 3.1 accepts. */
26
+ export type JsonSchema = Record<string, unknown>;
27
+ /** Shared component schemas referenced by `$ref` from generated field shapes. */
28
+ export declare const SHARED_VALUE_COMPONENTS: Record<string, JsonSchema>;
29
+ /**
30
+ * The depth=0 *write* shape of one field as JSON Schema.
31
+ *
32
+ * Write shape, not read shape: references stay `{_ref}` rather than the resolved
33
+ * document, because that is what a caller sends and what the validator checks.
34
+ */
35
+ export declare function fieldToJsonSchema(field: Field, schemaMap: Map<string, SchemaType>, seen?: Set<string>): JsonSchema;
36
+ /** Turn a list of fields into an object schema with a `required` array. */
37
+ export declare function fieldsToJsonSchema(fields: Field[], schemaMap: Map<string, SchemaType>, seen?: Set<string>): JsonSchema;
38
+ /** PascalCase component name for a schema type, e.g. `post` → `PostData`. */
39
+ export declare function componentName(schemaName: string): string;
40
+ /**
41
+ * Every schema type in the instance as components: `<Type>Data` for documents
42
+ * (the `draftData`/`data` payload) and the object types they reference.
43
+ */
44
+ export declare function buildSchemaComponents(schemaTypes: SchemaType[]): Record<string, JsonSchema>;
45
+ //# sourceMappingURL=json-schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json-schema.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/api/openapi/json-schema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAGhE,6EAA6E;AAC7E,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEjD,iFAAiF;AACjF,eAAO,MAAM,uBAAuB,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAwD9D,CAAC;AAuBF;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAChC,KAAK,EAAE,KAAK,EACZ,SAAS,EAAE,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,EAClC,IAAI,GAAE,GAAG,CAAC,MAAM,CAAa,GAC3B,UAAU,CAuEZ;AAED,2EAA2E;AAC3E,wBAAgB,kBAAkB,CACjC,MAAM,EAAE,KAAK,EAAE,EACf,SAAS,EAAE,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,EAClC,IAAI,GAAE,GAAG,CAAC,MAAM,CAAa,GAC3B,UAAU,CAiBZ;AAED,6EAA6E;AAC7E,wBAAgB,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAIxD;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,WAAW,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAgB3F"}