contractdiff 0.0.0-stage → 0.4.2

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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +228 -2
  3. package/dist/bin.js +4 -0
  4. package/dist/cli.d.ts +3 -0
  5. package/dist/cli.js +24 -0
  6. package/dist/command-diff.js +310 -0
  7. package/dist/command-explain-cap.js +36 -0
  8. package/dist/command-explain-inline.js +17 -0
  9. package/dist/command-explain-name.js +31 -0
  10. package/dist/command-explain-operation.js +85 -0
  11. package/dist/command-explain-text.js +21 -0
  12. package/dist/command-explain.js +54 -0
  13. package/dist/command-lint.js +280 -0
  14. package/dist/command-migrate.js +70 -0
  15. package/dist/command-plugin.js +32 -0
  16. package/dist/command-props.js +116 -0
  17. package/dist/commands.js +7 -0
  18. package/dist/core/index.d.ts +2 -0
  19. package/dist/core/index.js +2 -0
  20. package/dist/core/model.d.ts +46 -0
  21. package/dist/core/model.js +1 -0
  22. package/dist/core/resolve.d.ts +22 -0
  23. package/dist/core/resolve.js +71 -0
  24. package/dist/diff-classify.js +30 -0
  25. package/dist/diff-contract.js +176 -0
  26. package/dist/diff-decisions.js +446 -0
  27. package/dist/diff-normalise.js +143 -0
  28. package/dist/diff-rules.js +109 -0
  29. package/dist/diff-schema.js +335 -0
  30. package/dist/diff-security.js +33 -0
  31. package/dist/diff-transitive.js +26 -0
  32. package/dist/diff-usage.js +59 -0
  33. package/dist/extract-normalise.js +85 -0
  34. package/dist/extract-roundtrip.js +28 -0
  35. package/dist/extract-standard.js +79 -0
  36. package/dist/gen-ts-ast.d.ts +135 -0
  37. package/dist/gen-ts-ast.js +52 -0
  38. package/dist/gen-ts-bundle.js +233 -0
  39. package/dist/gen-ts-comment.js +48 -0
  40. package/dist/gen-ts-context.d.ts +83 -0
  41. package/dist/gen-ts-context.js +45 -0
  42. package/dist/gen-ts-dict.d.ts +14 -0
  43. package/dist/gen-ts-dict.js +14 -0
  44. package/dist/gen-ts-discriminators.d.ts +7 -0
  45. package/dist/gen-ts-discriminators.js +117 -0
  46. package/dist/gen-ts-document.d.ts +12 -0
  47. package/dist/gen-ts-document.js +82 -0
  48. package/dist/gen-ts-enums.js +139 -0
  49. package/dist/gen-ts-helpers.js +30 -0
  50. package/dist/gen-ts-index.d.ts +49 -0
  51. package/dist/gen-ts-index.js +110 -0
  52. package/dist/gen-ts-operations.js +277 -0
  53. package/dist/gen-ts-print.js +113 -0
  54. package/dist/gen-ts-ref.d.ts +30 -0
  55. package/dist/gen-ts-ref.js +75 -0
  56. package/dist/gen-ts-schema.js +283 -0
  57. package/dist/gen-ts-text.d.ts +24 -0
  58. package/dist/gen-ts-text.js +98 -0
  59. package/dist/host.d.ts +145 -0
  60. package/dist/host.js +273 -0
  61. package/dist/index.d.ts +6 -0
  62. package/dist/index.js +5 -0
  63. package/dist/input-asyncapi.js +167 -0
  64. package/dist/input-buf.js +58 -0
  65. package/dist/input-jsonschema.js +165 -0
  66. package/dist/input-mcp.js +111 -0
  67. package/dist/input-overlay-jsonpath.js +265 -0
  68. package/dist/input-overlay.js +138 -0
  69. package/dist/input-protobuf.js +212 -0
  70. package/dist/input-swagger2.js +331 -0
  71. package/dist/inputs.js +8 -0
  72. package/dist/lint-code-read.js +129 -0
  73. package/dist/lint-code.d.ts +56 -0
  74. package/dist/lint-code.js +64 -0
  75. package/dist/lint-engine.d.ts +93 -0
  76. package/dist/lint-engine.js +87 -0
  77. package/dist/lint-functions.js +95 -0
  78. package/dist/lint-history.js +133 -0
  79. package/dist/lint-jsonpath.js +92 -0
  80. package/dist/lint-names.d.ts +11 -0
  81. package/dist/lint-names.js +2 -0
  82. package/dist/lint-redocly.js +141 -0
  83. package/dist/lint-rules.js +189 -0
  84. package/dist/lint-select.d.ts +33 -0
  85. package/dist/lint-select.js +129 -0
  86. package/dist/lint-since.js +20 -0
  87. package/dist/lint-spectral.js +167 -0
  88. package/dist/lint-stats.js +58 -0
  89. package/dist/migrate-hey-api.js +144 -0
  90. package/dist/migrate-literal.js +139 -0
  91. package/dist/migrate-openapi-fetch.js +62 -0
  92. package/dist/migrate-openapi-typescript.js +159 -0
  93. package/dist/migrate-orval.js +119 -0
  94. package/dist/migrate-shared.js +31 -0
  95. package/dist/openapi-typescript.d.ts +9 -0
  96. package/dist/openapi-typescript.js +36 -0
  97. package/dist/openapi.d.ts +20 -0
  98. package/dist/openapi.js +94 -0
  99. package/dist/plugin-express.js +66 -0
  100. package/dist/plugin-extract-hono.js +1 -0
  101. package/dist/plugin-extract-nest.js +1 -0
  102. package/dist/plugin-extract-openapi.js +246 -0
  103. package/dist/plugin-extract-standard-schema.js +42 -0
  104. package/dist/plugin-extract-trpc.js +1 -0
  105. package/dist/plugin-extract-ts-rest.js +77 -0
  106. package/dist/plugin-fastify.js +68 -0
  107. package/dist/plugin-fetch-client.js +172 -0
  108. package/dist/plugin-fetch-routes.js +110 -0
  109. package/dist/plugin-fetch-sample.js +155 -0
  110. package/dist/plugin-fetch-text.js +5 -0
  111. package/dist/plugin-fetch.js +19 -0
  112. package/dist/plugin-hono.js +42 -0
  113. package/dist/plugin-json-schema-build.js +289 -0
  114. package/dist/plugin-json-schema-dialect-anthropic.js +41 -0
  115. package/dist/plugin-json-schema-dialect-gemini.js +29 -0
  116. package/dist/plugin-json-schema-dialect-mcp-elicitation.js +32 -0
  117. package/dist/plugin-json-schema-dialect-mcp.js +13 -0
  118. package/dist/plugin-json-schema-dialect-openai.js +37 -0
  119. package/dist/plugin-json-schema-dialect.js +180 -0
  120. package/dist/plugin-json-schema.js +125 -0
  121. package/dist/plugin-markdown.js +114 -0
  122. package/dist/plugin-mcp-code.js +28 -0
  123. package/dist/plugin-mcp-tools.js +152 -0
  124. package/dist/plugin-mcp.js +107 -0
  125. package/dist/plugin-msw-files.js +50 -0
  126. package/dist/plugin-msw-sample.js +45 -0
  127. package/dist/plugin-msw-synth.js +116 -0
  128. package/dist/plugin-msw.js +30 -0
  129. package/dist/plugin-nest-code.js +68 -0
  130. package/dist/plugin-nest-contract.js +23 -0
  131. package/dist/plugin-nest.js +44 -0
  132. package/dist/plugin-server-code.js +61 -0
  133. package/dist/plugin-server-contract.js +48 -0
  134. package/dist/plugin-server-example.js +62 -0
  135. package/dist/plugin-server-router.js +77 -0
  136. package/dist/plugin-server-routes.js +155 -0
  137. package/dist/plugin-server-runtime.js +3 -0
  138. package/dist/plugin-server-sample.js +40 -0
  139. package/dist/plugin-swr-sample.js +21 -0
  140. package/dist/plugin-swr.js +40 -0
  141. package/dist/plugin-tanstack-query-sample.js +21 -0
  142. package/dist/plugin-tanstack-query.js +59 -0
  143. package/dist/plugin-types.js +80 -0
  144. package/dist/plugin-validator-code.js +41 -0
  145. package/dist/plugin-validator-names.js +27 -0
  146. package/dist/plugin-validator.js +103 -0
  147. package/dist/plugins.js +21 -0
  148. package/dist/props-emit.js +194 -0
  149. package/dist/props-generate.js +409 -0
  150. package/dist/props-judge.js +61 -0
  151. package/dist/props-mutate.js +144 -0
  152. package/dist/props-random.js +25 -0
  153. package/dist/props-run.js +176 -0
  154. package/dist/props-shrink.js +75 -0
  155. package/dist/run-apply.js +25 -0
  156. package/dist/run-command.js +31 -0
  157. package/dist/run-commit.d.ts +51 -0
  158. package/dist/run-commit.js +48 -0
  159. package/dist/run-config.d.ts +193 -0
  160. package/dist/run-config.js +256 -0
  161. package/dist/run-diff.js +24 -0
  162. package/dist/run-extract.d.ts +13 -0
  163. package/dist/run-extract.js +21 -0
  164. package/dist/run-gen.d.ts +15 -0
  165. package/dist/run-gen.js +43 -0
  166. package/dist/run-header.js +37 -0
  167. package/dist/run-input.js +31 -0
  168. package/dist/run-load.js +32 -0
  169. package/dist/run-map.d.ts +41 -0
  170. package/dist/run-map.js +52 -0
  171. package/dist/run-plan.d.ts +31 -0
  172. package/dist/run-plan.js +35 -0
  173. package/dist/scaffold-seed.js +43 -0
  174. package/dist/scaffold-write.js +17 -0
  175. package/dist/scaffold.js +196 -0
  176. package/dist/testing-lint.js +43 -0
  177. package/dist/testing-owner.js +17 -0
  178. package/dist/testing-probe.js +25 -0
  179. package/dist/testing-rules.d.ts +65 -0
  180. package/dist/testing-rules.js +115 -0
  181. package/dist/testing.d.ts +32 -0
  182. package/dist/testing.js +79 -0
  183. package/package.json +108 -4
@@ -0,0 +1,165 @@
1
+ const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
2
+ const token = (key) => key.replaceAll('~', '~0').replaceAll('/', '~1');
3
+ const TYPES = new Set(['null', 'boolean', 'object', 'array', 'number', 'string', 'integer']);
4
+ const DIALECTS = new Set([
5
+ 'json-schema.org/draft/2020-12/schema',
6
+ 'json-schema.org/draft/2019-09/schema',
7
+ 'json-schema.org/draft-07/schema',
8
+ 'json-schema.org/draft-06/schema',
9
+ 'json-schema.org/draft-04/schema',
10
+ ]);
11
+ const DATA = new Set(['const', 'default', 'enum', 'examples']);
12
+ const DYNAMIC = new Set(['$dynamicRef', '$recursiveRef']);
13
+ export class JsonSchemaError extends Error {
14
+ constructor(reason, fix) {
15
+ super(`not a JSON Schema: ${reason}. fix: ${fix}`);
16
+ this.name = 'JsonSchemaError';
17
+ }
18
+ }
19
+ const isType = (value) => TYPES.has(value) || (Array.isArray(value) && value.length > 0 && value.every((item) => TYPES.has(item)));
20
+ export const detect = (document) => isDict(document) &&
21
+ (typeof document.$schema === 'string' ||
22
+ typeof document.$id === 'string' ||
23
+ typeof document.$ref === 'string' ||
24
+ isDict(document.$defs) ||
25
+ isDict(document.definitions) ||
26
+ isDict(document.properties) ||
27
+ isType(document.type));
28
+ const isSchema = (value) => typeof value === 'boolean' || isDict(value);
29
+ const embedded = (node) => {
30
+ if (!isDict(node))
31
+ return false;
32
+ const id = typeof node.$id === 'string' ? node.$id : node.id;
33
+ return typeof id === 'string' && !id.startsWith('#');
34
+ };
35
+ const referenceFinding = (keyword, ref, pointer, resource) => {
36
+ if (DYNAMIC.has(keyword)) {
37
+ return {
38
+ code: 'ref-dynamic',
39
+ pointer,
40
+ message: `\`${keyword}: ${ref}\` is passed as written; references are resolved only through \`$ref\``,
41
+ fix: 'use a `$ref` to a `#/$defs/…` pointer where the dynamic scope is not needed',
42
+ };
43
+ }
44
+ if (!ref.startsWith('#')) {
45
+ return {
46
+ code: 'ref-external',
47
+ pointer,
48
+ message: `\`$ref: ${ref}\` is a URI, not a fragment of this document, and is passed as written`,
49
+ fix: 'bundle the schemas into one document first, or use a `#/…` reference',
50
+ };
51
+ }
52
+ if (ref !== '#' && !ref.startsWith('#/')) {
53
+ return {
54
+ code: 'ref-anchor',
55
+ pointer,
56
+ message: `\`$ref: ${ref}\` names an anchor, which is passed as written; only JSON Pointers are resolved`,
57
+ fix: 'reference the subschema by JSON Pointer, e.g. `#/$defs/…`',
58
+ };
59
+ }
60
+ if (resource === undefined)
61
+ return undefined;
62
+ return {
63
+ code: 'ref-in-embedded-resource',
64
+ pointer,
65
+ message: `\`$ref: ${ref}\` is relative to the embedded resource at \`${resource}\`, and is resolved from the document root`,
66
+ fix: "move the subschema under the root's `$defs` and drop its `$id`",
67
+ };
68
+ };
69
+ const childrenOf = (node, pointer) => {
70
+ if (Array.isArray(node))
71
+ return node.map((item, index) => [String(index), item, `${pointer}/${String(index)}`]);
72
+ if (!isDict(node))
73
+ return [];
74
+ return Object.entries(node).map(([key, child]) => [key, child, `${pointer}/${token(key)}`]);
75
+ };
76
+ const isReference = (keyword, value) => (keyword === '$ref' || DYNAMIC.has(keyword)) && typeof value === 'string';
77
+ const references = (root) => {
78
+ const findings = [];
79
+ const walk = (node, pointer, resource) => {
80
+ const inside = resource ?? (pointer !== '#' && embedded(node) ? pointer : undefined);
81
+ for (const [keyword, child, at] of childrenOf(node, pointer)) {
82
+ if (DATA.has(keyword))
83
+ continue;
84
+ if (!isReference(keyword, child)) {
85
+ walk(child, at, inside);
86
+ continue;
87
+ }
88
+ const finding = referenceFinding(keyword, child, at, inside);
89
+ if (finding !== undefined)
90
+ findings.push(finding);
91
+ }
92
+ };
93
+ walk(root, '#', undefined);
94
+ return findings;
95
+ };
96
+ const known = (dialect) => DIALECTS.has(dialect.replace(/^https?:\/\//, '').replace(/#$/, ''));
97
+ const rootId = (root) => {
98
+ for (const key of ['$id', 'id', 'title']) {
99
+ if (typeof root[key] === 'string')
100
+ return root[key];
101
+ }
102
+ return 'schema';
103
+ };
104
+ const operationOf = (id, source, schema) => ({
105
+ id,
106
+ source,
107
+ payloads: [{ name: 'value', direction: 'request', schema, required: true }],
108
+ });
109
+ export const read = (document) => {
110
+ if (typeof document === 'boolean') {
111
+ return { format: 'jsonschema', document, operations: [operationOf('schema', '#', document)], findings: [] };
112
+ }
113
+ if (!isDict(document)) {
114
+ throw new JsonSchemaError('a schema is an object or a boolean', 'pass the parsed schema document, not a list or a value');
115
+ }
116
+ const findings = [];
117
+ if (typeof document.$schema === 'string' && !known(document.$schema)) {
118
+ findings.push({
119
+ code: 'dialect-unknown',
120
+ pointer: '#/$schema',
121
+ message: `\`$schema: ${document.$schema}\` is not a dialect this reader knows; it is read as 2020-12`,
122
+ fix: 'use the 2020-12, 2019-09, draft-07, draft-06 or draft-04 meta-schema URI',
123
+ });
124
+ }
125
+ const root = rootId(document);
126
+ const operations = [operationOf(root, '#', document)];
127
+ const taken = new Set([root]);
128
+ for (const keyword of ['$defs', 'definitions']) {
129
+ const group = document[keyword];
130
+ if (!isDict(group))
131
+ continue;
132
+ for (const [name, schema] of Object.entries(group)) {
133
+ const source = `#/${keyword}/${token(name)}`;
134
+ if (!isSchema(schema)) {
135
+ findings.push({
136
+ code: 'not-a-schema',
137
+ pointer: source,
138
+ message: `\`${keyword}.${name}\` is neither an object nor a boolean, so it is not read as an operation`,
139
+ fix: `make it a schema, or move it out of \`${keyword}\``,
140
+ });
141
+ continue;
142
+ }
143
+ let id = name;
144
+ if (taken.has(name)) {
145
+ id = `${keyword}/${name}`;
146
+ findings.push({
147
+ code: 'id-collision',
148
+ pointer: source,
149
+ message: `another operation is already named \`${name}\`, so this one is \`${id}\``,
150
+ fix: 'give the definitions, and the root `$id` or `title`, distinct names',
151
+ });
152
+ }
153
+ taken.add(id);
154
+ operations.push(operationOf(id, source, schema));
155
+ }
156
+ }
157
+ findings.push(...references(document));
158
+ return { format: 'jsonschema', document, operations, findings };
159
+ };
160
+ export const adapter = Object.freeze({
161
+ name: 'jsonschema',
162
+ description: 'JSON Schema documents (2020-12, 2019-09, draft-07, draft-06, draft-04): the root and each `$defs` entry',
163
+ detect,
164
+ read,
165
+ });
@@ -0,0 +1,111 @@
1
+ const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
2
+ const LISTS = ['tools', 'prompts', 'resourceTemplates'];
3
+ export class McpError extends Error {
4
+ constructor(reason, fix) {
5
+ super(`not an MCP snapshot: ${reason}. fix: ${fix}`);
6
+ this.name = 'McpError';
7
+ }
8
+ }
9
+ const isTool = (value) => typeof value.name === 'string' && 'inputSchema' in value;
10
+ const hasList = (value) => LISTS.some((key) => Array.isArray(value[key]));
11
+ const isEnvelope = (value) => typeof value.jsonrpc === 'string' && isDict(value.result) && hasList(value.result);
12
+ export const detect = (document) => isDict(document) && (hasList(document) || isTool(document) || isEnvelope(document));
13
+ const strings = (members) => ({
14
+ type: 'object',
15
+ properties: Object.fromEntries(members.map(({ name, description }) => [name, typeof description === 'string' ? { type: 'string', description } : { type: 'string' }])),
16
+ required: members.filter(({ required }) => required).map(({ name }) => name),
17
+ });
18
+ const OPTIONAL_OPERATORS = new Set(['.', '/', ';', '?', '&']);
19
+ const variables = (template) => (template.match(/\{[^}]*\}/g) ?? []).flatMap((braced) => {
20
+ const expression = braced.slice(1, -1);
21
+ const operator = /^[+#./;?&]/.test(expression) ? expression.slice(0, 1) : '';
22
+ return expression
23
+ .slice(operator.length)
24
+ .split(',')
25
+ .map((variable) => ({ name: variable.replace(/(\*|:\d*)$/, ''), required: !OPTIONAL_OPERATORS.has(operator) }));
26
+ });
27
+ const toolOf = (tool, name, at, report) => {
28
+ const payloads = [];
29
+ if (isDict(tool.inputSchema)) {
30
+ payloads.push({ name: 'arguments', direction: 'tool-call', schema: tool.inputSchema, required: true });
31
+ }
32
+ else {
33
+ report('input-schema-missing', `${at}/inputSchema`, `tool \`${name}\` has no object \`inputSchema\`, so its arguments are read as \`{ "type": "object" }\``, 'declare `inputSchema` as an object schema; a tool without parameters has `{ "type": "object" }`');
34
+ payloads.push({ name: 'arguments', direction: 'tool-call', schema: { type: 'object' }, required: true });
35
+ }
36
+ if (isDict(tool.outputSchema)) {
37
+ payloads.push({ name: 'structuredContent', direction: 'tool-result', schema: tool.outputSchema, required: true });
38
+ }
39
+ else if (tool.outputSchema !== undefined) {
40
+ report('output-schema-dropped', `${at}/outputSchema`, `tool \`${name}\` declares an \`outputSchema\` that is not an object schema, so its result is not read`, 'make `outputSchema` an object schema, or remove it');
41
+ }
42
+ return { id: name, source: at, payloads };
43
+ };
44
+ const promptOf = (prompt, name, at, report) => {
45
+ const declared = Array.isArray(prompt.arguments) ? prompt.arguments.filter((argument) => isDict(argument) && typeof argument.name === 'string') : [];
46
+ const members = declared.map((argument) => ({ name: argument.name, description: argument.description, required: argument.required === true }));
47
+ if (declared.length > 0) {
48
+ report('prompt-arguments-synthesised', `${at}/arguments`, `prompt \`${name}\` declares arguments, not a schema; its \`tool-call\` payload is an object of strings built from them`, 'nothing to do: prompt arguments are strings on the wire; describe each in `arguments[].description`');
49
+ }
50
+ return { id: `prompt:${name}`, source: at, payloads: [{ name: 'arguments', direction: 'tool-call', schema: strings(members), required: true }] };
51
+ };
52
+ const templateOf = (template, uriTemplate, at, report) => {
53
+ report('resource-variables-synthesised', `${at}/uriTemplate`, `resource template \`${uriTemplate}\` declares a URI template, not a schema; its \`tool-call\` payload is an object of strings built from its variables`, 'nothing to do: URI template variables are strings');
54
+ return {
55
+ id: `resource:${uriTemplate}`,
56
+ source: at,
57
+ payloads: [{ name: 'variables', direction: 'tool-call', schema: strings(variables(uriTemplate)), required: true }],
58
+ };
59
+ };
60
+ const READERS = {
61
+ tools: { key: 'name', of: toolOf },
62
+ prompts: { key: 'name', of: promptOf },
63
+ resourceTemplates: { key: 'uriTemplate', of: templateOf },
64
+ };
65
+ const entriesOf = (body, base, report) => {
66
+ const operations = [];
67
+ const seen = new Set();
68
+ for (const list of LISTS) {
69
+ const entries = Array.isArray(body[list]) ? body[list] : [];
70
+ const { key, of } = READERS[list];
71
+ for (const [index, entry] of entries.entries()) {
72
+ const at = `${base}/${list}/${String(index)}`;
73
+ if (!isDict(entry) || typeof entry[key] !== 'string') {
74
+ report('entry-unnamed', at, `\`${list}[${String(index)}]\` has no \`${key}\`, so it is not read`, `give it a string \`${key}\``);
75
+ continue;
76
+ }
77
+ const operation = of(entry, entry[key], at, report);
78
+ if (seen.has(operation.id)) {
79
+ report('duplicate-name', at, `\`${operation.id}\` is listed twice; the first is read`, 'give each entry a distinct name');
80
+ continue;
81
+ }
82
+ seen.add(operation.id);
83
+ operations.push(operation);
84
+ }
85
+ }
86
+ return operations;
87
+ };
88
+ export const read = (document) => {
89
+ if (!detect(document)) {
90
+ throw new McpError('it has no `tools`, `prompts` or `resourceTemplates` list and is not a tool', 'pass the `result` of `tools/list`, `prompts/list` or `resources/templates/list`, or one tool');
91
+ }
92
+ const root = document;
93
+ const findings = [];
94
+ const report = (code, pointer, message, fix) => {
95
+ findings.push({ code, pointer, message, fix });
96
+ };
97
+ if (isTool(root) && !hasList(root)) {
98
+ return { format: 'mcp', document, operations: [toolOf(root, root.name, '#', report)], findings };
99
+ }
100
+ const [body, base] = isEnvelope(root) ? [root.result, '#/result'] : [root, '#'];
101
+ if (typeof body.nextCursor === 'string') {
102
+ report('page-incomplete', `${base}/nextCursor`, 'this snapshot is one page of a longer list; entries on later pages are not read', 'snapshot every page: repeat the request with `cursor` until no `nextCursor` comes back');
103
+ }
104
+ return { format: 'mcp', document, operations: entriesOf(body, base, report), findings };
105
+ };
106
+ export const adapter = Object.freeze({
107
+ name: 'mcp',
108
+ description: 'MCP snapshots: `tools/list`, `prompts/list` and `resources/templates/list` results, or one tool',
109
+ detect,
110
+ read,
111
+ });
@@ -0,0 +1,265 @@
1
+ export class JsonPathError extends Error {
2
+ constructor(path, reason, fix) {
3
+ super(`cannot read the JSONPath \`${path}\`: ${reason}. fix: ${fix}`);
4
+ this.name = 'JsonPathError';
5
+ }
6
+ }
7
+ const NAME_FIRST = /[A-Za-z_\u0080-\uFFFF]/;
8
+ const NAME_REST = /[\w\-\u0080-\uFFFF]/;
9
+ const COMPARATORS = ['==', '!=', '<=', '>=', '<', '>'];
10
+ const createParser = (path) => {
11
+ let at = 0;
12
+ const fail = (reason, fix = 'write the query as RFC 9535 describes it') => {
13
+ throw new JsonPathError(path, `${reason} at character ${String(at)}`, fix);
14
+ };
15
+ const blank = () => {
16
+ while (at < path.length && ' \t\n\r'.includes(path.charAt(at)))
17
+ at += 1;
18
+ };
19
+ const take = (text) => {
20
+ if (!path.startsWith(text, at))
21
+ return false;
22
+ at += text.length;
23
+ return true;
24
+ };
25
+ const quoted = () => {
26
+ const quote = path.charAt(at);
27
+ at += 1;
28
+ let text = '';
29
+ while (at < path.length && path.charAt(at) !== quote) {
30
+ if (path.charAt(at) === '\\')
31
+ at += 1;
32
+ text += path.charAt(at);
33
+ at += 1;
34
+ }
35
+ if (!take(quote))
36
+ fail('a string is not closed');
37
+ return text;
38
+ };
39
+ const integer = () => {
40
+ const match = /^-?\d+/.exec(path.slice(at));
41
+ if (match === null)
42
+ return fail(`\`${path.charAt(at)}\` is not a selector`);
43
+ at += match[0].length;
44
+ if (path.charAt(at) === ':')
45
+ fail('array slices are not read', 'select the items by index, or with a filter');
46
+ return Number(match[0]);
47
+ };
48
+ const shorthand = () => {
49
+ if (take('*'))
50
+ return { kind: 'wildcard' };
51
+ if (!NAME_FIRST.test(path.charAt(at)))
52
+ fail('a name is expected after `.`');
53
+ const start = at;
54
+ while (NAME_REST.test(path.charAt(at)))
55
+ at += 1;
56
+ return { kind: 'name', name: path.slice(start, at) };
57
+ };
58
+ let expression;
59
+ const selector = () => {
60
+ blank();
61
+ if (path.charAt(at) === "'" || path.charAt(at) === '"')
62
+ return { kind: 'name', name: quoted() };
63
+ if (take('*'))
64
+ return { kind: 'wildcard' };
65
+ if (take('?'))
66
+ return { kind: 'filter', test: expression() };
67
+ return { kind: 'index', index: integer() };
68
+ };
69
+ const bracketed = () => {
70
+ const selectors = [selector()];
71
+ blank();
72
+ while (take(',')) {
73
+ selectors.push(selector());
74
+ blank();
75
+ }
76
+ if (!take(']'))
77
+ fail('a `]` is expected');
78
+ return selectors;
79
+ };
80
+ const segments = () => {
81
+ const list = [];
82
+ for (;;) {
83
+ const mark = at;
84
+ blank();
85
+ if (take('..')) {
86
+ list.push({ descendant: true, selectors: take('[') ? bracketed() : [shorthand()] });
87
+ }
88
+ else if (take('.')) {
89
+ list.push({ descendant: false, selectors: [shorthand()] });
90
+ }
91
+ else if (take('[')) {
92
+ list.push({ descendant: false, selectors: bracketed() });
93
+ }
94
+ else {
95
+ at = mark;
96
+ return list;
97
+ }
98
+ }
99
+ };
100
+ const query = () => {
101
+ const root = path.charAt(at);
102
+ if (root !== '$' && root !== '@')
103
+ return undefined;
104
+ at += 1;
105
+ return { root, segments: segments() };
106
+ };
107
+ const literal = () => {
108
+ if (path.charAt(at) === "'" || path.charAt(at) === '"')
109
+ return { kind: 'literal', value: quoted() };
110
+ for (const [word, value] of [
111
+ ['true', true],
112
+ ['false', false],
113
+ ['null', null],
114
+ ]) {
115
+ if (take(word))
116
+ return { kind: 'literal', value };
117
+ }
118
+ const match = /^-?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?/.exec(path.slice(at));
119
+ if (match === null) {
120
+ return /^[a-z]\w*\(/.test(path.slice(at))
121
+ ? fail('function extensions are not read', 'compare the value directly, or select it with a filter')
122
+ : fail('a value or a query is expected');
123
+ }
124
+ at += match[0].length;
125
+ return { kind: 'literal', value: Number(match[0]) };
126
+ };
127
+ const operand = () => {
128
+ const found = query();
129
+ return found === undefined ? literal() : { kind: 'query', query: found };
130
+ };
131
+ const basic = () => {
132
+ blank();
133
+ if (take('!'))
134
+ return { kind: 'not', operand: basic() };
135
+ if (take('(')) {
136
+ const inner = expression();
137
+ if (!take(')'))
138
+ fail('a `)` is expected');
139
+ return inner;
140
+ }
141
+ const left = operand();
142
+ blank();
143
+ const op = COMPARATORS.find((candidate) => take(candidate));
144
+ if (op === undefined) {
145
+ if (left.kind === 'literal')
146
+ fail('a value on its own is not a test', 'compare it with something, e.g. `@.name == …`');
147
+ return { kind: 'exists', query: left.query };
148
+ }
149
+ blank();
150
+ return { kind: 'compare', op, left, right: operand() };
151
+ };
152
+ const binary = (kind, symbol, next) => () => {
153
+ let left = next();
154
+ blank();
155
+ while (take(symbol)) {
156
+ left = { kind, left, right: next() };
157
+ blank();
158
+ }
159
+ return left;
160
+ };
161
+ expression = binary('or', '||', binary('and', '&&', basic));
162
+ return {
163
+ parse: () => {
164
+ blank();
165
+ if (!take('$'))
166
+ fail('a query starts with `$`');
167
+ const parsed = { root: '$', segments: segments() };
168
+ blank();
169
+ if (at < path.length)
170
+ fail(`\`${path.slice(at)}\` is not read`);
171
+ return parsed;
172
+ },
173
+ };
174
+ };
175
+ export const parse = (path) => createParser(path).parse();
176
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
177
+ const children = (node) => {
178
+ const { value } = node;
179
+ if (Array.isArray(value))
180
+ return value.map((item, index) => ({ value: item, parent: value, key: index }));
181
+ if (!isObject(value))
182
+ return [];
183
+ return Object.entries(value).map(([key, item]) => ({ value: item, parent: value, key }));
184
+ };
185
+ const descendants = (node) => [node, ...children(node).flatMap((child) => descendants(child))];
186
+ const deepEqual = (left, right) => {
187
+ if (Array.isArray(left) && Array.isArray(right))
188
+ return left.length === right.length && left.every((item, index) => deepEqual(item, right[index]));
189
+ if (isObject(left) && isObject(right)) {
190
+ const keys = Object.keys(left);
191
+ return keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && deepEqual(left[key], right[key]));
192
+ }
193
+ return left === right;
194
+ };
195
+ const NOTHING = Symbol('nothing');
196
+ const lessThan = (left, right) => (typeof left === 'number' && typeof right === 'number') || (typeof left === 'string' && typeof right === 'string') ? left < right : false;
197
+ const compare = (op, left, right) => {
198
+ const equal = deepEqual(left, right);
199
+ const less = lessThan(left, right);
200
+ const results = {
201
+ '==': equal,
202
+ '!=': !equal,
203
+ '<': less,
204
+ '<=': less || equal,
205
+ '>': lessThan(right, left),
206
+ '>=': lessThan(right, left) || equal,
207
+ };
208
+ return results[op];
209
+ };
210
+ const select = (node, selector, test) => {
211
+ const all = children(node);
212
+ switch (selector.kind) {
213
+ case 'wildcard': {
214
+ return all;
215
+ }
216
+ case 'name': {
217
+ return isObject(node.value) ? all.filter(({ key }) => key === selector.name) : [];
218
+ }
219
+ case 'index': {
220
+ const index = selector.index < 0 ? all.length + selector.index : selector.index;
221
+ return all.filter(({ key }) => key === index);
222
+ }
223
+ case 'filter': {
224
+ return all.filter((child) => test(selector.test, child));
225
+ }
226
+ }
227
+ };
228
+ const createEvaluator = (document) => {
229
+ const rootNode = { value: document, parent: undefined, key: undefined };
230
+ const run = (query, current) => {
231
+ let nodes = [query.root === '$' ? rootNode : current];
232
+ for (const { descendant, selectors } of query.segments) {
233
+ const from = descendant ? nodes.flatMap((node) => descendants(node)) : nodes;
234
+ nodes = from.flatMap((node) => selectors.flatMap((selector) => select(node, selector, test)));
235
+ }
236
+ return nodes;
237
+ };
238
+ const valueOf = (operand, current) => {
239
+ if (operand.kind === 'literal')
240
+ return operand.value;
241
+ const nodes = run(operand.query, current);
242
+ return nodes.length === 1 ? nodes[0]?.value : NOTHING;
243
+ };
244
+ const test = (expression, current) => {
245
+ switch (expression.kind) {
246
+ case 'or': {
247
+ return test(expression.left, current) || test(expression.right, current);
248
+ }
249
+ case 'and': {
250
+ return test(expression.left, current) && test(expression.right, current);
251
+ }
252
+ case 'not': {
253
+ return !test(expression.operand, current);
254
+ }
255
+ case 'exists': {
256
+ return run(expression.query, current).length > 0;
257
+ }
258
+ case 'compare': {
259
+ return compare(expression.op, valueOf(expression.left, current), valueOf(expression.right, current));
260
+ }
261
+ }
262
+ };
263
+ return { run: (query) => run(query, rootNode) };
264
+ };
265
+ export const query = (document, path) => createEvaluator(document).run(parse(path));
@@ -0,0 +1,138 @@
1
+ import { pointerGet } from './core/resolve.js';
2
+ import { query } from './input-overlay-jsonpath.js';
3
+ const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
4
+ const isPrimitive = (value) => !Array.isArray(value) && !isDict(value);
5
+ const setMember = (target, key, value) => {
6
+ Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
7
+ };
8
+ export class OverlayError extends Error {
9
+ constructor(reason, fix) {
10
+ super(`cannot apply the overlay: ${reason}. fix: ${fix}`);
11
+ this.name = 'OverlayError';
12
+ }
13
+ }
14
+ export const detect = (document) => isDict(document) && typeof document.overlay === 'string' && document.overlay.startsWith('1.');
15
+ const merge = (target, update, at) => {
16
+ for (const [key, value] of Object.entries(update)) {
17
+ const where = `${at}.${key}`;
18
+ const current = Object.getOwnPropertyDescriptor(target, key)?.value;
19
+ if (current === undefined)
20
+ setMember(target, key, structuredClone(value));
21
+ else if (isPrimitive(current) && isPrimitive(value))
22
+ setMember(target, key, value);
23
+ else if (Array.isArray(current) && Array.isArray(value))
24
+ current.push(...structuredClone(value));
25
+ else if (isDict(current) && isDict(value))
26
+ merge(current, value, where);
27
+ else
28
+ throw new OverlayError(`\`${where}\` is ${kindOf(current)} in the document and ${kindOf(value)} in the update`, 'update a member with a value of the same kind, or remove it first');
29
+ }
30
+ };
31
+ const kindOf = (value) => {
32
+ if (Array.isArray(value))
33
+ return 'an array';
34
+ return isDict(value) ? 'an object' : 'a primitive';
35
+ };
36
+ const replace = (node, value, document) => {
37
+ if (node.parent === undefined)
38
+ document.value = value;
39
+ else
40
+ setMember(node.parent, node.key, value);
41
+ };
42
+ const updateEach = (nodes, update, target, document) => {
43
+ for (const node of nodes) {
44
+ if (Array.isArray(node.value)) {
45
+ node.value.push(...(Array.isArray(update) ? structuredClone(update) : [structuredClone(update)]));
46
+ }
47
+ else if (isDict(node.value)) {
48
+ if (!isDict(update))
49
+ throw new OverlayError(`\`${target}\` selects an object, and the update is ${kindOf(update)}`, 'update an object with an object of the members to merge');
50
+ merge(node.value, update, target);
51
+ }
52
+ else {
53
+ if (!isPrimitive(update))
54
+ throw new OverlayError(`\`${target}\` selects a primitive, and the update is ${kindOf(update)}`, 'replace a primitive with a primitive, or target its parent');
55
+ replace(node, update, document);
56
+ }
57
+ }
58
+ };
59
+ const removeEach = (nodes, target) => {
60
+ const items = new Map();
61
+ for (const node of nodes) {
62
+ if (Array.isArray(node.parent))
63
+ items.set(node.parent, new Set([...(items.get(node.parent) ?? []), node.key]));
64
+ else if (node.parent === undefined)
65
+ throw new OverlayError(`\`${target}\` selects the whole document, which cannot be removed`, 'remove its members instead, e.g. `$.paths`');
66
+ else
67
+ Reflect.deleteProperty(node.parent, node.key);
68
+ }
69
+ for (const [list, indexes] of items) {
70
+ for (const index of [...indexes].toSorted((a, b) => b - a))
71
+ list.splice(index, 1);
72
+ }
73
+ };
74
+ const resolveAction = (overlay, action, at) => {
75
+ if (!isDict(action))
76
+ throw new OverlayError(`\`${at}\` is not an action object`, 'write each action as `{ target, update | copy | remove }`');
77
+ if (typeof action.$ref !== 'string')
78
+ return action;
79
+ if (!action.$ref.startsWith('#/components/actions/')) {
80
+ throw new OverlayError(`\`${at}.$ref\` is \`${action.$ref}\``, 'reference a reusable action as `#/components/actions/<name>`');
81
+ }
82
+ let reusable;
83
+ try {
84
+ reusable = pointerGet(overlay, action.$ref);
85
+ }
86
+ catch {
87
+ throw new OverlayError(`\`${at}.$ref\` names \`${action.$ref}\`, which the overlay does not define`, 'define it under `components.actions`');
88
+ }
89
+ if (!isDict(reusable) || (reusable.fields !== undefined && !isDict(reusable.fields))) {
90
+ throw new OverlayError(`\`${action.$ref}\` is not a reusable action`, 'write it as `{ fields: { update | copy | remove } }`');
91
+ }
92
+ const { $ref: _ref, ...own } = action;
93
+ return { ...reusable.fields, ...own };
94
+ };
95
+ const run = (action, index, result, findings) => {
96
+ const at = `actions[${String(index)}]`;
97
+ if (typeof action.target !== 'string')
98
+ throw new OverlayError(`\`${at}\` has no \`target\``, 'say which nodes it applies to, e.g. `target: $.info`');
99
+ const nodes = query(result.value, action.target);
100
+ const report = (code, pointer, message, fix) => {
101
+ findings.push({ code, pointer: `#/actions/${String(index)}${pointer}`, message, fix });
102
+ };
103
+ if (nodes.length === 0) {
104
+ report('target-matched-nothing', '/target', `\`${action.target}\` selects nothing in the document, so the action changes nothing`, 'update the target to match the document, or remove the action');
105
+ return;
106
+ }
107
+ if (action.remove === true) {
108
+ removeEach(nodes, action.target);
109
+ return;
110
+ }
111
+ if (action.update !== undefined && action.copy !== undefined)
112
+ throw new OverlayError(`\`${at}\` has both \`update\` and \`copy\``, 'split it into two actions');
113
+ if (action.update !== undefined) {
114
+ updateEach(nodes, action.update, action.target, result);
115
+ return;
116
+ }
117
+ if (typeof action.copy !== 'string') {
118
+ report('action-without-effect', '', `the action on \`${action.target}\` has no \`update\`, \`copy\` or \`remove: true\`, so it changes nothing`, 'say what the action does, or remove it');
119
+ return;
120
+ }
121
+ const sources = query(result.value, action.copy);
122
+ if (sources.length !== 1)
123
+ throw new OverlayError(`\`${at}.copy\` selects ${String(sources.length)} nodes`, 'copy from a query that selects exactly one node');
124
+ updateEach(nodes, sources[0]?.value, action.target, result);
125
+ };
126
+ export const apply = (document, overlay) => {
127
+ if (!detect(overlay))
128
+ throw new OverlayError('it has no `overlay: 1.x` member', 'pass an OpenAPI Overlay 1.0, 1.1 or 1.2 document');
129
+ const root = overlay;
130
+ if (!Array.isArray(root.actions))
131
+ throw new OverlayError('it has no `actions` list', 'list the actions to apply under `actions`');
132
+ const result = { value: structuredClone(document) };
133
+ const findings = [];
134
+ for (const [index, written] of root.actions.entries())
135
+ run(resolveAction(root, written, `actions[${String(index)}]`), index, result, findings);
136
+ return { document: result.value, findings };
137
+ };
138
+ export const applyOverlays = (document, overlays) => overlays.reduce((current, overlay) => apply(current, overlay).document, document);