@fudanda/create-arcbase 2.20261024.1-beta.2 → 2.20261107.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/.runtime/npm/index.json +18 -18
  2. package/.runtime/sdk.json +3 -3
  3. package/LICENSE +21 -21
  4. package/README.md +99 -91
  5. package/cli.mjs +42 -39
  6. package/package.json +58 -53
  7. package/src/assistant.mjs +76 -0
  8. package/src/delivery.mjs +20 -20
  9. package/src/enhance.mjs +103 -104
  10. package/src/evolve.mjs +66 -66
  11. package/src/fields.mjs +73 -73
  12. package/src/goa-contracts.mjs +331 -331
  13. package/src/goa.mjs +202 -202
  14. package/src/history.mjs +16 -16
  15. package/src/layout.mjs +1 -1
  16. package/src/module.mjs +439 -477
  17. package/src/packages.mjs +12 -4
  18. package/src/page-antd.mjs +98 -77
  19. package/src/page-webmcp.mjs +51 -0
  20. package/src/project.mjs +112 -105
  21. package/src/records.mjs +15 -15
  22. package/src/release-vite.mjs +1 -0
  23. package/src/release.mjs +455 -0
  24. package/src/templates.mjs +20 -20
  25. package/src/upgrade.mjs +415 -249
  26. package/templates/module/02-migrations.go.txt +10 -10
  27. package/templates/module/03-service.go.txt +52 -52
  28. package/templates/module/04-module.go.txt +12 -12
  29. package/templates/module/06-queries.ts.txt +15 -15
  30. package/templates/module/08-service_test.go.txt +9 -9
  31. package/templates/module/09-TransferPanel.tsx.txt +16 -0
  32. package/templates/module-runtime-test.go.txt +86 -86
  33. package/templates/module-transfer.go.txt +74 -74
  34. package/templates/project-v2/.agents/skills/arcbase/SKILL.md +32 -0
  35. package/templates/project-v2/.agents/skills/goa-service-designer/SKILL.md +31 -0
  36. package/templates/project-v2/AGENTS.md +38 -0
  37. package/templates/project-v2/DEVELOPMENT.md +115 -84
  38. package/templates/project-v2/README.md +76 -74
  39. package/templates/project-v2/RELEASE.md +88 -0
  40. package/templates/project-v2/TEAM-TRIAL.md +32 -32
  41. package/templates/project-v2/arcbase.release.json +23 -0
  42. package/templates/project-v2/cmd/server/main.go +62 -36
  43. package/templates/project-v2/cmd/server/modules.gen.go +6 -6
  44. package/templates/project-v2/eslint.config.mjs +9 -9
  45. package/templates/project-v2/internal/dashboard/dist/README.txt +1 -1
  46. package/templates/project-v2/internal/dashboard/embed.go +11 -11
  47. package/templates/project-v2/package.json +11 -4
  48. package/templates/project-v2/scripts/application-version.mjs +138 -0
  49. package/templates/project-v2/scripts/assets.mjs +13 -11
  50. package/templates/project-v2/scripts/build-backend.mjs +11 -9
  51. package/templates/project-v2/scripts/build.mjs +12 -0
  52. package/templates/project-v2/scripts/check-generated.mjs +79 -48
  53. package/templates/project-v2/scripts/config.mjs +55 -54
  54. package/templates/project-v2/scripts/dev-watch.mjs +78 -78
  55. package/templates/project-v2/scripts/dev.mjs +50 -49
  56. package/templates/project-v2/scripts/doctor.mjs +94 -94
  57. package/templates/project-v2/scripts/generate-contracts.mjs +88 -88
  58. package/templates/project-v2/scripts/go-build-identity/main.go +210 -0
  59. package/templates/project-v2/scripts/go.mjs +17 -15
  60. package/templates/project-v2/scripts/layout.mjs +10 -10
  61. package/templates/project-v2/scripts/lifecycle.mjs +245 -245
  62. package/templates/project-v2/scripts/openobserve-build.mjs +115 -0
  63. package/templates/project-v2/scripts/project-info.mjs +105 -0
  64. package/templates/project-v2/scripts/release-metadata.mjs +13 -0
  65. package/templates/project-v2/scripts/release-vite.mjs +23 -0
  66. package/templates/project-v2/scripts/release.mjs +3 -0
  67. package/templates/project-v2/scripts/run.mjs +11 -11
  68. package/templates/project-v2/scripts/sdk-integrity.mjs +39 -39
  69. package/templates/project-v2/scripts/setup.mjs +44 -44
  70. package/templates/project-v2/web/admin/index.html +5 -5
  71. package/templates/project-v2/web/admin/package.json +3 -2
  72. package/templates/project-v2/web/admin/src/brand.json +1 -1
  73. package/templates/project-v2/web/admin/src/extensions.gen.ts +6 -6
  74. package/templates/project-v2/web/admin/src/extensions.ts +1 -1
  75. package/templates/project-v2/web/admin/src/main.tsx +20 -14
  76. package/templates/project-v2/web/admin/tsconfig.json +17 -17
  77. package/templates/project-v2/web/admin/vite.config.ts +47 -27
  78. package/src/page.mjs +0 -66
  79. package/templates/module/07-Page.tsx.txt +0 -20
@@ -1,331 +1,331 @@
1
- const methods = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options']);
2
- const annotations = new Set(['title', 'description', 'example', 'examples', 'deprecated', 'readOnly', 'writeOnly', 'xml', 'externalDocs']);
3
- const supported = new Set(['$ref', 'type', 'properties', 'required', 'additionalProperties', 'items', 'enum', 'const', 'nullable', 'default', 'format', 'pattern', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf', 'minLength', 'maxLength', 'minItems', 'maxItems', 'uniqueItems', 'minProperties', 'maxProperties', 'anyOf', 'oneOf', 'allOf']);
4
- const quote = JSON.stringify;
5
- const identifier = name => /^[A-Za-z_$][\w$]*$/.test(name) && !['class', 'default', 'function', 'new', 'var', 'let', 'const', 'delete', 'export', 'import'].includes(name);
6
- const schemaName = name => 'Api' + name.replace(/[^A-Za-z0-9_$]/g, '_');
7
- const hasDefault = schema => Object.hasOwn(schema, 'default');
8
-
9
- function validate(schema) {
10
- if (!schema || typeof schema !== 'object' || Array.isArray(schema)) throw new Error('Expected an explicit OpenAPI schema');
11
- for (const key of Object.keys(schema)) if (!supported.has(key) && !annotations.has(key) && !key.startsWith('x-')) throw new Error(`Unsupported schema keyword: ${key}`);
12
- if (schema['x-arcbase-nullable'] !== undefined && typeof schema['x-arcbase-nullable'] !== 'boolean') throw new Error('Goa nullable metadata must be boolean');
13
- let allowed, combination;
14
- if (schema.$ref) { allowed = new Set(['$ref']); combination = 'ref'; }
15
- else if (schema.oneOf || schema.anyOf) {
16
- if (schema.oneOf && schema.anyOf) throw new Error('Unsupported combined oneOf/anyOf constraints');
17
- allowed = new Set([schema.oneOf ? 'oneOf' : 'anyOf', 'default', 'nullable']); combination = 'union';
18
- // Goa's tagged union body repeats type:object beside inline object branches.
19
- // Accept only that provably redundant type, never discard a restricting one.
20
- if (schema.type) {
21
- if (!(schema.oneOf ?? schema.anyOf).every(branch => !branch.$ref && branch.type === schema.type)) throw new Error('Unsupported union type constraint');
22
- allowed.add('type');
23
- }
24
- } else if (schema.enum || Object.hasOwn(schema, 'const')) {
25
- allowed = new Set(['type', schema.enum ? 'enum' : 'const', 'default', 'nullable']); combination = 'literal';
26
- if (schema.enum && (!schema.enum.length || schema.enum.some(value => value !== null && typeof value === 'object'))) throw new Error('Unsupported empty or non-scalar enum');
27
- // A literal restricts the same value as its scalar schema. Keep both checks;
28
- // enum membership does not make a pattern/range/format redundant.
29
- const constraints = schema.type === 'string' ? ['format', 'pattern', 'minLength', 'maxLength']
30
- : ['integer', 'number'].includes(schema.type) ? ['format', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf'] : [];
31
- constraints.forEach(key => allowed.add(key));
32
- }
33
- if (allowed) for (const key of Object.keys(schema)) {
34
- if (!allowed.has(key) && !annotations.has(key) && !key.startsWith('x-')) throw new Error(`Unsupported ${combination} validation sibling constraint: ${key}`);
35
- }
36
- }
37
-
38
- function referenceName(reference) {
39
- if (!reference.startsWith('#/components/schemas/')) throw new Error(`Unsupported external schema reference: ${reference}`);
40
- return reference.slice('#/components/schemas/'.length).replaceAll('~1', '/').replaceAll('~0', '~');
41
- }
42
-
43
- function model(document) {
44
- const schemas = document.components?.schemas ?? {};
45
- const expressionReferences = new WeakMap();
46
- function metadata(schema) {
47
- const value = {};
48
- if (schema.description !== undefined) value.description = schema.description;
49
- if (schema['x-filter'] !== undefined) value['x-filter'] = schema['x-filter'];
50
- return Object.keys(value).length ? `.meta(${quote(value)})` : '';
51
- }
52
- function object(schema, stack = new Set()) {
53
- validate(schema);
54
- if (schema.$ref) {
55
- const name = referenceName(schema.$ref);
56
- if (stack.has(name)) throw new Error(`Recursive allOf: ${name}`);
57
- const next = new Set(stack).add(name);
58
- if (!schemas[name]) throw new Error(`Missing schema reference: ${name}`);
59
- return object(schemas[name], next);
60
- }
61
- if (!schema.allOf) return schema;
62
- if (schema.type && schema.type !== 'object') throw new Error('allOf currently requires explicit object schemas');
63
- const result = { type: 'object', properties: {}, required: [] };
64
- for (const branch of schema.allOf) {
65
- const value = object(branch, stack);
66
- if (value.type !== 'object') throw new Error('allOf currently requires explicit object schemas');
67
- for (const key of Object.keys(value)) {
68
- if (!['type', 'properties', 'required'].includes(key) && !annotations.has(key) && !key.startsWith('x-')) throw new Error(`Unsupported allOf branch constraint: ${key}`);
69
- }
70
- for (const [key, property] of Object.entries(value.properties ?? {})) {
71
- if (result.properties[key] && quote(result.properties[key]) !== quote(property)) throw new Error(`Conflicting allOf property: ${key}`);
72
- result.properties[key] = property;
73
- }
74
- result.required.push(...(value.required ?? []));
75
- }
76
- const { allOf: _, ...rest } = schema;
77
- for (const [key, property] of Object.entries(rest.properties ?? {})) {
78
- if (result.properties[key] && quote(result.properties[key]) !== quote(property)) throw new Error(`Conflicting allOf property: ${key}`);
79
- }
80
- return { ...result, ...rest, properties: { ...result.properties, ...rest.properties }, required: [...new Set([...result.required, ...(rest.required ?? [])])] };
81
- }
82
-
83
- function type(raw, input = false) {
84
- validate(raw);
85
- const schema = raw.allOf ? object(raw) : raw;
86
- let result;
87
- if (schema.$ref) result = schemaName(referenceName(schema.$ref)) + (input ? 'Input' : '');
88
- else if (schema.enum) result = schema.enum.map(quote).join(' | ');
89
- else if (Object.hasOwn(schema, 'const')) result = quote(schema.const);
90
- else if (schema.oneOf || schema.anyOf) result = (schema.oneOf ?? schema.anyOf).map(item => `(${type(item, input)})`).join(' | ');
91
- else if (schema['x-arcbase-json-value'] === true) result = 'JSONValue';
92
- else switch (schema.type) {
93
- case 'string': result = schema.format === 'binary' ? 'Blob' : 'string'; break;
94
- case 'integer': case 'number': result = 'number'; break;
95
- case 'boolean': result = 'boolean'; break;
96
- case 'null': result = 'null'; break;
97
- case 'array': result = `Array<${type(schema.items, input)}>`; break;
98
- case 'object': {
99
- const required = new Set(schema.required ?? []);
100
- const props = Object.entries(schema.properties ?? {}).map(([key, field]) => `${quote(key)}${!required.has(key) && (input || !hasDefault(field)) ? '?' : ''}: ${type(field, input)}`);
101
- if (schema.additionalProperties === true) props.push('[key: string]: JSONValue');
102
- else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') props.push(`[key: string]: ${type(schema.additionalProperties, input)}`);
103
- result = `{ ${props.join('; ')} }`; break;
104
- }
105
- default: throw new Error(`Unsupported or untyped schema: ${quote(schema)}`);
106
- }
107
- return (schema.nullable || schema['x-arcbase-nullable'] === true) && schema.type !== 'null' ? `(${result}) | null` : result;
108
- }
109
-
110
- function expression(raw) {
111
- if (expressionReferences.has(raw)) return expressionReferences.get(raw);
112
- validate(raw);
113
- const schema = raw.allOf ? object(raw) : raw;
114
- let result;
115
- if (schema.$ref) result = `z.lazy(() => ${schemaName(referenceName(schema.$ref))}Schema)`;
116
- else if (schema.enum || Object.hasOwn(schema, 'const')) {
117
- result = schema.enum ? schema.enum.length === 1 ? `z.literal(${quote(schema.enum[0])})` : `z.union([${schema.enum.map(item => `z.literal(${quote(item)})`).join(', ')}])` : `z.literal(${quote(schema.const)})`;
118
- if (schema.type) {
119
- const { enum: _enum, const: _const, nullable: _nullable, default: _default, ...scalar } = schema;
120
- result = `z.intersection(${result}, ${expression(scalar)})`;
121
- }
122
- }
123
- else if (schema.oneOf || schema.anyOf) {
124
- const alternatives = schema.oneOf ?? schema.anyOf;
125
- result = alternatives.length === 1 ? expression(alternatives[0]) : `z.${schema.oneOf ? 'xor' : 'union'}([${alternatives.map(expression).join(', ')}])`;
126
- } else if (schema['x-arcbase-json-value'] === true) result = 'z.json()';
127
- else switch (schema.type) {
128
- case 'string': {
129
- const formats = { 'date-time': 'z.iso.datetime({ offset: true })', date: 'z.iso.date()', uuid: 'z.uuid()', email: 'z.email()', uri: 'z.url()', url: 'z.url()', byte: 'z.base64()', binary: 'z.custom<Blob>(value => typeof Blob !== "undefined" && value instanceof Blob)' };
130
- if (schema.format && !formats[schema.format] && !['password', 'hostname', 'ipv4', 'ipv6'].includes(schema.format)) throw new Error(`Unsupported string format: ${schema.format}`);
131
- result = formats[schema.format] ?? 'z.string()';
132
- if (schema.format === 'hostname') result += '.refine(value => /^(?=.{1,253}$)(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value))';
133
- if (schema.format === 'ipv4' || schema.format === 'ipv6') result = `z.${schema.format}()`;
134
- if (schema.minLength !== undefined) result += `.min(${schema.minLength})`;
135
- if (schema.maxLength !== undefined) result += `.max(${schema.maxLength})`;
136
- if (schema.pattern) result += `.regex(new RegExp(${quote(schema.pattern)}))`;
137
- break;
138
- }
139
- case 'integer': case 'number': {
140
- const formats = schema.type === 'integer' ? ['int32', 'int64'] : ['double'];
141
- if (schema.format && !formats.includes(schema.format)) throw new Error(`Unsupported numeric format: ${schema.format}`);
142
- result = schema.type === 'integer' ? 'z.int()' : 'z.number()';
143
- if (schema.format === 'int32') result += '.min(-2147483648).max(2147483647)';
144
- if (schema.minimum !== undefined) result += `.${schema.exclusiveMinimum === true ? 'gt' : 'min'}(${schema.minimum})`;
145
- if (schema.maximum !== undefined) result += `.${schema.exclusiveMaximum === true ? 'lt' : 'max'}(${schema.maximum})`;
146
- if (typeof schema.exclusiveMinimum === 'number') result += `.gt(${schema.exclusiveMinimum})`;
147
- if (typeof schema.exclusiveMaximum === 'number') result += `.lt(${schema.exclusiveMaximum})`;
148
- if (schema.multipleOf !== undefined) result += `.multipleOf(${schema.multipleOf})`;
149
- break;
150
- }
151
- case 'boolean': result = 'z.boolean()'; break;
152
- case 'null': result = 'z.null()'; break;
153
- case 'array':
154
- result = `z.array(${expression(schema.items)})`;
155
- if (schema.minItems !== undefined) result += `.min(${schema.minItems})`;
156
- if (schema.maxItems !== undefined) result += `.max(${schema.maxItems})`;
157
- if (schema.uniqueItems) result += '.refine(items => new Set(items.map(item => JSON.stringify(item))).size === items.length)';
158
- break;
159
- case 'object': {
160
- const required = new Set(schema.required ?? []);
161
- const fields = Object.entries(schema.properties ?? {}).map(([name, field]) => {
162
- let value = expression(field);
163
- if (!required.has(name) && !hasDefault(field)) value += '.optional()';
164
- if (!required.has(name) && hasDefault(field)) value += `.prefault(${quote(field.default)})`;
165
- value += metadata(field);
166
- return `${quote(name)}: ${value}`;
167
- });
168
- result = `z.${schema.additionalProperties ? 'object' : 'strictObject'}({ ${fields.join(', ')} })`;
169
- if (schema.additionalProperties === true) result += '.catchall(z.json())';
170
- else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') result += `.catchall(${expression(schema.additionalProperties)})`;
171
- if (schema.minProperties !== undefined) result += `.refine(value => Object.keys(value).length >= ${schema.minProperties})`;
172
- if (schema.maxProperties !== undefined) result += `.refine(value => Object.keys(value).length <= ${schema.maxProperties})`;
173
- break;
174
- }
175
- default: throw new Error(`Unsupported or untyped schema: ${quote(schema)}`);
176
- }
177
- if ((schema.nullable || schema['x-arcbase-nullable'] === true) && schema.type !== 'null') result += '.nullable()';
178
- return result;
179
- }
180
-
181
- function dependencies(values) {
182
- const names = new Set();
183
- function visit(value) {
184
- if (!value || typeof value !== 'object') return;
185
- if (value.$ref) {
186
- const name = referenceName(value.$ref);
187
- if (!schemas[name]) throw new Error(`Missing schema reference: ${name}`);
188
- if (!names.has(name)) { names.add(name); visit(schemas[name]); }
189
- }
190
- for (const child of Object.values(value)) visit(child);
191
- }
192
- values.forEach(visit);
193
- return [...names].sort();
194
- }
195
- return { type, expression, dependencies, schemas, reference: (schema, name) => expressionReferences.set(schema, name) };
196
- }
197
-
198
- function contentSchema(content) {
199
- if (!content) return undefined;
200
- const values = Object.entries(content);
201
- const chosen = values.find(([name]) => name === 'application/json') ?? values.find(([name]) => name === 'application/vnd.goa.error' || name.endsWith('+json'));
202
- if (!chosen) throw new Error(`Expected a JSON media type, got ${values.map(([name]) => name).join(', ')}`);
203
- return chosen[1].schema;
204
- }
205
-
206
- function inputSchema(operation, transport) {
207
- const fields = {}, required = [];
208
- for (const location of ['path', 'query', 'header']) {
209
- const parameters = (operation.parameters ?? []).filter(item => item.in === location);
210
- if (!parameters.length) continue;
211
- const name = { path: 'params', query: 'query', header: 'headers' }[location];
212
- const schema = { type: 'object', properties: {}, required: [] };
213
- for (const parameter of parameters) {
214
- if (!parameter.schema || schema.properties[parameter.name]) throw new Error('Duplicate or unsupported parameter');
215
- schema.properties[parameter.name] = parameter.schema;
216
- if (parameter.required) schema.required.push(parameter.name);
217
- }
218
- if (!schema.required.length) schema.default = {};
219
- fields[name] = schema;
220
- if (schema.required.length) required.push(name);
221
- }
222
- if (operation.requestBody) {
223
- if (transport === 'multipart') {
224
- const content = operation.requestBody.content?.['multipart/form-data'];
225
- if (!content?.schema) throw new Error('Multipart operation requires a multipart/form-data request schema');
226
- fields.body = content.schema;
227
- } else fields.body = contentSchema(operation.requestBody.content);
228
- if (operation.requestBody.required) required.push('body');
229
- }
230
- return { type: 'object', properties: fields, required };
231
- }
232
-
233
- /** Render domain-local TS/Zod modules from one matching Goa generation. */
234
- export function renderContracts(document, policySet) {
235
- if (!/^3\.(0|1)\./.test(document.openapi ?? '')) throw new Error('Expected OpenAPI 3.0 or 3.1');
236
- if (policySet.version !== 1) throw new Error('Unsupported ArcBase policy version');
237
- const policies = new Map();
238
- for (const policy of policySet.operations) {
239
- if (policies.has(policy.id)) throw new Error(`Duplicate policy: ${policy.id}`);
240
- policies.set(policy.id, policy);
241
- }
242
- const groups = new Map(), used = new Set();
243
- for (const [path, verbs] of Object.entries(document.paths ?? {})) for (const [method, operation] of Object.entries(verbs)) {
244
- if (!methods.has(method)) continue;
245
- const policy = policies.get(operation.operationId);
246
- if (!policy) throw new Error(`Missing policy for ${operation.operationId}`);
247
- if (used.has(policy.id)) throw new Error(`Duplicate operation: ${policy.id}`);
248
- if (policy.path !== path || policy.method !== method.toUpperCase()) throw new Error(`Policy differs from OpenAPI: ${policy.id}`);
249
- if (!identifier(policy.id)) throw new Error(`operationId must be a TypeScript identifier: ${policy.id}`);
250
- const group = operation.tags?.[0];
251
- if (!group || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(group)) throw new Error(`Invalid domain tag for ${policy.id}`);
252
- const responses = {}, errors = {}, mediaTypes = {};
253
- for (const [status, response] of Object.entries(operation.responses ?? {})) {
254
- if (!/^\d{3}$/.test(status)) throw new Error(`Unsupported response status: ${status}`);
255
- if (+status >= 200 && +status < 300) {
256
- responses[status] = policy.transport === 'sse'
257
- ? response.content?.['text/event-stream']?.schema ?? null
258
- : ['json', 'multipart'].includes(policy.transport) && response.content ? contentSchema(response.content) : null;
259
- const contentTypes = Object.entries(response.headers ?? {}).find(([name]) => name.toLowerCase() === 'content-type')?.[1]?.schema?.enum;
260
- mediaTypes[status] = ['file','csv'].includes(policy.transport) && Array.isArray(contentTypes) && contentTypes.every(value => typeof value === 'string')
261
- ? contentTypes : Object.keys(response.content ?? {});
262
- }
263
- else if (response.content) errors[status] = contentSchema(response.content);
264
- }
265
- if (!Object.keys(responses).length) throw new Error(`Missing success response: ${policy.id}`);
266
- const entry = { policy, input: inputSchema(operation, policy.transport), responses, errors, mediaTypes };
267
- if (!groups.has(group)) groups.set(group, []);
268
- groups.get(group).push(entry);
269
- used.add(policy.id);
270
- }
271
- // JSON-RPC-only MCP routes come from the same evaluated design and policy
272
- // generator, but are not ordinary HTTP OpenAPI operations.
273
- for (const policy of policies.values()) if (!used.has(policy.id) && policy.transport === 'mcp' && policy.method === 'POST' && !policy.protocol) {
274
- if (!policySet.mcpTools?.length || policy.access.kind !== 'authenticated' || !policy.apiKey.allowed || policy.apiKey.scopeMode !== 'tool'
275
- || policy.audit.mode !== 'authentication' || policy.audit.recordRequest || policy.audit.recordResponse || !identifier(policy.id)) {
276
- throw new Error('Invalid native MCP protocol policy');
277
- }
278
- if (!groups.has('integration_mcp')) groups.set('integration_mcp', []);
279
- groups.get('integration_mcp').push({ policy, input: inputSchema({}, 'mcp'), responses: { 200: null }, errors: {}, mediaTypes: { 200: ['application/json'] } });
280
- used.add(policy.id);
281
- }
282
- for (const policy of policies.values()) if (!used.has(policy.id)) {
283
- const protocol = policy.protocol;
284
- const owner = protocol && policies.get(protocol.owner);
285
- if (!protocol || protocol.kind !== 'mcp_stateless_method_not_allowed' || !owner || !used.has(owner.id)
286
- || owner.transport !== 'mcp' || owner.method !== 'POST' || owner.protocol
287
- || policy.transport !== 'mcp' || !['GET', 'DELETE'].includes(policy.method) || policy.path !== owner.path
288
- || policy.successStatus || policy.audit.mode !== 'none'
289
- || quote(policy.access) !== quote(owner.access) || quote(policy.apiKey) !== quote(owner.apiKey)) throw new Error('Policy set contains an absent or invalid protocol operation');
290
- used.add(policy.id);
291
- }
292
- const modeler = model(document), output = {};
293
- for (const [group, entries] of [...groups].sort(([a], [b]) => a.localeCompare(b))) {
294
- const lines = ['// Generated from Goa OpenAPI and ArcBase policies. DO NOT EDIT.', "import { z } from 'zod';", 'export type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue };', ''];
295
- const names = modeler.dependencies(entries.flatMap(entry => [entry.input, entry.responses, entry.errors]));
296
- if (new Set(names.map(schemaName)).size !== names.length) throw new Error(`Colliding schema names in ${group}`);
297
- for (const name of names) {
298
- lines.push(`export type ${schemaName(name)} = ${modeler.type(modeler.schemas[name])};`);
299
- lines.push(`export type ${schemaName(name)}Input = ${modeler.type(modeler.schemas[name], true)};`);
300
- lines.push(`export const ${schemaName(name)}Schema: z.ZodType<${schemaName(name)}, ${schemaName(name)}Input> = z.lazy(() => ${modeler.expression(modeler.schemas[name])});`, '');
301
- }
302
- for (const entry of entries.sort((a, b) => a.policy.id.localeCompare(b.policy.id))) {
303
- const response = values => Object.entries(values).map(([status, schema]) => `${status}: ${schema ? modeler.expression(schema) : 'z.undefined()'}`).join(', ');
304
- const query = entry.input.properties.query;
305
- if (query) {
306
- const name = `${entry.policy.id}QuerySchema`;
307
- lines.push(`export const ${name} = ${modeler.expression(query)};`, '');
308
- modeler.reference(query, name);
309
- }
310
- lines.push(`export const ${entry.policy.id} = {`);
311
- lines.push(` id: ${quote(entry.policy.id)}, method: ${quote(entry.policy.method)}, path: ${quote(entry.policy.path)}, kind: ${quote(entry.policy.transport)},`);
312
- lines.push(` access: ${quote(entry.policy.access)}, apiKey: ${quote(entry.policy.apiKey)},`);
313
- if (entry.policy.sse) lines.push(` sse: ${quote(entry.policy.sse)},`);
314
- if (query) lines.push(` query: ${entry.policy.id}QuerySchema,`);
315
- lines.push(` input: ${modeler.expression(entry.input)}${entry.input.required.length ? '' : '.prefault({})'},`);
316
- lines.push(` responses: { ${response(entry.responses)} }, errors: { ${response(entry.errors)} }, mediaTypes: ${quote(entry.mediaTypes)},`, '} as const;', '');
317
- }
318
- output[`${group}.ts`] = lines.join('\n') + '\n';
319
- }
320
- if (policySet.mcpTools) {
321
- const tools = policySet.mcpTools.map(tool => {
322
- const source = policies.get(tool.operationId);
323
- if (!source || source.method !== 'GET' || source.transport !== 'json' || !source.apiKey.allowed || source.access.kind !== 'permission' || source.access.permissions?.length !== 1) {
324
- throw new Error(`MCP tool ${tool.name} must reference a read policy`);
325
- }
326
- return { ...tool, permission: source.access.permissions[0] };
327
- });
328
- output['mcp-tools.ts'] = '// Generated from Goa-AI tool declarations and ArcBase read policies. DO NOT EDIT.\nexport const mcpTools = ' + JSON.stringify(tools, null, 2) + ' as const;\n';
329
- }
330
- return output;
331
- }
1
+ const methods = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options']);
2
+ const annotations = new Set(['title', 'description', 'example', 'examples', 'deprecated', 'readOnly', 'writeOnly', 'xml', 'externalDocs']);
3
+ const supported = new Set(['$ref', 'type', 'properties', 'required', 'additionalProperties', 'items', 'enum', 'const', 'nullable', 'default', 'format', 'pattern', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf', 'minLength', 'maxLength', 'minItems', 'maxItems', 'uniqueItems', 'minProperties', 'maxProperties', 'anyOf', 'oneOf', 'allOf']);
4
+ const quote = JSON.stringify;
5
+ const identifier = name => /^[A-Za-z_$][\w$]*$/.test(name) && !['class', 'default', 'function', 'new', 'var', 'let', 'const', 'delete', 'export', 'import'].includes(name);
6
+ const schemaName = name => 'Api' + name.replace(/[^A-Za-z0-9_$]/g, '_');
7
+ const hasDefault = schema => Object.hasOwn(schema, 'default');
8
+
9
+ function validate(schema) {
10
+ if (!schema || typeof schema !== 'object' || Array.isArray(schema)) throw new Error('Expected an explicit OpenAPI schema');
11
+ for (const key of Object.keys(schema)) if (!supported.has(key) && !annotations.has(key) && !key.startsWith('x-')) throw new Error(`Unsupported schema keyword: ${key}`);
12
+ if (schema['x-arcbase-nullable'] !== undefined && typeof schema['x-arcbase-nullable'] !== 'boolean') throw new Error('Goa nullable metadata must be boolean');
13
+ let allowed, combination;
14
+ if (schema.$ref) { allowed = new Set(['$ref']); combination = 'ref'; }
15
+ else if (schema.oneOf || schema.anyOf) {
16
+ if (schema.oneOf && schema.anyOf) throw new Error('Unsupported combined oneOf/anyOf constraints');
17
+ allowed = new Set([schema.oneOf ? 'oneOf' : 'anyOf', 'default', 'nullable']); combination = 'union';
18
+ // Goa's tagged union body repeats type:object beside inline object branches.
19
+ // Accept only that provably redundant type, never discard a restricting one.
20
+ if (schema.type) {
21
+ if (!(schema.oneOf ?? schema.anyOf).every(branch => !branch.$ref && branch.type === schema.type)) throw new Error('Unsupported union type constraint');
22
+ allowed.add('type');
23
+ }
24
+ } else if (schema.enum || Object.hasOwn(schema, 'const')) {
25
+ allowed = new Set(['type', schema.enum ? 'enum' : 'const', 'default', 'nullable']); combination = 'literal';
26
+ if (schema.enum && (!schema.enum.length || schema.enum.some(value => value !== null && typeof value === 'object'))) throw new Error('Unsupported empty or non-scalar enum');
27
+ // A literal restricts the same value as its scalar schema. Keep both checks;
28
+ // enum membership does not make a pattern/range/format redundant.
29
+ const constraints = schema.type === 'string' ? ['format', 'pattern', 'minLength', 'maxLength']
30
+ : ['integer', 'number'].includes(schema.type) ? ['format', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf'] : [];
31
+ constraints.forEach(key => allowed.add(key));
32
+ }
33
+ if (allowed) for (const key of Object.keys(schema)) {
34
+ if (!allowed.has(key) && !annotations.has(key) && !key.startsWith('x-')) throw new Error(`Unsupported ${combination} validation sibling constraint: ${key}`);
35
+ }
36
+ }
37
+
38
+ function referenceName(reference) {
39
+ if (!reference.startsWith('#/components/schemas/')) throw new Error(`Unsupported external schema reference: ${reference}`);
40
+ return reference.slice('#/components/schemas/'.length).replaceAll('~1', '/').replaceAll('~0', '~');
41
+ }
42
+
43
+ function model(document) {
44
+ const schemas = document.components?.schemas ?? {};
45
+ const expressionReferences = new WeakMap();
46
+ function metadata(schema) {
47
+ const value = {};
48
+ if (schema.description !== undefined) value.description = schema.description;
49
+ if (schema['x-filter'] !== undefined) value['x-filter'] = schema['x-filter'];
50
+ return Object.keys(value).length ? `.meta(${quote(value)})` : '';
51
+ }
52
+ function object(schema, stack = new Set()) {
53
+ validate(schema);
54
+ if (schema.$ref) {
55
+ const name = referenceName(schema.$ref);
56
+ if (stack.has(name)) throw new Error(`Recursive allOf: ${name}`);
57
+ const next = new Set(stack).add(name);
58
+ if (!schemas[name]) throw new Error(`Missing schema reference: ${name}`);
59
+ return object(schemas[name], next);
60
+ }
61
+ if (!schema.allOf) return schema;
62
+ if (schema.type && schema.type !== 'object') throw new Error('allOf currently requires explicit object schemas');
63
+ const result = { type: 'object', properties: {}, required: [] };
64
+ for (const branch of schema.allOf) {
65
+ const value = object(branch, stack);
66
+ if (value.type !== 'object') throw new Error('allOf currently requires explicit object schemas');
67
+ for (const key of Object.keys(value)) {
68
+ if (!['type', 'properties', 'required'].includes(key) && !annotations.has(key) && !key.startsWith('x-')) throw new Error(`Unsupported allOf branch constraint: ${key}`);
69
+ }
70
+ for (const [key, property] of Object.entries(value.properties ?? {})) {
71
+ if (result.properties[key] && quote(result.properties[key]) !== quote(property)) throw new Error(`Conflicting allOf property: ${key}`);
72
+ result.properties[key] = property;
73
+ }
74
+ result.required.push(...(value.required ?? []));
75
+ }
76
+ const { allOf: _, ...rest } = schema;
77
+ for (const [key, property] of Object.entries(rest.properties ?? {})) {
78
+ if (result.properties[key] && quote(result.properties[key]) !== quote(property)) throw new Error(`Conflicting allOf property: ${key}`);
79
+ }
80
+ return { ...result, ...rest, properties: { ...result.properties, ...rest.properties }, required: [...new Set([...result.required, ...(rest.required ?? [])])] };
81
+ }
82
+
83
+ function type(raw, input = false) {
84
+ validate(raw);
85
+ const schema = raw.allOf ? object(raw) : raw;
86
+ let result;
87
+ if (schema.$ref) result = schemaName(referenceName(schema.$ref)) + (input ? 'Input' : '');
88
+ else if (schema.enum) result = schema.enum.map(quote).join(' | ');
89
+ else if (Object.hasOwn(schema, 'const')) result = quote(schema.const);
90
+ else if (schema.oneOf || schema.anyOf) result = (schema.oneOf ?? schema.anyOf).map(item => `(${type(item, input)})`).join(' | ');
91
+ else if (schema['x-arcbase-json-value'] === true) result = 'JSONValue';
92
+ else switch (schema.type) {
93
+ case 'string': result = schema.format === 'binary' ? 'Blob' : 'string'; break;
94
+ case 'integer': case 'number': result = 'number'; break;
95
+ case 'boolean': result = 'boolean'; break;
96
+ case 'null': result = 'null'; break;
97
+ case 'array': result = `Array<${type(schema.items, input)}>`; break;
98
+ case 'object': {
99
+ const required = new Set(schema.required ?? []);
100
+ const props = Object.entries(schema.properties ?? {}).map(([key, field]) => `${quote(key)}${!required.has(key) && (input || !hasDefault(field)) ? '?' : ''}: ${type(field, input)}`);
101
+ if (schema.additionalProperties === true) props.push('[key: string]: JSONValue');
102
+ else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') props.push(`[key: string]: ${type(schema.additionalProperties, input)}`);
103
+ result = `{ ${props.join('; ')} }`; break;
104
+ }
105
+ default: throw new Error(`Unsupported or untyped schema: ${quote(schema)}`);
106
+ }
107
+ return (schema.nullable || schema['x-arcbase-nullable'] === true) && schema.type !== 'null' ? `(${result}) | null` : result;
108
+ }
109
+
110
+ function expression(raw) {
111
+ if (expressionReferences.has(raw)) return expressionReferences.get(raw);
112
+ validate(raw);
113
+ const schema = raw.allOf ? object(raw) : raw;
114
+ let result;
115
+ if (schema.$ref) result = `z.lazy(() => ${schemaName(referenceName(schema.$ref))}Schema)`;
116
+ else if (schema.enum || Object.hasOwn(schema, 'const')) {
117
+ result = schema.enum ? schema.enum.length === 1 ? `z.literal(${quote(schema.enum[0])})` : `z.union([${schema.enum.map(item => `z.literal(${quote(item)})`).join(', ')}])` : `z.literal(${quote(schema.const)})`;
118
+ if (schema.type) {
119
+ const { enum: _enum, const: _const, nullable: _nullable, default: _default, ...scalar } = schema;
120
+ result = `z.intersection(${result}, ${expression(scalar)})`;
121
+ }
122
+ }
123
+ else if (schema.oneOf || schema.anyOf) {
124
+ const alternatives = schema.oneOf ?? schema.anyOf;
125
+ result = alternatives.length === 1 ? expression(alternatives[0]) : `z.${schema.oneOf ? 'xor' : 'union'}([${alternatives.map(expression).join(', ')}])`;
126
+ } else if (schema['x-arcbase-json-value'] === true) result = 'z.json()';
127
+ else switch (schema.type) {
128
+ case 'string': {
129
+ const formats = { 'date-time': 'z.iso.datetime({ offset: true })', date: 'z.iso.date()', uuid: 'z.uuid()', email: 'z.email()', uri: 'z.url()', url: 'z.url()', byte: 'z.base64()', binary: 'z.custom<Blob>(value => typeof Blob !== "undefined" && value instanceof Blob)' };
130
+ if (schema.format && !formats[schema.format] && !['password', 'hostname', 'ipv4', 'ipv6'].includes(schema.format)) throw new Error(`Unsupported string format: ${schema.format}`);
131
+ result = formats[schema.format] ?? 'z.string()';
132
+ if (schema.format === 'hostname') result += '.refine(value => /^(?=.{1,253}$)(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value))';
133
+ if (schema.format === 'ipv4' || schema.format === 'ipv6') result = `z.${schema.format}()`;
134
+ if (schema.minLength !== undefined) result += `.min(${schema.minLength})`;
135
+ if (schema.maxLength !== undefined) result += `.max(${schema.maxLength})`;
136
+ if (schema.pattern) result += `.regex(new RegExp(${quote(schema.pattern)}))`;
137
+ break;
138
+ }
139
+ case 'integer': case 'number': {
140
+ const formats = schema.type === 'integer' ? ['int32', 'int64'] : ['double'];
141
+ if (schema.format && !formats.includes(schema.format)) throw new Error(`Unsupported numeric format: ${schema.format}`);
142
+ result = schema.type === 'integer' ? 'z.int()' : 'z.number()';
143
+ if (schema.format === 'int32') result += '.min(-2147483648).max(2147483647)';
144
+ if (schema.minimum !== undefined) result += `.${schema.exclusiveMinimum === true ? 'gt' : 'min'}(${schema.minimum})`;
145
+ if (schema.maximum !== undefined) result += `.${schema.exclusiveMaximum === true ? 'lt' : 'max'}(${schema.maximum})`;
146
+ if (typeof schema.exclusiveMinimum === 'number') result += `.gt(${schema.exclusiveMinimum})`;
147
+ if (typeof schema.exclusiveMaximum === 'number') result += `.lt(${schema.exclusiveMaximum})`;
148
+ if (schema.multipleOf !== undefined) result += `.multipleOf(${schema.multipleOf})`;
149
+ break;
150
+ }
151
+ case 'boolean': result = 'z.boolean()'; break;
152
+ case 'null': result = 'z.null()'; break;
153
+ case 'array':
154
+ result = `z.array(${expression(schema.items)})`;
155
+ if (schema.minItems !== undefined) result += `.min(${schema.minItems})`;
156
+ if (schema.maxItems !== undefined) result += `.max(${schema.maxItems})`;
157
+ if (schema.uniqueItems) result += '.refine(items => new Set(items.map(item => JSON.stringify(item))).size === items.length)';
158
+ break;
159
+ case 'object': {
160
+ const required = new Set(schema.required ?? []);
161
+ const fields = Object.entries(schema.properties ?? {}).map(([name, field]) => {
162
+ let value = expression(field);
163
+ if (!required.has(name) && !hasDefault(field)) value += '.optional()';
164
+ if (!required.has(name) && hasDefault(field)) value += `.prefault(${quote(field.default)})`;
165
+ value += metadata(field);
166
+ return `${quote(name)}: ${value}`;
167
+ });
168
+ result = `z.${schema.additionalProperties ? 'object' : 'strictObject'}({ ${fields.join(', ')} })`;
169
+ if (schema.additionalProperties === true) result += '.catchall(z.json())';
170
+ else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') result += `.catchall(${expression(schema.additionalProperties)})`;
171
+ if (schema.minProperties !== undefined) result += `.refine(value => Object.keys(value).length >= ${schema.minProperties})`;
172
+ if (schema.maxProperties !== undefined) result += `.refine(value => Object.keys(value).length <= ${schema.maxProperties})`;
173
+ break;
174
+ }
175
+ default: throw new Error(`Unsupported or untyped schema: ${quote(schema)}`);
176
+ }
177
+ if ((schema.nullable || schema['x-arcbase-nullable'] === true) && schema.type !== 'null') result += '.nullable()';
178
+ return result;
179
+ }
180
+
181
+ function dependencies(values) {
182
+ const names = new Set();
183
+ function visit(value) {
184
+ if (!value || typeof value !== 'object') return;
185
+ if (value.$ref) {
186
+ const name = referenceName(value.$ref);
187
+ if (!schemas[name]) throw new Error(`Missing schema reference: ${name}`);
188
+ if (!names.has(name)) { names.add(name); visit(schemas[name]); }
189
+ }
190
+ for (const child of Object.values(value)) visit(child);
191
+ }
192
+ values.forEach(visit);
193
+ return [...names].sort();
194
+ }
195
+ return { type, expression, dependencies, schemas, reference: (schema, name) => expressionReferences.set(schema, name) };
196
+ }
197
+
198
+ function contentSchema(content) {
199
+ if (!content) return undefined;
200
+ const values = Object.entries(content);
201
+ const chosen = values.find(([name]) => name === 'application/json') ?? values.find(([name]) => name === 'application/vnd.goa.error' || name.endsWith('+json'));
202
+ if (!chosen) throw new Error(`Expected a JSON media type, got ${values.map(([name]) => name).join(', ')}`);
203
+ return chosen[1].schema;
204
+ }
205
+
206
+ function inputSchema(operation, transport) {
207
+ const fields = {}, required = [];
208
+ for (const location of ['path', 'query', 'header']) {
209
+ const parameters = (operation.parameters ?? []).filter(item => item.in === location);
210
+ if (!parameters.length) continue;
211
+ const name = { path: 'params', query: 'query', header: 'headers' }[location];
212
+ const schema = { type: 'object', properties: {}, required: [] };
213
+ for (const parameter of parameters) {
214
+ if (!parameter.schema || schema.properties[parameter.name]) throw new Error('Duplicate or unsupported parameter');
215
+ schema.properties[parameter.name] = parameter.schema;
216
+ if (parameter.required) schema.required.push(parameter.name);
217
+ }
218
+ if (!schema.required.length) schema.default = {};
219
+ fields[name] = schema;
220
+ if (schema.required.length) required.push(name);
221
+ }
222
+ if (operation.requestBody) {
223
+ if (transport === 'multipart') {
224
+ const content = operation.requestBody.content?.['multipart/form-data'];
225
+ if (!content?.schema) throw new Error('Multipart operation requires a multipart/form-data request schema');
226
+ fields.body = content.schema;
227
+ } else fields.body = contentSchema(operation.requestBody.content);
228
+ if (operation.requestBody.required) required.push('body');
229
+ }
230
+ return { type: 'object', properties: fields, required };
231
+ }
232
+
233
+ /** Render domain-local TS/Zod modules from one matching Goa generation. */
234
+ export function renderContracts(document, policySet) {
235
+ if (!/^3\.(0|1)\./.test(document.openapi ?? '')) throw new Error('Expected OpenAPI 3.0 or 3.1');
236
+ if (policySet.version !== 1) throw new Error('Unsupported ArcBase policy version');
237
+ const policies = new Map();
238
+ for (const policy of policySet.operations) {
239
+ if (policies.has(policy.id)) throw new Error(`Duplicate policy: ${policy.id}`);
240
+ policies.set(policy.id, policy);
241
+ }
242
+ const groups = new Map(), used = new Set();
243
+ for (const [path, verbs] of Object.entries(document.paths ?? {})) for (const [method, operation] of Object.entries(verbs)) {
244
+ if (!methods.has(method)) continue;
245
+ const policy = policies.get(operation.operationId);
246
+ if (!policy) throw new Error(`Missing policy for ${operation.operationId}`);
247
+ if (used.has(policy.id)) throw new Error(`Duplicate operation: ${policy.id}`);
248
+ if (policy.path !== path || policy.method !== method.toUpperCase()) throw new Error(`Policy differs from OpenAPI: ${policy.id}`);
249
+ if (!identifier(policy.id)) throw new Error(`operationId must be a TypeScript identifier: ${policy.id}`);
250
+ const group = operation.tags?.[0];
251
+ if (!group || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(group)) throw new Error(`Invalid domain tag for ${policy.id}`);
252
+ const responses = {}, errors = {}, mediaTypes = {};
253
+ for (const [status, response] of Object.entries(operation.responses ?? {})) {
254
+ if (!/^\d{3}$/.test(status)) throw new Error(`Unsupported response status: ${status}`);
255
+ if (+status >= 200 && +status < 300) {
256
+ responses[status] = policy.transport === 'sse'
257
+ ? response.content?.['text/event-stream']?.schema ?? null
258
+ : ['json', 'multipart'].includes(policy.transport) && response.content ? contentSchema(response.content) : null;
259
+ const contentTypes = Object.entries(response.headers ?? {}).find(([name]) => name.toLowerCase() === 'content-type')?.[1]?.schema?.enum;
260
+ mediaTypes[status] = ['file','csv'].includes(policy.transport) && Array.isArray(contentTypes) && contentTypes.every(value => typeof value === 'string')
261
+ ? contentTypes : Object.keys(response.content ?? {});
262
+ }
263
+ else if (response.content) errors[status] = contentSchema(response.content);
264
+ }
265
+ if (!Object.keys(responses).length) throw new Error(`Missing success response: ${policy.id}`);
266
+ const entry = { policy, input: inputSchema(operation, policy.transport), responses, errors, mediaTypes };
267
+ if (!groups.has(group)) groups.set(group, []);
268
+ groups.get(group).push(entry);
269
+ used.add(policy.id);
270
+ }
271
+ // JSON-RPC-only MCP routes come from the same evaluated design and policy
272
+ // generator, but are not ordinary HTTP OpenAPI operations.
273
+ for (const policy of policies.values()) if (!used.has(policy.id) && policy.transport === 'mcp' && policy.method === 'POST' && !policy.protocol) {
274
+ if (!policySet.mcpTools?.length || policy.access.kind !== 'authenticated' || !policy.apiKey.allowed || policy.apiKey.scopeMode !== 'tool'
275
+ || policy.audit.mode !== 'authentication' || policy.audit.recordRequest || policy.audit.recordResponse || !identifier(policy.id)) {
276
+ throw new Error('Invalid native MCP protocol policy');
277
+ }
278
+ if (!groups.has('integration_mcp')) groups.set('integration_mcp', []);
279
+ groups.get('integration_mcp').push({ policy, input: inputSchema({}, 'mcp'), responses: { 200: null }, errors: {}, mediaTypes: { 200: ['application/json'] } });
280
+ used.add(policy.id);
281
+ }
282
+ for (const policy of policies.values()) if (!used.has(policy.id)) {
283
+ const protocol = policy.protocol;
284
+ const owner = protocol && policies.get(protocol.owner);
285
+ if (!protocol || protocol.kind !== 'mcp_stateless_method_not_allowed' || !owner || !used.has(owner.id)
286
+ || owner.transport !== 'mcp' || owner.method !== 'POST' || owner.protocol
287
+ || policy.transport !== 'mcp' || !['GET', 'DELETE'].includes(policy.method) || policy.path !== owner.path
288
+ || policy.successStatus || policy.audit.mode !== 'none'
289
+ || quote(policy.access) !== quote(owner.access) || quote(policy.apiKey) !== quote(owner.apiKey)) throw new Error('Policy set contains an absent or invalid protocol operation');
290
+ used.add(policy.id);
291
+ }
292
+ const modeler = model(document), output = {};
293
+ for (const [group, entries] of [...groups].sort(([a], [b]) => a.localeCompare(b))) {
294
+ const lines = ['// Generated from Goa OpenAPI and ArcBase policies. DO NOT EDIT.', "import { z } from 'zod';", 'export type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue };', ''];
295
+ const names = modeler.dependencies(entries.flatMap(entry => [entry.input, entry.responses, entry.errors]));
296
+ if (new Set(names.map(schemaName)).size !== names.length) throw new Error(`Colliding schema names in ${group}`);
297
+ for (const name of names) {
298
+ lines.push(`export type ${schemaName(name)} = ${modeler.type(modeler.schemas[name])};`);
299
+ lines.push(`export type ${schemaName(name)}Input = ${modeler.type(modeler.schemas[name], true)};`);
300
+ lines.push(`export const ${schemaName(name)}Schema: z.ZodType<${schemaName(name)}, ${schemaName(name)}Input> = z.lazy(() => ${modeler.expression(modeler.schemas[name])});`, '');
301
+ }
302
+ for (const entry of entries.sort((a, b) => a.policy.id.localeCompare(b.policy.id))) {
303
+ const response = values => Object.entries(values).map(([status, schema]) => `${status}: ${schema ? modeler.expression(schema) : 'z.undefined()'}`).join(', ');
304
+ const query = entry.input.properties.query;
305
+ if (query) {
306
+ const name = `${entry.policy.id}QuerySchema`;
307
+ lines.push(`export const ${name} = ${modeler.expression(query)};`, '');
308
+ modeler.reference(query, name);
309
+ }
310
+ lines.push(`export const ${entry.policy.id} = {`);
311
+ lines.push(` id: ${quote(entry.policy.id)}, method: ${quote(entry.policy.method)}, path: ${quote(entry.policy.path)}, kind: ${quote(entry.policy.transport)},`);
312
+ lines.push(` access: ${quote(entry.policy.access)}, apiKey: ${quote(entry.policy.apiKey)},`);
313
+ if (entry.policy.sse) lines.push(` sse: ${quote(entry.policy.sse)},`);
314
+ if (query) lines.push(` query: ${entry.policy.id}QuerySchema,`);
315
+ lines.push(` input: ${modeler.expression(entry.input)}${entry.input.required.length ? '' : '.prefault({})'},`);
316
+ lines.push(` responses: { ${response(entry.responses)} }, errors: { ${response(entry.errors)} }, mediaTypes: ${quote(entry.mediaTypes)},`, '} as const;', '');
317
+ }
318
+ output[`${group}.ts`] = lines.join('\n') + '\n';
319
+ }
320
+ if (policySet.mcpTools) {
321
+ const tools = policySet.mcpTools.map(tool => {
322
+ const source = policies.get(tool.operationId);
323
+ if (!source || source.method !== 'GET' || source.transport !== 'json' || !source.apiKey.allowed || source.access.kind !== 'permission' || source.access.permissions?.length !== 1) {
324
+ throw new Error(`MCP tool ${tool.name} must reference a read policy`);
325
+ }
326
+ return { ...tool, permission: source.access.permissions[0] };
327
+ });
328
+ output['mcp-tools.ts'] = '// Generated from Goa-AI tool declarations and ArcBase read policies. DO NOT EDIT.\nexport const mcpTools = ' + JSON.stringify(tools, null, 2) + ' as const;\n';
329
+ }
330
+ return output;
331
+ }