micro-contracts 0.18.10 → 0.18.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -14
- package/cli-contract.yaml +15 -27
- package/dist/agents/context-builder.d.ts +5 -0
- package/dist/agents/context-builder.d.ts.map +1 -0
- package/dist/agents/context-builder.js +239 -0
- package/dist/agents/context-builder.js.map +1 -0
- package/dist/agents/formatter.d.ts +9 -0
- package/dist/agents/formatter.d.ts.map +1 -0
- package/dist/agents/formatter.js +124 -0
- package/dist/agents/formatter.js.map +1 -0
- package/dist/agents/index.d.ts +6 -0
- package/dist/agents/index.d.ts.map +1 -0
- package/dist/agents/index.js +4 -0
- package/dist/agents/index.js.map +1 -0
- package/dist/agents/orchestrator.d.ts +5 -0
- package/dist/agents/orchestrator.d.ts.map +1 -0
- package/dist/agents/orchestrator.js +46 -0
- package/dist/agents/orchestrator.js.map +1 -0
- package/dist/agents/types.d.ts +29 -0
- package/dist/agents/types.d.ts.map +1 -0
- package/dist/agents/types.js +7 -0
- package/dist/agents/types.js.map +1 -0
- package/dist/cli/templates.d.ts +15 -0
- package/dist/cli/templates.d.ts.map +1 -0
- package/dist/cli/templates.js +445 -0
- package/dist/cli/templates.js.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +1201 -0
- package/dist/cli.js.map +1 -0
- package/dist/commands/audit-guardrails.d.ts +15 -0
- package/dist/commands/audit-guardrails.d.ts.map +1 -0
- package/dist/commands/audit-guardrails.js +33 -0
- package/dist/commands/audit-guardrails.js.map +1 -0
- package/dist/commands/audit-openapi.d.ts +15 -0
- package/dist/commands/audit-openapi.d.ts.map +1 -0
- package/dist/commands/audit-openapi.js +33 -0
- package/dist/commands/audit-openapi.js.map +1 -0
- package/dist/commands/insights.d.ts +8 -0
- package/dist/commands/insights.d.ts.map +1 -0
- package/dist/commands/insights.js +13 -0
- package/dist/commands/insights.js.map +1 -0
- package/dist/commands/propose-overlays.d.ts +15 -0
- package/dist/commands/propose-overlays.d.ts.map +1 -0
- package/dist/commands/propose-overlays.js +33 -0
- package/dist/commands/propose-overlays.js.map +1 -0
- package/dist/commands/review-published.d.ts +15 -0
- package/dist/commands/review-published.d.ts.map +1 -0
- package/dist/commands/review-published.js +33 -0
- package/dist/commands/review-published.js.map +1 -0
- package/dist/external/insight-provider.d.ts.map +1 -0
- package/dist/external/insight-provider.js.map +1 -0
- package/dist/generated/commands.d.ts +2 -0
- package/dist/generated/commands.d.ts.map +1 -0
- package/dist/generated/commands.js +2 -0
- package/dist/generated/commands.js.map +1 -0
- package/dist/generated/contract.d.ts +3 -0
- package/dist/generated/contract.d.ts.map +1 -0
- package/dist/generated/contract.js +5 -0
- package/dist/generated/contract.js.map +1 -0
- package/dist/generated/dsl/agents.d.ts +34 -0
- package/dist/generated/dsl/agents.d.ts.map +1 -0
- package/dist/generated/dsl/agents.js +98 -0
- package/dist/generated/dsl/agents.js.map +1 -0
- package/dist/generated/dsl/dsl-data.d.ts +7 -0
- package/dist/generated/dsl/dsl-data.d.ts.map +1 -0
- package/dist/generated/dsl/dsl-data.js +1041 -0
- package/dist/generated/dsl/dsl-data.js.map +1 -0
- package/dist/generated/dsl/handoffs.d.ts +457 -0
- package/dist/generated/dsl/handoffs.d.ts.map +1 -0
- package/dist/generated/dsl/handoffs.js +205 -0
- package/dist/generated/dsl/handoffs.js.map +1 -0
- package/dist/generated/dsl/index.d.ts +14 -0
- package/dist/generated/dsl/index.d.ts.map +1 -0
- package/dist/generated/dsl/index.js +11 -0
- package/dist/generated/dsl/index.js.map +1 -0
- package/dist/generated/dsl/tasks.d.ts +28 -0
- package/dist/generated/dsl/tasks.d.ts.map +1 -0
- package/dist/generated/dsl/tasks.js +137 -0
- package/dist/generated/dsl/tasks.js.map +1 -0
- package/dist/generated/dsl/workflows.d.ts +34 -0
- package/dist/generated/dsl/workflows.d.ts.map +1 -0
- package/dist/generated/dsl/workflows.js +84 -0
- package/dist/generated/dsl/workflows.js.map +1 -0
- package/dist/generated/index.d.ts +8 -0
- package/dist/generated/index.d.ts.map +1 -0
- package/dist/generated/index.js +8 -0
- package/dist/generated/index.js.map +1 -0
- package/dist/generated/policy-runtime.d.ts +114 -0
- package/dist/generated/policy-runtime.d.ts.map +1 -0
- package/dist/generated/policy-runtime.js +195 -0
- package/dist/generated/policy-runtime.js.map +1 -0
- package/dist/generated/policy.d.ts +658 -0
- package/dist/generated/policy.d.ts.map +1 -0
- package/dist/generated/policy.js +844 -0
- package/dist/generated/policy.js.map +1 -0
- package/dist/generated/program.d.ts +120 -0
- package/dist/generated/program.d.ts.map +1 -0
- package/dist/generated/program.js +370 -0
- package/dist/generated/program.js.map +1 -0
- package/dist/generated/schemas.d.ts +779 -0
- package/dist/generated/schemas.d.ts.map +1 -0
- package/dist/generated/schemas.js +1006 -0
- package/dist/generated/schemas.js.map +1 -0
- package/dist/generated/types.d.ts +786 -0
- package/dist/generated/types.d.ts.map +1 -0
- package/dist/generated/types.js +3 -0
- package/dist/generated/types.js.map +1 -0
- package/dist/generator/dependencyGenerator.d.ts +16 -0
- package/dist/generator/dependencyGenerator.d.ts.map +1 -0
- package/dist/generator/dependencyGenerator.js +25 -0
- package/dist/generator/dependencyGenerator.js.map +1 -0
- package/dist/generator/index.d.ts +47 -0
- package/dist/generator/index.d.ts.map +1 -0
- package/dist/generator/index.js +707 -0
- package/dist/generator/index.js.map +1 -0
- package/dist/generator/inputHash.d.ts +23 -0
- package/dist/generator/inputHash.d.ts.map +1 -0
- package/dist/generator/inputHash.js +138 -0
- package/dist/generator/inputHash.js.map +1 -0
- package/dist/generator/linter.d.ts +26 -0
- package/dist/generator/linter.d.ts.map +1 -0
- package/dist/generator/linter.js +441 -0
- package/dist/generator/linter.js.map +1 -0
- package/dist/generator/overlayProcessor.d.ts +71 -0
- package/dist/generator/overlayProcessor.d.ts.map +1 -0
- package/dist/generator/overlayProcessor.js +500 -0
- package/dist/generator/overlayProcessor.js.map +1 -0
- package/dist/generator/schemaGenerator.d.ts +10 -0
- package/dist/generator/schemaGenerator.d.ts.map +1 -0
- package/dist/generator/schemaGenerator.js +296 -0
- package/dist/generator/schemaGenerator.js.map +1 -0
- package/dist/generator/serviceGenerator.d.ts +20 -0
- package/dist/generator/serviceGenerator.d.ts.map +1 -0
- package/dist/generator/serviceGenerator.js +293 -0
- package/dist/generator/serviceGenerator.js.map +1 -0
- package/dist/generator/templateProcessor.d.ts +208 -0
- package/dist/generator/templateProcessor.d.ts.map +1 -0
- package/dist/generator/templateProcessor.js +604 -0
- package/dist/generator/templateProcessor.js.map +1 -0
- package/dist/generator/typeGenerator.d.ts +22 -0
- package/dist/generator/typeGenerator.d.ts.map +1 -0
- package/dist/generator/typeGenerator.js +439 -0
- package/dist/generator/typeGenerator.js.map +1 -0
- package/dist/generator/typeGenerator.test.d.ts +2 -0
- package/dist/generator/typeGenerator.test.d.ts.map +1 -0
- package/dist/generator/typeGenerator.test.js +155 -0
- package/dist/generator/typeGenerator.test.js.map +1 -0
- package/dist/glob.d.ts +22 -0
- package/dist/glob.d.ts.map +1 -0
- package/dist/glob.js +103 -0
- package/dist/glob.js.map +1 -0
- package/dist/guardrails/allowlist.d.ts +30 -0
- package/dist/guardrails/allowlist.d.ts.map +1 -0
- package/dist/guardrails/allowlist.js +174 -0
- package/dist/guardrails/allowlist.js.map +1 -0
- package/dist/guardrails/config.d.ts +40 -0
- package/dist/guardrails/config.d.ts.map +1 -0
- package/dist/guardrails/config.js +177 -0
- package/dist/guardrails/config.js.map +1 -0
- package/dist/guardrails/drift.d.ts +19 -0
- package/dist/guardrails/drift.d.ts.map +1 -0
- package/dist/guardrails/drift.js +115 -0
- package/dist/guardrails/drift.js.map +1 -0
- package/dist/guardrails/index.d.ts +18 -0
- package/dist/guardrails/index.d.ts.map +1 -0
- package/dist/guardrails/index.js +21 -0
- package/dist/guardrails/index.js.map +1 -0
- package/dist/guardrails/lint.d.ts +16 -0
- package/dist/guardrails/lint.d.ts.map +1 -0
- package/dist/guardrails/lint.js +172 -0
- package/dist/guardrails/lint.js.map +1 -0
- package/dist/guardrails/manifest.d.ts +63 -0
- package/dist/guardrails/manifest.d.ts.map +1 -0
- package/dist/guardrails/manifest.js +310 -0
- package/dist/guardrails/manifest.js.map +1 -0
- package/dist/guardrails/runner.d.ts +53 -0
- package/dist/guardrails/runner.d.ts.map +1 -0
- package/dist/guardrails/runner.js +387 -0
- package/dist/guardrails/runner.js.map +1 -0
- package/dist/guardrails/types.d.ts +196 -0
- package/dist/guardrails/types.d.ts.map +1 -0
- package/dist/guardrails/types.js +8 -0
- package/dist/guardrails/types.js.map +1 -0
- package/dist/index.d.ts +21 -4
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +21 -4
- package/dist/index.js.map +1 -0
- package/dist/micro-contracts.bundle.mjs +349 -374
- package/dist/micro-contracts.bundle.mjs.map +3 -3
- package/dist/types.d.ts +502 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +409 -0
- package/dist/types.js.map +1 -0
- package/dist/version.d.ts +10 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +31 -0
- package/dist/version.js.map +1 -0
- package/docs/cli-reference.md +13 -15
- package/docs/development-guardrails.md +3 -3
- package/docs/screen-spec.md +3 -3
- package/package.json +13 -12
|
@@ -0,0 +1,707 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* micro-contracts Generator
|
|
3
|
+
*/
|
|
4
|
+
import fs from 'fs';
|
|
5
|
+
import path from 'path';
|
|
6
|
+
import yaml from 'js-yaml';
|
|
7
|
+
import { isMultiModuleConfig, resolveModuleConfig, validateConfigKeys, } from '../types.js';
|
|
8
|
+
import { generateTypes, operationTypeNames } from './typeGenerator.js';
|
|
9
|
+
import { generateSchemas } from './schemaGenerator.js';
|
|
10
|
+
import { generateServiceInterfaces } from './serviceGenerator.js';
|
|
11
|
+
import { lintSpec, formatLintResults } from './linter.js';
|
|
12
|
+
import { processOverlays, generateExtensionInterfaces, formatOverlayLog, rebaseRefs, } from './overlayProcessor.js';
|
|
13
|
+
import { buildTemplateContext, renderTemplate, } from './templateProcessor.js';
|
|
14
|
+
import { validateDependsOn } from './dependencyGenerator.js';
|
|
15
|
+
import { matchGlob } from '../glob.js';
|
|
16
|
+
import { extractDependencies, collectReachableComponents } from '../types.js';
|
|
17
|
+
export { generateTypes } from './typeGenerator.js';
|
|
18
|
+
export { generateSchemas } from './schemaGenerator.js';
|
|
19
|
+
export { generateServiceInterfaces } from './serviceGenerator.js';
|
|
20
|
+
export { lintSpec, formatLintResults } from './linter.js';
|
|
21
|
+
export { processOverlays, generateExtensionInterfaces } from './overlayProcessor.js';
|
|
22
|
+
export { buildTemplateContext, renderTemplate } from './templateProcessor.js';
|
|
23
|
+
export { collectInputFiles, computeInputHash } from './inputHash.js';
|
|
24
|
+
/**
|
|
25
|
+
* Write file only if content has changed (ignoring timestamp in header).
|
|
26
|
+
* This prevents unnecessary git diffs when only the timestamp changes.
|
|
27
|
+
* Returns true if file was written, false if content was unchanged.
|
|
28
|
+
*/
|
|
29
|
+
function writeFileIfChanged(filePath, newContent) {
|
|
30
|
+
// Resolve to absolute path for consistency
|
|
31
|
+
const absolutePath = path.resolve(filePath);
|
|
32
|
+
if (fs.existsSync(absolutePath)) {
|
|
33
|
+
const existingContent = fs.readFileSync(absolutePath, 'utf-8');
|
|
34
|
+
if (existingContent === newContent) {
|
|
35
|
+
return false; // No change, skip writing
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
// Creating the parent directory belongs to the write itself: no caller may
|
|
39
|
+
// mkdir an output path, or a file path ends up existing as a directory.
|
|
40
|
+
fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
|
|
41
|
+
fs.writeFileSync(absolutePath, newContent);
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Write file and log result. Uses writeFileIfChanged to avoid unnecessary updates.
|
|
46
|
+
*/
|
|
47
|
+
function writeAndLog(filePath, content, indent = ' ') {
|
|
48
|
+
const written = writeFileIfChanged(filePath, content);
|
|
49
|
+
if (written) {
|
|
50
|
+
console.log(`${indent}Written: ${filePath}`);
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
console.log(`${indent}Unchanged: ${filePath}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Load OpenAPI spec from file
|
|
58
|
+
*/
|
|
59
|
+
export function loadOpenAPISpec(filePath) {
|
|
60
|
+
const content = fs.readFileSync(filePath, 'utf-8');
|
|
61
|
+
if (filePath.endsWith('.yaml') || filePath.endsWith('.yml')) {
|
|
62
|
+
return yaml.load(content);
|
|
63
|
+
}
|
|
64
|
+
else if (filePath.endsWith('.json')) {
|
|
65
|
+
return JSON.parse(content);
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
throw new Error(`Unsupported file format: ${filePath}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Config file names, in the order they are looked for.
|
|
73
|
+
*/
|
|
74
|
+
const CONFIG_FILENAMES = [
|
|
75
|
+
'micro-contracts.config.yaml',
|
|
76
|
+
'micro-contracts.config.yml',
|
|
77
|
+
'api-framework.config.yaml',
|
|
78
|
+
'api-framework.config.yml',
|
|
79
|
+
];
|
|
80
|
+
/**
|
|
81
|
+
* The project's config file, if one is present in the working directory.
|
|
82
|
+
*
|
|
83
|
+
* Everything that needs the project's spec list — generation and the guardrail
|
|
84
|
+
* checks alike — resolves it from here, so no consumer has to guess where the
|
|
85
|
+
* specs live.
|
|
86
|
+
*/
|
|
87
|
+
export function findConfigFile() {
|
|
88
|
+
for (const candidate of CONFIG_FILENAMES) {
|
|
89
|
+
const configPath = path.resolve(candidate);
|
|
90
|
+
if (fs.existsSync(configPath))
|
|
91
|
+
return configPath;
|
|
92
|
+
}
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Load config from file (supports both legacy and multi-module formats)
|
|
97
|
+
*/
|
|
98
|
+
export function loadConfig(configPath) {
|
|
99
|
+
const content = fs.readFileSync(configPath, 'utf-8');
|
|
100
|
+
const config = yaml.load(content);
|
|
101
|
+
if (isMultiModuleConfig(config)) {
|
|
102
|
+
validateConfigKeys(config);
|
|
103
|
+
}
|
|
104
|
+
return config;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Parse module filter from options
|
|
108
|
+
*/
|
|
109
|
+
function parseListOption(value) {
|
|
110
|
+
if (!value)
|
|
111
|
+
return null;
|
|
112
|
+
const items = Array.isArray(value) ? value : value.split(',').map(v => v.trim());
|
|
113
|
+
const filtered = items.filter(Boolean);
|
|
114
|
+
return filtered.length > 0 ? filtered : null;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Generate all files from config
|
|
118
|
+
*/
|
|
119
|
+
export async function generate(config, options = {}) {
|
|
120
|
+
// Handle multi-module config
|
|
121
|
+
if (isMultiModuleConfig(config)) {
|
|
122
|
+
await generateMultiModule(config, options);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
// Legacy single-module config is no longer supported
|
|
126
|
+
throw new Error('Legacy single-module configuration format is no longer supported. ' +
|
|
127
|
+
'Please migrate to the multi-module format with a "modules:" section. ' +
|
|
128
|
+
'See README.md for configuration examples.');
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Generate for multi-module config
|
|
132
|
+
*/
|
|
133
|
+
async function generateMultiModule(config, options) {
|
|
134
|
+
const moduleFilter = parseListOption(options.modules);
|
|
135
|
+
const moduleNames = Object.keys(config.modules);
|
|
136
|
+
// Filter modules if specified
|
|
137
|
+
const targetModules = moduleFilter
|
|
138
|
+
? moduleNames.filter(m => moduleFilter.includes(m))
|
|
139
|
+
: moduleNames;
|
|
140
|
+
if (targetModules.length === 0) {
|
|
141
|
+
if (moduleFilter) {
|
|
142
|
+
console.error(`No matching modules found. Available: ${moduleNames.join(', ')}`);
|
|
143
|
+
process.exit(1);
|
|
144
|
+
}
|
|
145
|
+
console.log('No modules defined in config.');
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
console.log(`Generating for modules: ${targetModules.join(', ')}`);
|
|
149
|
+
// Resolve every declared module, not just the targeted ones: cross-module
|
|
150
|
+
// deps/ re-exports need the output directories of their dependency targets.
|
|
151
|
+
const resolvedModules = new Map();
|
|
152
|
+
for (const moduleName of moduleNames) {
|
|
153
|
+
resolvedModules.set(moduleName, resolveModuleConfig(moduleName, config.modules[moduleName], config.defaults));
|
|
154
|
+
}
|
|
155
|
+
// Generate each module
|
|
156
|
+
for (const moduleName of targetModules) {
|
|
157
|
+
console.log(`\n${'='.repeat(60)}`);
|
|
158
|
+
console.log(`Module: ${moduleName}`);
|
|
159
|
+
console.log(`${'='.repeat(60)}`);
|
|
160
|
+
await generateModule(resolvedModules.get(moduleName), options, resolvedModules);
|
|
161
|
+
}
|
|
162
|
+
console.log('\nGeneration complete!');
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Generate for a single resolved module
|
|
166
|
+
*/
|
|
167
|
+
async function generateModule(config, options, resolvedModules) {
|
|
168
|
+
// Load OpenAPI spec
|
|
169
|
+
const openapiPath = path.resolve(config.openapi);
|
|
170
|
+
console.log(`Loading OpenAPI spec from: ${openapiPath}`);
|
|
171
|
+
if (!fs.existsSync(openapiPath)) {
|
|
172
|
+
throw new Error(`OpenAPI spec not found: ${openapiPath}`);
|
|
173
|
+
}
|
|
174
|
+
let spec = loadOpenAPISpec(openapiPath);
|
|
175
|
+
console.log(` Title: ${spec.info.title}`);
|
|
176
|
+
console.log(` Version: ${spec.info.version}`);
|
|
177
|
+
// Run linting first (unless skipped)
|
|
178
|
+
if (!options.skipLint) {
|
|
179
|
+
console.log('\nLinting OpenAPI spec...');
|
|
180
|
+
const lintResult = lintSpec(spec, { screen: config.screen });
|
|
181
|
+
console.log(formatLintResults(lintResult));
|
|
182
|
+
if (!lintResult.valid) {
|
|
183
|
+
throw new Error('Lint failed. Fix errors before generating.');
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
// Apply overlays if configured
|
|
187
|
+
let overlayResult = null;
|
|
188
|
+
if (config.overlays.length > 0) {
|
|
189
|
+
console.log('\nApplying overlays...');
|
|
190
|
+
overlayResult = processOverlays(spec, {
|
|
191
|
+
collision: config.overlayCollision,
|
|
192
|
+
files: config.overlays,
|
|
193
|
+
}, process.cwd(), openapiPath // Pass spec path for $ref rebasing
|
|
194
|
+
);
|
|
195
|
+
spec = overlayResult.spec;
|
|
196
|
+
console.log(formatOverlayLog(overlayResult));
|
|
197
|
+
// Note: Transformed spec is written to packages/contract/*/docs/openapi.generated.yaml
|
|
198
|
+
}
|
|
199
|
+
const generateAll = !options.contractsOnly && !options.serverOnly &&
|
|
200
|
+
!options.frontendOnly;
|
|
201
|
+
// Validate and generate dependencies
|
|
202
|
+
const dependencies = extractDependencies(spec);
|
|
203
|
+
if (config.dependsOn) {
|
|
204
|
+
const validation = validateDependsOn(dependencies.allDeps.map(d => d.raw), config.dependsOn, config.name);
|
|
205
|
+
if (!validation.valid) {
|
|
206
|
+
for (const err of validation.errors) {
|
|
207
|
+
console.error(`ERROR: ${err}`);
|
|
208
|
+
}
|
|
209
|
+
throw new Error('Dependency validation failed');
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
// Generate contract package
|
|
213
|
+
if (generateAll || options.contractsOnly) {
|
|
214
|
+
await generateContractPackage(spec, config, false, overlayResult);
|
|
215
|
+
// Generate public contract if there are public endpoints
|
|
216
|
+
if (hasPublicEndpoints(spec)) {
|
|
217
|
+
await generateContractPackage(spec, config, true, overlayResult);
|
|
218
|
+
}
|
|
219
|
+
// Generate deps/ re-exports if module has dependencies
|
|
220
|
+
if (dependencies.allDeps.length > 0) {
|
|
221
|
+
await generateDepsReExports(config, dependencies, resolvedModules);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
// Generate using new outputs system if configured
|
|
225
|
+
if (config.outputs.length > 0) {
|
|
226
|
+
await generateFromOutputs(spec, config, overlayResult, options);
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
// Fallback to legacy server/frontend generation
|
|
230
|
+
// Generate server routes
|
|
231
|
+
if ((generateAll || options.serverOnly) && config.server) {
|
|
232
|
+
await generateServerRoutes(spec, config, overlayResult);
|
|
233
|
+
}
|
|
234
|
+
// Generate frontend clients
|
|
235
|
+
if ((generateAll || options.frontendOnly) && config.frontend) {
|
|
236
|
+
await generateFrontendClient(spec, config, overlayResult);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
// Documentation (Redoc HTML) generation removed.
|
|
240
|
+
// Use @redocly/cli directly if needed:
|
|
241
|
+
// npx @redocly/cli build-docs openapi.generated.yaml -o api-reference.html
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Check if spec has any public endpoints
|
|
245
|
+
*/
|
|
246
|
+
function hasPublicEndpoints(spec) {
|
|
247
|
+
for (const pathItem of Object.values(spec.paths)) {
|
|
248
|
+
for (const method of ['get', 'post', 'put', 'patch', 'delete']) {
|
|
249
|
+
const operation = pathItem[method];
|
|
250
|
+
if (operation?.['x-micro-contracts-published'] === true) {
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return false;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Generate contract package
|
|
259
|
+
*/
|
|
260
|
+
async function generateContractPackage(spec, config, publicOnly, overlayResult = null) {
|
|
261
|
+
const outputDir = publicOnly ? config.contractPublicOutput : config.contractOutput;
|
|
262
|
+
const label = publicOnly ? 'public contract' : 'contract';
|
|
263
|
+
console.log(`\nGenerating ${label} package...`);
|
|
264
|
+
// For public contract, use filtered spec
|
|
265
|
+
const targetSpec = publicOnly ? filterPublicSpec(spec) : spec;
|
|
266
|
+
// Note: We no longer delete files before generating to enable change detection.
|
|
267
|
+
// Orphaned files from removed services/schemas should be manually cleaned up.
|
|
268
|
+
// Generate service interfaces
|
|
269
|
+
console.log(` Generating service interfaces...`);
|
|
270
|
+
const serviceInterfaces = generateServiceInterfaces(targetSpec, {
|
|
271
|
+
publicOnly,
|
|
272
|
+
serviceTemplate: config.serviceTemplate,
|
|
273
|
+
});
|
|
274
|
+
for (const [name, content] of serviceInterfaces) {
|
|
275
|
+
const fileName = name === 'index' ? 'index.ts' : `${name}ServiceApi.ts`;
|
|
276
|
+
const filePath = path.join(outputDir, 'services', fileName);
|
|
277
|
+
writeAndLog(filePath, content);
|
|
278
|
+
}
|
|
279
|
+
// Generate types (use filtered spec for public)
|
|
280
|
+
console.log(` Generating schema types...`);
|
|
281
|
+
const typesContent = generateTypes(targetSpec);
|
|
282
|
+
const typesPath = path.join(outputDir, 'schemas', 'types.ts');
|
|
283
|
+
writeAndLog(typesPath, typesContent);
|
|
284
|
+
// Generate validators (JSON Schemas) - use filtered spec for public
|
|
285
|
+
console.log(` Generating validators...`);
|
|
286
|
+
const validatorsContent = generateSchemas(targetSpec);
|
|
287
|
+
const validatorsPath = path.join(outputDir, 'schemas', 'validators.ts');
|
|
288
|
+
writeAndLog(validatorsPath, validatorsContent);
|
|
289
|
+
// Generate schemas index
|
|
290
|
+
const schemasIndex = `/**
|
|
291
|
+
* Schema exports
|
|
292
|
+
* Auto-generated - DO NOT EDIT
|
|
293
|
+
*/
|
|
294
|
+
|
|
295
|
+
export * from './types.js';
|
|
296
|
+
export { allSchemas } from './validators.js';
|
|
297
|
+
`;
|
|
298
|
+
writeAndLog(path.join(outputDir, 'schemas', 'index.ts'), schemasIndex);
|
|
299
|
+
// Generate errors
|
|
300
|
+
const hasEndpoints = Object.keys(targetSpec.paths).length > 0;
|
|
301
|
+
console.log(` Generating error types...`);
|
|
302
|
+
const errorsContent = hasEndpoints ? generateErrors() : generateEmptyErrors();
|
|
303
|
+
writeAndLog(path.join(outputDir, 'errors', 'index.ts'), errorsContent);
|
|
304
|
+
// Generate overlay interfaces if overlays were applied
|
|
305
|
+
if (overlayResult && overlayResult.extensionInfo.size > 0 && !publicOnly) {
|
|
306
|
+
console.log(` Generating overlay interfaces...`);
|
|
307
|
+
const overlaysDir = path.join(outputDir, 'overlays');
|
|
308
|
+
const overlayContent = generateExtensionInterfaces(overlayResult.extensionInfo);
|
|
309
|
+
const overlayPath = path.join(overlaysDir, 'index.ts');
|
|
310
|
+
writeAndLog(overlayPath, overlayContent);
|
|
311
|
+
}
|
|
312
|
+
// Generate package index
|
|
313
|
+
const hasOverlays = overlayResult && overlayResult.extensionInfo.size > 0 && !publicOnly;
|
|
314
|
+
const indexContent = `/**
|
|
315
|
+
* ${publicOnly ? 'Public ' : ''}Contract Package
|
|
316
|
+
* Auto-generated - DO NOT EDIT
|
|
317
|
+
*/
|
|
318
|
+
|
|
319
|
+
export * from './services/index.js';
|
|
320
|
+
export * from './schemas/index.js';
|
|
321
|
+
export * from './errors/index.js';
|
|
322
|
+
${hasOverlays ? "export * from './overlays/index.js';" : ''}
|
|
323
|
+
`;
|
|
324
|
+
writeAndLog(path.join(outputDir, 'index.ts'), indexContent);
|
|
325
|
+
// Copy OpenAPI spec to docs with source info header
|
|
326
|
+
// Rebase $ref paths from source directory to output directory
|
|
327
|
+
const sourceDir = path.dirname(config.openapi);
|
|
328
|
+
const docsDir = path.join(outputDir, 'docs');
|
|
329
|
+
const rebasedSpec = rebaseRefs(targetSpec, sourceDir, docsDir);
|
|
330
|
+
const specHeader = `# Auto-generated OpenAPI specification
|
|
331
|
+
# DO NOT EDIT MANUALLY
|
|
332
|
+
#
|
|
333
|
+
# Source: ${config.openapi}
|
|
334
|
+
# Regenerate: micro-contracts generate
|
|
335
|
+
${publicOnly ? '# Filtered for public endpoints only\n' : ''}
|
|
336
|
+
`;
|
|
337
|
+
const yamlContent = specHeader + yaml.dump(rebasedSpec, { lineWidth: -1 });
|
|
338
|
+
writeAndLog(path.join(docsDir, 'openapi.generated.yaml'), yamlContent);
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Generate using flexible outputs configuration
|
|
342
|
+
*/
|
|
343
|
+
async function generateFromOutputs(spec, config, overlayResult, options) {
|
|
344
|
+
// The built-in server/frontend sections and the outputs system are separate
|
|
345
|
+
// config surfaces: an output is not "a server output" or "a frontend output",
|
|
346
|
+
// it is a template rendered to a path. Select outputs with --output.
|
|
347
|
+
if (options.serverOnly || options.frontendOnly) {
|
|
348
|
+
const flag = options.serverOnly ? '--server-only' : '--frontend-only';
|
|
349
|
+
throw new Error(`${flag} does not apply to an outputs configuration. ` +
|
|
350
|
+
`Select outputs with --output <ids> (comma-separated, glob patterns allowed). ` +
|
|
351
|
+
`Configured outputs: ${config.outputs.map(o => o.id).join(', ')}.`);
|
|
352
|
+
}
|
|
353
|
+
if (options.contractsOnly)
|
|
354
|
+
return;
|
|
355
|
+
console.log(`\nGenerating from outputs configuration...`);
|
|
356
|
+
const patterns = parseListOption(options.outputs);
|
|
357
|
+
const hasPublic = hasPublicEndpoints(spec);
|
|
358
|
+
let selected = 0;
|
|
359
|
+
for (const output of config.outputs) {
|
|
360
|
+
// Skip disabled outputs
|
|
361
|
+
if (!output.enabled)
|
|
362
|
+
continue;
|
|
363
|
+
// Check conditions
|
|
364
|
+
if (output.condition === 'hasPublicEndpoints' && !hasPublic) {
|
|
365
|
+
console.log(` Skipping ${output.id} (no public endpoints)`);
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
const hasOverlays = overlayResult && overlayResult.extensionInfo.size > 0;
|
|
369
|
+
if (output.condition === 'hasOverlays' && !hasOverlays) {
|
|
370
|
+
console.log(` Skipping ${output.id} (no overlays)`);
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
if (patterns && !patterns.some(pattern => matchGlob(output.id, pattern))) {
|
|
374
|
+
console.log(` Skipping ${output.id} (not selected by --output)`);
|
|
375
|
+
continue;
|
|
376
|
+
}
|
|
377
|
+
selected++;
|
|
378
|
+
// Check if file exists and overwrite is disabled
|
|
379
|
+
if (!output.overwrite && fs.existsSync(output.output)) {
|
|
380
|
+
console.log(` Skipping ${output.id} (file exists, overwrite=false)`);
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
console.log(` Generating ${output.id}...`);
|
|
384
|
+
// Build template context with output-specific config
|
|
385
|
+
// Expand {module} placeholders in config values
|
|
386
|
+
const expandPlaceholder = (val, fallback) => (val?.replace(/{module}/g, config.name) ?? fallback);
|
|
387
|
+
const templateContext = buildTemplateContext(spec, config.name, {
|
|
388
|
+
servicesPath: expandPlaceholder(output.config?.servicesPath, `fastify.services.${config.name}`),
|
|
389
|
+
contractPackage: expandPlaceholder(output.config?.contractPackage, `@project/contract/${config.name}`),
|
|
390
|
+
extensionInfo: overlayResult?.extensionInfo,
|
|
391
|
+
appliedOverlays: overlayResult?.appliedOverlays,
|
|
392
|
+
screen: config.screen,
|
|
393
|
+
});
|
|
394
|
+
// Add output-specific config to context
|
|
395
|
+
const extendedContext = {
|
|
396
|
+
...templateContext,
|
|
397
|
+
outputConfig: output.config || {},
|
|
398
|
+
};
|
|
399
|
+
// Failures propagate: a template that cannot be found, parsed or rendered
|
|
400
|
+
// leaves the previous generated file in place, so the run must not succeed.
|
|
401
|
+
const content = renderTemplate(output.template, extendedContext, `output '${output.id}'`);
|
|
402
|
+
// Write output file (only if content changed)
|
|
403
|
+
writeAndLog(output.output, content);
|
|
404
|
+
}
|
|
405
|
+
if (selected === 0) {
|
|
406
|
+
throw new Error((patterns ? `--output ${patterns.join(',')} matched no output` : 'No outputs to generate') +
|
|
407
|
+
` for module '${config.name}'. Configured outputs: ` +
|
|
408
|
+
`${config.outputs.map(o => o.id).join(', ') || '(none)'}.`);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Generate deps/ re-exports for cross-module dependencies
|
|
413
|
+
*/
|
|
414
|
+
async function generateDepsReExports(config, dependencies, resolvedModules) {
|
|
415
|
+
if (dependencies.allDeps.length === 0) {
|
|
416
|
+
console.log(`\n No dependencies declared, skipping deps/ generation`);
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
console.log(`\nGenerating deps/ re-exports...`);
|
|
420
|
+
const depsDir = path.join(config.contractOutput, 'deps');
|
|
421
|
+
// Group deps by target module
|
|
422
|
+
const depsByModule = new Map();
|
|
423
|
+
for (const dep of dependencies.allDeps) {
|
|
424
|
+
if (!depsByModule.has(dep.module)) {
|
|
425
|
+
depsByModule.set(dep.module, []);
|
|
426
|
+
}
|
|
427
|
+
depsByModule.get(dep.module).push(dep);
|
|
428
|
+
}
|
|
429
|
+
for (const [targetModule, deps] of depsByModule) {
|
|
430
|
+
const target = resolvedModules.get(targetModule);
|
|
431
|
+
if (!target) {
|
|
432
|
+
throw new Error(`Module '${config.name}' depends on '${targetModule}' ` +
|
|
433
|
+
`(${deps.map(d => d.raw).join(', ')}) but '${targetModule}' is not defined in the config.`);
|
|
434
|
+
}
|
|
435
|
+
const importPrefix = relativeImportPath(depsDir, target.contractPublicOutput);
|
|
436
|
+
const exported = declaredDependencyTypes(config.name, targetModule, deps, target);
|
|
437
|
+
const content = `/**
|
|
438
|
+
* Auto-generated from x-micro-contracts-depend-on - DO NOT EDIT
|
|
439
|
+
* Source module: ${config.name}
|
|
440
|
+
* Target module: ${targetModule}
|
|
441
|
+
* Dependencies: ${deps.map(d => d.raw).join(', ')}
|
|
442
|
+
*/
|
|
443
|
+
|
|
444
|
+
// Types reached by the declared dependencies of ${targetModule} (contract-published)
|
|
445
|
+
export type {
|
|
446
|
+
${exported.map(name => ` ${name},`).join('\n')}
|
|
447
|
+
} from '${importPrefix}/schemas/types.js';
|
|
448
|
+
`;
|
|
449
|
+
writeAndLog(path.join(depsDir, `${targetModule}.ts`), content, ' ');
|
|
450
|
+
}
|
|
451
|
+
const indexContent = `/**
|
|
452
|
+
* Auto-generated deps index - DO NOT EDIT
|
|
453
|
+
*/
|
|
454
|
+
|
|
455
|
+
${Array.from(depsByModule.keys()).map(m => `export * from './${m}.js';`).join('\n')}
|
|
456
|
+
`;
|
|
457
|
+
writeAndLog(path.join(depsDir, 'index.ts'), indexContent, ' ');
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Type names a module may use through its declared dependencies.
|
|
461
|
+
*
|
|
462
|
+
* Only what the declared operations reach: re-exporting the target's whole
|
|
463
|
+
* published contract would hand over every type it has, which is not what
|
|
464
|
+
* declaring `{module}.{service}.{method}` asks for.
|
|
465
|
+
*/
|
|
466
|
+
function declaredDependencyTypes(sourceModule, targetModule, deps, target) {
|
|
467
|
+
const targetSpec = loadOpenAPISpec(path.resolve(target.openapi));
|
|
468
|
+
const names = new Set();
|
|
469
|
+
for (const dep of deps) {
|
|
470
|
+
const operation = findOperation(targetSpec, dep.service, dep.method);
|
|
471
|
+
if (!operation) {
|
|
472
|
+
throw new Error(`Module '${sourceModule}' depends on '${dep.raw}' but module '${targetModule}' ` +
|
|
473
|
+
`has no operation with x-micro-contracts-service '${dep.service}' ` +
|
|
474
|
+
`and x-micro-contracts-method '${dep.method}'.`);
|
|
475
|
+
}
|
|
476
|
+
// deps/ re-exports from contract-published, which only carries published
|
|
477
|
+
// operations: depending on an unpublished one cannot resolve.
|
|
478
|
+
if (operation['x-micro-contracts-published'] !== true) {
|
|
479
|
+
throw new Error(`Module '${sourceModule}' depends on '${dep.raw}' but that operation is not ` +
|
|
480
|
+
`x-micro-contracts-published, so it is absent from the published contract of '${targetModule}'.`);
|
|
481
|
+
}
|
|
482
|
+
const typeNames = operationTypeNames(operation);
|
|
483
|
+
names.add(typeNames.input);
|
|
484
|
+
if (typeNames.params)
|
|
485
|
+
names.add(typeNames.params);
|
|
486
|
+
if (typeNames.body)
|
|
487
|
+
names.add(typeNames.body);
|
|
488
|
+
// Schemas the operation reaches, named in the published types.
|
|
489
|
+
for (const pointer of collectReachableComponents(operation, targetSpec)) {
|
|
490
|
+
if (pointer.startsWith('schemas/')) {
|
|
491
|
+
names.add(pointer.slice('schemas/'.length));
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
return [...names].sort();
|
|
496
|
+
}
|
|
497
|
+
/** The operation declaring this service and method, if the spec has one. */
|
|
498
|
+
function findOperation(spec, service, method) {
|
|
499
|
+
for (const pathItem of Object.values(spec.paths)) {
|
|
500
|
+
for (const httpMethod of ['get', 'post', 'put', 'patch', 'delete']) {
|
|
501
|
+
const operation = pathItem[httpMethod];
|
|
502
|
+
if (operation?.['x-micro-contracts-service'] === service &&
|
|
503
|
+
operation['x-micro-contracts-method'] === method) {
|
|
504
|
+
return operation;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
return undefined;
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Module specifier for `to`, relative to a file inside `fromDir`.
|
|
512
|
+
*/
|
|
513
|
+
function relativeImportPath(fromDir, to) {
|
|
514
|
+
const relative = path.relative(path.resolve(fromDir), path.resolve(to))
|
|
515
|
+
.split(path.sep)
|
|
516
|
+
.join('/');
|
|
517
|
+
return relative.startsWith('.') ? relative : `./${relative}`;
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Generate server routes
|
|
521
|
+
*/
|
|
522
|
+
async function generateServerRoutes(spec, config, overlayResult = null) {
|
|
523
|
+
if (!config.server)
|
|
524
|
+
return;
|
|
525
|
+
console.log(`\nGenerating server routes...`);
|
|
526
|
+
// Template is required for server routes generation
|
|
527
|
+
if (!config.server.template) {
|
|
528
|
+
throw new Error('Server template is required. Please specify server.template in your config.');
|
|
529
|
+
}
|
|
530
|
+
const templateContext = buildTemplateContext(spec, config.name, {
|
|
531
|
+
servicesPath: config.server.servicesPath,
|
|
532
|
+
contractPackage: `@project/contract/${config.name}`,
|
|
533
|
+
extensionInfo: overlayResult?.extensionInfo,
|
|
534
|
+
appliedOverlays: overlayResult?.appliedOverlays,
|
|
535
|
+
screen: config.screen,
|
|
536
|
+
});
|
|
537
|
+
const routesContent = renderTemplate(config.server.template, templateContext, `server routes of module '${config.name}'`);
|
|
538
|
+
writeAndLog(config.server.output, routesContent, ' ');
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* Generate frontend client
|
|
542
|
+
*/
|
|
543
|
+
async function generateFrontendClient(spec, config, overlayResult = null) {
|
|
544
|
+
if (!config.frontend)
|
|
545
|
+
return;
|
|
546
|
+
const outputDir = path.resolve(config.frontend.output);
|
|
547
|
+
const clientFile = config.frontend.client;
|
|
548
|
+
console.log(`\nGenerating frontend client...`);
|
|
549
|
+
// Template is required for frontend client generation
|
|
550
|
+
if (!config.frontend.template) {
|
|
551
|
+
throw new Error('Frontend template is required. Please specify frontend.template in your config.');
|
|
552
|
+
}
|
|
553
|
+
const templateContext = buildTemplateContext(spec, config.name, {
|
|
554
|
+
contractPackage: `@project/contract/${config.name}`,
|
|
555
|
+
extensionInfo: overlayResult?.extensionInfo,
|
|
556
|
+
appliedOverlays: overlayResult?.appliedOverlays,
|
|
557
|
+
screen: config.screen,
|
|
558
|
+
});
|
|
559
|
+
const clientContent = renderTemplate(config.frontend.template, templateContext, `frontend client of module '${config.name}'`);
|
|
560
|
+
const clientPath = path.join(outputDir, clientFile);
|
|
561
|
+
writeAndLog(clientPath, clientContent, ' ');
|
|
562
|
+
// Generate service re-exports
|
|
563
|
+
const serviceContent = generateServiceReExports(config.name);
|
|
564
|
+
const servicePath = path.join(outputDir, config.frontend.service);
|
|
565
|
+
writeAndLog(servicePath, serviceContent, ' ');
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* Generate service re-exports file
|
|
569
|
+
*/
|
|
570
|
+
function generateServiceReExports(moduleName) {
|
|
571
|
+
const lines = [];
|
|
572
|
+
lines.push('/**');
|
|
573
|
+
lines.push(' * Service re-exports');
|
|
574
|
+
lines.push(' * Auto-generated - DO NOT EDIT');
|
|
575
|
+
lines.push('');
|
|
576
|
+
// Re-export API clients from api.generated
|
|
577
|
+
lines.push('// API clients');
|
|
578
|
+
lines.push("export * from './api.generated';");
|
|
579
|
+
lines.push('');
|
|
580
|
+
// Re-export types from contract package
|
|
581
|
+
lines.push('// Contract types');
|
|
582
|
+
lines.push(`export * from '@project/contract/${moduleName}/schemas';`);
|
|
583
|
+
lines.push(`export * from '@project/contract/${moduleName}/services';`);
|
|
584
|
+
lines.push(`export * from '@project/contract/${moduleName}/errors';`);
|
|
585
|
+
lines.push('');
|
|
586
|
+
return lines.join('\n');
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* Generate error types
|
|
590
|
+
*/
|
|
591
|
+
function generateErrors() {
|
|
592
|
+
return `/**
|
|
593
|
+
* Error types
|
|
594
|
+
* Auto-generated - DO NOT EDIT
|
|
595
|
+
*/
|
|
596
|
+
|
|
597
|
+
// Re-export ProblemDetails from schemas (RFC 9457)
|
|
598
|
+
export type { ProblemDetails, ValidationError } from '../schemas/types.js';
|
|
599
|
+
import type { ProblemDetails } from '../schemas/types.js';
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* API Error wrapper
|
|
603
|
+
*/
|
|
604
|
+
export class ApiError extends Error {
|
|
605
|
+
constructor(
|
|
606
|
+
public readonly status: number,
|
|
607
|
+
public readonly problem: ProblemDetails,
|
|
608
|
+
public readonly requestId?: string,
|
|
609
|
+
) {
|
|
610
|
+
super(problem.title);
|
|
611
|
+
this.name = 'ApiError';
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
get isValidationError(): boolean {
|
|
615
|
+
return this.status === 400;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
get isNotFound(): boolean {
|
|
619
|
+
return this.status === 404;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
get isServerError(): boolean {
|
|
623
|
+
return this.status >= 500;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
`;
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Generate empty error types (when no endpoints exist)
|
|
630
|
+
*/
|
|
631
|
+
function generateEmptyErrors() {
|
|
632
|
+
return `/**
|
|
633
|
+
* Error types
|
|
634
|
+
* Auto-generated - DO NOT EDIT
|
|
635
|
+
*
|
|
636
|
+
* No endpoints defined - error types not needed.
|
|
637
|
+
*/
|
|
638
|
+
`;
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Filter OpenAPI spec for public endpoints only
|
|
642
|
+
*/
|
|
643
|
+
function filterPublicSpec(spec) {
|
|
644
|
+
const filtered = {
|
|
645
|
+
...spec,
|
|
646
|
+
paths: {},
|
|
647
|
+
tags: [],
|
|
648
|
+
components: {},
|
|
649
|
+
};
|
|
650
|
+
const publicOperations = [];
|
|
651
|
+
const usedTags = new Set();
|
|
652
|
+
// Filter paths to only include x-micro-contracts-published: true
|
|
653
|
+
for (const [pathKey, pathItem] of Object.entries(spec.paths)) {
|
|
654
|
+
const filteredPathItem = {};
|
|
655
|
+
let hasPublicOperation = false;
|
|
656
|
+
for (const method of ['get', 'post', 'put', 'patch', 'delete']) {
|
|
657
|
+
const operation = pathItem[method];
|
|
658
|
+
if (operation?.['x-micro-contracts-published'] === true) {
|
|
659
|
+
filteredPathItem[method] = operation;
|
|
660
|
+
hasPublicOperation = true;
|
|
661
|
+
publicOperations.push(operation);
|
|
662
|
+
for (const tag of operation.tags ?? []) {
|
|
663
|
+
usedTags.add(tag);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
if (hasPublicOperation) {
|
|
668
|
+
filtered.paths[pathKey] = filteredPathItem;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
// Keep exactly the components the public operations reach, in every section.
|
|
672
|
+
// Copying a section wholesale left components that only private endpoints
|
|
673
|
+
// used, referring to schemas this filter had dropped: a dangling $ref.
|
|
674
|
+
const reachable = collectReachableComponents(publicOperations, spec);
|
|
675
|
+
const sourceComponents = spec.components;
|
|
676
|
+
const targetComponents = filtered.components;
|
|
677
|
+
// Iterate the spec's own order, not the traversal order, so the published
|
|
678
|
+
// document keeps the declaration order of its source.
|
|
679
|
+
for (const [section, entries] of Object.entries(sourceComponents ?? {})) {
|
|
680
|
+
if (!entries || typeof entries !== 'object')
|
|
681
|
+
continue;
|
|
682
|
+
for (const [name, component] of Object.entries(entries)) {
|
|
683
|
+
if (!reachable.has(`${section}/${name}`))
|
|
684
|
+
continue;
|
|
685
|
+
targetComponents[section] = targetComponents[section] ?? {};
|
|
686
|
+
targetComponents[section][name] = component;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
// Filter tags to only include used ones
|
|
690
|
+
if (spec.tags) {
|
|
691
|
+
filtered.tags = spec.tags.filter(tag => usedTags.has(tag.name));
|
|
692
|
+
}
|
|
693
|
+
// Clean up empty sections
|
|
694
|
+
for (const [section, entries] of Object.entries(filtered.components ?? {})) {
|
|
695
|
+
if (entries && typeof entries === 'object' && Object.keys(entries).length === 0) {
|
|
696
|
+
delete filtered.components[section];
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
if (Object.keys(filtered.components ?? {}).length === 0) {
|
|
700
|
+
delete filtered.components;
|
|
701
|
+
}
|
|
702
|
+
if (filtered.tags?.length === 0) {
|
|
703
|
+
delete filtered.tags;
|
|
704
|
+
}
|
|
705
|
+
return filtered;
|
|
706
|
+
}
|
|
707
|
+
//# sourceMappingURL=index.js.map
|