@stitchapi/openapi 1.0.0-rc.4

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # @stitchapi/openapi
2
+
3
+ [![npm](https://img.shields.io/npm/v/@stitchapi/openapi?color=2563EB&label=npm)](https://www.npmjs.com/package/@stitchapi/openapi)
4
+
5
+ **Eject selected operations from an OpenAPI document into ready-to-own
6
+ [StitchAPI](https://stitchapi.dev) source.** A build-time code generator, kept
7
+ separate from the zero-dep `stitchapi` runtime so it can take build-time
8
+ dependencies (a YAML parser, validator emitters) without ever touching the core.
9
+
10
+ You pick which operations to generate, the files land in a directory you own, and
11
+ the generator does not come back to manage them — _eject, not managed
12
+ regeneration_ (see [ADR 0013](https://github.com/rejifald/StitchAPI/blob/main/docs/adr/0013-gen-selective-eject-codegen-from-openapi.md)).
13
+
14
+ ## Usage
15
+
16
+ No install needed — run it with `npx` / `pnpm dlx`:
17
+
18
+ ```bash
19
+ # pick by tag (or --only <id>, --grep <substr>, or --all)
20
+ npx @stitchapi/openapi ./openapi.yaml --tag pet --out ./src/pet-client
21
+
22
+ # preview without writing anything
23
+ npx @stitchapi/openapi ./openapi.json --all --dry-run
24
+ ```
25
+
26
+ | Flag | Meaning |
27
+ | -------------------- | ----------------------------------------------------------------- |
28
+ | `<spec>` | an OpenAPI 3.x document (JSON or YAML) |
29
+ | `--out, -o <dir>` | output directory (required unless `--dry-run`) |
30
+ | `--all` | generate every operation (otherwise pass a selector) |
31
+ | `--tag <t>` | only operations with this tag (repeatable) |
32
+ | `--only <id>` | only this operationId / export name (repeatable) |
33
+ | `--grep <substr>` | only operations whose path contains this substring |
34
+ | `--layout dir\|flat` | `dir` = one folder per operation (default); `flat` = one file |
35
+ | `--validator <t>` | `types-only` (default). valibot/zod tiers are not implemented yet |
36
+ | `--dry-run` | print the files to stdout instead of writing them |
37
+
38
+ ## What it emits
39
+
40
+ A `client.ts` [seam](https://stitchapi.dev) (base URL + auth, with `// TODO`s),
41
+ one stitch per operation typed via `stitch<T>()`, and **atomic** component types
42
+ placed by fan-in — a schema used by ≥2 operations goes to `_shared/`, one used by
43
+ a single operation lives **inside that operation's directory** so deleting the
44
+ operation deletes its private types too. A `.stitch-gen.json` manifest records the
45
+ ownership graph.
46
+
47
+ ```
48
+ src/pet-client/
49
+ client.ts # the seam: baseUrl + auth (edit the TODOs)
50
+ _shared/pet.ts # used by ≥2 operations
51
+ get-pet-by-id/
52
+ index.ts # export const getPetById = client.stitch<Pet>({ ... })
53
+ ...
54
+ .stitch-gen.json # ownership manifest
55
+ ```
56
+
57
+ The output is **yours to edit** — set the base URL and auth in `client.ts`, then:
58
+
59
+ ```ts
60
+ import { getPetById } from './pet-client';
61
+
62
+ const pet = await getPetById({ params: { petId: 1 } }); // typed as Pet
63
+ ```
64
+
65
+ ### Notes
66
+
67
+ - **`types-only` is the default** (the lightest frontend tier): it emits TS types
68
+ and a typed `stitch<T>()` but **no runtime validator**, so response validation
69
+ and drift are off until the `valibot`/`zod` tiers ship. A notice tells you so.
70
+ - **Auth** maps `securitySchemes` → `bearer` / `apiKey` / `basic` with `env()`
71
+ placeholders; the secret is never emitted. oauth2 is flagged for manual setup.
72
+ - The generated client imports from `stitchapi` — add it to your project:
73
+ `npm i stitchapi`.
74
+
75
+ ## Library API
76
+
77
+ The generator is also a pure library:
78
+
79
+ ```ts
80
+ import { type OpenApiDoc, planGen } from '@stitchapi/openapi';
81
+
82
+ const result = planGen(doc as OpenApiDoc, { tags: ['pet'] });
83
+ for (const f of result.files) console.log(f.path, f.contents);
84
+ ```
85
+
86
+ ## License
87
+
88
+ Apache-2.0
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // Thin shim: the implementation lives in src/cli.ts and is bundled to lib/cli.js
5
+ // by the build. Keep this file dependency-free and logic-free.
6
+ require('../lib/cli.js')
7
+ .main(process.argv.slice(2))
8
+ .then((code) => {
9
+ process.exitCode = code || 0;
10
+ })
11
+ .catch((err) => {
12
+ process.stderr.write(`${(err && err.stack) || err}\n`);
13
+ process.exitCode = 1;
14
+ });
@@ -0,0 +1,12 @@
1
+ var J=["get","put","post","delete","patch","options","head","trace"];function M(e){return e.replace(/[{}]/g," ").replace(/[^A-Za-z0-9]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").trim().split(/\s+/).filter(Boolean)}function D(e){let t=M(e);return t.length===0?"op":t.map((n,r)=>r===0?n.toLowerCase():n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join("")}function C(e){let t=D(e);return t.charAt(0).toUpperCase()+t.slice(1)}function q(e){let t=M(e);return t.length?t.map(n=>n.toLowerCase()).join("-"):"item"}function F(e){let t=D(e);return/^[A-Za-z_$]/.test(t)?t:`op${C(t)}`}function Z(e,t,n){return n.operationId?.trim()?F(n.operationId):F(`${e} ${t}`)}function E(e){let t=/^#\/components\/schemas\/([^/]+)$/.exec(e);return t?t[1]:null}function S(e,t,n=0){if(!e||n>30)return"unknown";if(e.$ref){let o=E(e.$ref);return o===null?(t.unresolved.add(e.$ref),"unknown"):(t.used.add(o),C(o))}let r=e.nullable===!0,i=o=>r?`${o} | null`:o;if(Array.isArray(e.enum)&&e.enum.length>0)return i(e.enum.map(o=>JSON.stringify(o)).join(" | "));if(e.const!==void 0)return i(JSON.stringify(e.const));if(Array.isArray(e.allOf)&&e.allOf.length)return i(e.allOf.map(o=>`(${S(o,t,n+1)})`).join(" & "));let a=e.oneOf??e.anyOf;if(Array.isArray(a)&&a.length)return i(a.map(o=>`(${S(o,t,n+1)})`).join(" | "));let g=Array.isArray(e.type)?e.type[0]:e.type;switch(g){case"string":return i("string");case"integer":case"number":return i("number");case"boolean":return i("boolean");case"null":return"null";case"array":return i(`Array<${S(e.items,t,n+1)}>`);default:{if(e.properties){let h=new Set(e.required??[]),O=Object.entries(e.properties).map(([b,f])=>{let m=h.has(b)?"":"?";return`${L(b)}${m}: ${S(f,t,n+1)}`}),l=`{ ${O.join("; ")} }`,d=e.additionalProperties;return d&&typeof d=="object"&&(l=`${l} & Record<string, ${S(d,t,n+1)}>`),i(O.length?l:"Record<string, unknown>")}let o=e.additionalProperties;return o&&typeof o=="object"?i(`Record<string, ${S(o,t,n+1)}>`):g==="object"?i("Record<string, unknown>"):"unknown"}}}function L(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function _(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}function j(e,t){if(e){if(e.$ref){let n=E(e.$ref);n&&t.add(n);return}j(e.items,t);for(let n of Object.values(e.properties??{}))j(n,t);e.additionalProperties&&typeof e.additionalProperties=="object"&&j(e.additionalProperties,t);for(let n of e.allOf??[])j(n,t);for(let n of e.oneOf??[])j(n,t);for(let n of e.anyOf??[])j(n,t)}}function re(e,t={}){let n=[],r=[],i=t.validator??"types-only",a=t.layout??"dir";i!=="types-only"&&n.push(`validator "${i}" is not implemented in v1; emitting types-only`),r.push("validator: types-only \u2014 runtime validation + drift are OFF. Re-run with --validator valibot|zod once those tiers ship.");let g=e.components?.schemas??{},o=e.components?.securitySchemes??{},h=e.servers?.[0]?.url;(e.servers?.length??0)>1&&n.push(`spec has ${e.servers?.length} servers; used the first (${h}). Edit client.ts to switch.`);let O=[],l=new Set;for(let[s,u]of Object.entries(e.paths??{})){if(typeof u!="object"||u===null)continue;let c=u;for(let p of J){let y=c[p];if(typeof y!="object"||y===null)continue;let w=y,$=Z(p.toUpperCase(),s,w);if(l.has($)){let v=2;for(;l.has(`${$}_${v}`);)v++;n.push(`name collision: "${$}" \u2192 "${$}_${v}" (rename it)`),$=`${$}_${v}`}l.add($);let R=w.tags?.[0];O.push({name:$,method:p.toUpperCase(),path:s,...R?{tag:R}:{},op:w})}}let d=O.filter(s=>W(s,t));if(d.length===0)return n.push("no operations selected \u2014 pass --all, --tag <t>, --only <id>, or --grep <substr>"),{files:[],manifest:ne(i,a),selected:[],warnings:n,notices:r};let b=new Map,f=s=>{let u=b.get(s);if(u)return u;let c=new Set;b.set(s,c);let p=new Set;j(g[s],p);for(let y of p){c.add(y);for(let w of f(y))c.add(w)}return c},m=new Map;for(let s of d){let u=new Set;for(let p of H(s.op))j(p,u);let c=new Set(u);for(let p of u)for(let y of f(p))c.add(y);m.set(s,c)}let A=new Map;for(let[s,u]of m)for(let c of u){let p=A.get(c);p||(p=[],A.set(c,p)),p.push(s)}let P=new Map;for(let[s,u]of A){if(!g[s]){n.push(`referenced component "${s}" not found in components.schemas`);continue}let c=u[0];P.set(s,u.length>=2||!c?{shared:!0}:{shared:!1,owner:c})}let N=[],B=te(e,o,n);N.push(Q(h,B));let T=s=>{let u=P.get(s),c=q(s);if(u?.shared)return{import:`_shared/${c}`,path:`_shared/${c}.ts`};let p=u?.owner;return p?a==="flat"?{import:`_OWN_${p.name}`,path:""}:{import:`${x(p)}/${c}`,path:`${x(p)}/${c}.ts`}:{import:`_shared/${c}`,path:`_shared/${c}.ts`}},I=[];for(let[s,u]of P){let c=g[s];if(!c)continue;let p={used:new Set,unresolved:new Set},y=S(c,p,0);p.used.delete(s);for(let k of p.unresolved)n.push(`unresolved $ref "${k}" in component ${s} \u2192 unknown`);let w=[...p.used],$=(A.get(s)??[]).map(k=>k.name),R=T(s),v=a==="flat"&&!u.shared&&!!u.owner;v||N.push({path:R.path,contents:Y(s,y,w,T,R.path)}),I.push({name:s,file:v&&u.owner?`${x(u.owner)}.ts (inlined)`:R.path,shared:u.shared,importers:$,refs:w})}for(let s of d)N.push(V(s,{layout:a,placement:P,components:g,fileOfComponent:T,warnings:n}));N.push(ee(d,a));let G={generator:"stitch gen openapi",validator:i,layout:a,operations:d.map(s=>({name:s.name,method:s.method,path:s.path,...s.tag?{tag:s.tag}:{},file:a==="flat"?`${q(s.name)}.ts`:`${x(s)}/index.ts`,uses:[...m.get(s)??[]]})),schemas:I};return N.push({path:".stitch-gen.json",contents:`${JSON.stringify(G,null,2)}
2
+ `}),{files:N,manifest:G,selected:d.map(s=>({name:s.name,method:s.method,path:s.path,...s.tag?{tag:s.tag}:{}})),warnings:n,notices:r}}function W(e,t){return t.all?!0:(t.tags?.length??0)>0||(t.only?.length??0)>0||(t.grep?.length??0)>0?!!(t.tags?.length&&e.tag&&t.tags.includes(e.tag)||t.only?.length&&(t.only.includes(e.name)||e.op.operationId&&t.only.includes(e.op.operationId))||t.grep&&e.path.includes(t.grep)):!1}function H(e){let t=[];for(let i of e.parameters??[])i.schema&&t.push(i.schema);let n=e.requestBody?.content?.["application/json"]?.schema;n&&t.push(n);let r=U(e);return r&&t.push(r),t}function U(e){let t=e.responses??{},n=["200","201","202","2XX","default"].find(r=>t[r])??Object.keys(t)[0];if(n)return t[n]?.content?.["application/json"]?.schema}function x(e){return q(e.name)}function z(e,t){let n=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",r=X(n,t);return r.startsWith(".")||(r=`./${r}`),r}function X(e,t){let n=e?e.split("/"):[],r=t.split("/"),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i++;let a=n.slice(i).map(()=>".."),g=r.slice(i);return[...a,...g].join("/")}function Y(e,t,n,r,i){let a=n.filter(o=>o!==e).map(o=>{let h=r(o),O=z(i,h.import);return`import type { ${C(o)} } from '${O}';`});return`${a.length?`${a.join(`
3
+ `)}
4
+
5
+ `:""}export type ${C(e)} = ${t};
6
+ `}function Q(e,t){let n=["seam",...t.imports],r=[];return r.push(`import { ${n.join(", ")} } from 'stitchapi';`),r.push(""),r.push("// Generated by `stitch gen openapi`. This file is yours to edit (eject model)."),r.push("export const client = seam({"),e?r.push(` baseUrl: ${_(e)},`):r.push(" // TODO: set baseUrl (no `servers` in the spec)"),t.expr&&r.push(` auth: ${t.expr},`),r.push(" // TODO: tune shared resilience, e.g."),r.push(" // retry: { attempts: 3, on: [429, 502, 503] },"),r.push(" // throttle: { rate: '10/s', scope: 'host' },"),r.push("});"),{path:"client.ts",contents:`${r.join(`
7
+ `)}
8
+ `}}function V(e,t){let n=t.layout==="flat"?`${q(e.name)}.ts`:`${x(e)}/index.ts`,r=U(e.op),i={used:new Set,unresolved:new Set},a=r?S(r,i):"unknown";for(let f of i.unresolved)t.warnings.push(`unresolved $ref "${f}" in ${e.name} response \u2192 unknown`);let g=new Map,o=[],h=f=>{let m=t.placement.get(f);if(t.layout==="flat"&&m&&!m.shared){K(f,t,o,new Set);return}let A=t.fileOfComponent(f);g.set(C(f),z(n,A.import))};for(let f of i.used)h(f);let O=t.layout==="flat"?"./client":"../client",l=[];l.push(`import { client } from '${O}';`);for(let[f,m]of g)l.push(`import type { ${f} } from '${m}';`);l.push(""),o.length&&(l.push("// --- types private to this operation (delete this file, they go too) ---"),l.push(...o),l.push("")),e.op.summary&&l.push(`// ${e.op.summary}`),l.push(`// ${e.method} ${e.path}`);let d=[];d.push(` path: ${_(e.path)},`),e.method!=="GET"&&d.push(` method: ${_(e.method)},`);let b=(e.op.parameters??[]).filter(f=>f.in==="query").map(f=>f.name);return b.length&&d.push(` // query params: ${b.join(", ")} \u2014 pass them in the call's \`query\``),e.op.requestBody?.content?.["application/json"]&&d.push(" bodyType: 'json',"),l.push(`export const ${e.name} = client.stitch<${a}>({`),l.push(...d),l.push("});"),{path:n,contents:`${l.join(`
9
+ `)}
10
+ `}}function K(e,t,n,r){if(r.has(e))return;r.add(e);let i=t.components[e];if(!i)return;let a={used:new Set,unresolved:new Set},g=S(i,a);n.push(`type ${C(e)} = ${g};`);for(let o of a.used){let h=t.placement.get(o);o!==e&&h&&!h.shared&&K(o,t,n,r)}}function ee(e,t){let n=["export { client } from './client';"];for(let r of e){let i=t==="flat"?`./${q(r.name)}`:`./${x(r)}`;n.push(`export { ${r.name} } from '${i}';`)}return{path:"index.ts",contents:`${n.join(`
11
+ `)}
12
+ `}}function te(e,t,n){let r=e.security?.[0],i=r?Object.keys(r)[0]:Object.keys(t)[0];if(!i)return{imports:[]};let a=t[i];if(!a)return{imports:[]};if(a.type==="http"&&a.scheme==="bearer")return{expr:"bearer(env('API_TOKEN'))",imports:["bearer","env"]};if(a.type==="http"&&a.scheme==="basic")return{expr:"basic({ user: env('API_USER'), pass: env('API_PASSWORD') })",imports:["basic","env"]};if(a.type==="apiKey"){let g=a.in==="query"?"in: 'query', ":"",o=a.name?`name: ${JSON.stringify(a.name)}, `:"";return{expr:`apiKey({ ${g}${o}value: env('API_KEY') })`,imports:["apiKey","env"]}}return n.push(`security scheme "${i}" (type ${a.type??"?"}) not auto-mapped \u2014 set client.ts auth manually`),{imports:[]}}function ne(e,t){return{generator:"stitch gen openapi",validator:e,layout:t,operations:[],schemas:[]}}export{re as a};
package/lib/cli.d.mts ADDED
@@ -0,0 +1,10 @@
1
+ interface Io {
2
+ cwd: string;
3
+ write: (s: string) => void;
4
+ writeErr: (s: string) => void;
5
+ readFileText: (path: string) => Promise<string>;
6
+ writeFile: (path: string, contents: string) => Promise<void>;
7
+ }
8
+ declare function main(argv: string[], overrides?: Partial<Io>): Promise<number>;
9
+
10
+ export { main };
package/lib/cli.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ interface Io {
2
+ cwd: string;
3
+ write: (s: string) => void;
4
+ writeErr: (s: string) => void;
5
+ readFileText: (path: string) => Promise<string>;
6
+ writeFile: (path: string, contents: string) => Promise<void>;
7
+ }
8
+ declare function main(argv: string[], overrides?: Partial<Io>): Promise<number>;
9
+
10
+ export { main };
package/lib/cli.js ADDED
@@ -0,0 +1,45 @@
1
+ "use strict";var X=Object.create;var q=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var V=Object.getPrototypeOf,ee=Object.prototype.hasOwnProperty;var te=(e,t)=>{for(var n in t)q(e,n,{get:t[n],enumerable:!0})},M=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Q(t))!ee.call(e,s)&&s!==n&&q(e,s,{get:()=>t[s],enumerable:!(r=Y(t,s))||r.enumerable});return e};var ne=(e,t,n)=>(n=e!=null?X(V(e)):{},M(t||!e||!e.__esModule?q(n,"default",{value:e,enumerable:!0}):n,e)),re=e=>M(q({},"__esModule",{value:!0}),e);var we={};te(we,{main:()=>$e});module.exports=re(we);var se=["get","put","post","delete","patch","options","head","trace"];function z(e){return e.replace(/[{}]/g," ").replace(/[^A-Za-z0-9]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").trim().split(/\s+/).filter(Boolean)}function J(e){let t=z(e);return t.length===0?"op":t.map((n,r)=>r===0?n.toLowerCase():n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join("")}function E(e){let t=J(e);return t.charAt(0).toUpperCase()+t.slice(1)}function I(e){let t=z(e);return t.length?t.map(n=>n.toLowerCase()).join("-"):"item"}function U(e){let t=J(e);return/^[A-Za-z_$]/.test(t)?t:`op${E(t)}`}function ie(e,t,n){return n.operationId?.trim()?U(n.operationId):U(`${e} ${t}`)}function K(e){let t=/^#\/components\/schemas\/([^/]+)$/.exec(e);return t?t[1]:null}function S(e,t,n=0){if(!e||n>30)return"unknown";if(e.$ref){let a=K(e.$ref);return a===null?(t.unresolved.add(e.$ref),"unknown"):(t.used.add(a),E(a))}let r=e.nullable===!0,s=a=>r?`${a} | null`:a;if(Array.isArray(e.enum)&&e.enum.length>0)return s(e.enum.map(a=>JSON.stringify(a)).join(" | "));if(e.const!==void 0)return s(JSON.stringify(e.const));if(Array.isArray(e.allOf)&&e.allOf.length)return s(e.allOf.map(a=>`(${S(a,t,n+1)})`).join(" & "));let c=e.oneOf??e.anyOf;if(Array.isArray(c)&&c.length)return s(c.map(a=>`(${S(a,t,n+1)})`).join(" | "));let p=Array.isArray(e.type)?e.type[0]:e.type;switch(p){case"string":return s("string");case"integer":case"number":return s("number");case"boolean":return s("boolean");case"null":return"null";case"array":return s(`Array<${S(e.items,t,n+1)}>`);default:{if(e.properties){let y=new Set(e.required??[]),$=Object.entries(e.properties).map(([w,i])=>{let g=y.has(w)?"":"?";return`${oe(w)}${g}: ${S(i,t,n+1)}`}),d=`{ ${$.join("; ")} }`,l=e.additionalProperties;return l&&typeof l=="object"&&(d=`${d} & Record<string, ${S(l,t,n+1)}>`),s($.length?d:"Record<string, unknown>")}let a=e.additionalProperties;return a&&typeof a=="object"?s(`Record<string, ${S(a,t,n+1)}>`):p==="object"?s("Record<string, unknown>"):"unknown"}}}function oe(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function G(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}function j(e,t){if(e){if(e.$ref){let n=K(e.$ref);n&&t.add(n);return}j(e.items,t);for(let n of Object.values(e.properties??{}))j(n,t);e.additionalProperties&&typeof e.additionalProperties=="object"&&j(e.additionalProperties,t);for(let n of e.allOf??[])j(n,t);for(let n of e.oneOf??[])j(n,t);for(let n of e.anyOf??[])j(n,t)}}function B(e,t={}){let n=[],r=[],s=t.validator??"types-only",c=t.layout??"dir";s!=="types-only"&&n.push(`validator "${s}" is not implemented in v1; emitting types-only`),r.push("validator: types-only \u2014 runtime validation + drift are OFF. Re-run with --validator valibot|zod once those tiers ship.");let p=e.components?.schemas??{},a=e.components?.securitySchemes??{},y=e.servers?.[0]?.url;(e.servers?.length??0)>1&&n.push(`spec has ${e.servers?.length} servers; used the first (${y}). Edit client.ts to switch.`);let $=[],d=new Set;for(let[o,h]of Object.entries(e.paths??{})){if(typeof h!="object"||h===null)continue;let u=h;for(let f of se){let O=u[f];if(typeof O!="object"||O===null)continue;let v=O,b=ie(f.toUpperCase(),o,v);if(d.has(b)){let A=2;for(;d.has(`${b}_${A}`);)A++;n.push(`name collision: "${b}" \u2192 "${b}_${A}" (rename it)`),b=`${b}_${A}`}d.add(b);let R=v.tags?.[0];$.push({name:b,method:f.toUpperCase(),path:o,...R?{tag:R}:{},op:v})}}let l=$.filter(o=>ae(o,t));if(l.length===0)return n.push("no operations selected \u2014 pass --all, --tag <t>, --only <id>, or --grep <substr>"),{files:[],manifest:he(s,c),selected:[],warnings:n,notices:r};let w=new Map,i=o=>{let h=w.get(o);if(h)return h;let u=new Set;w.set(o,u);let f=new Set;j(p[o],f);for(let O of f){u.add(O);for(let v of i(O))u.add(v)}return u},g=new Map;for(let o of l){let h=new Set;for(let f of ce(o.op))j(f,h);let u=new Set(h);for(let f of h)for(let O of i(f))u.add(O);g.set(o,u)}let m=new Map;for(let[o,h]of g)for(let u of h){let f=m.get(u);f||(f=[],m.set(u,f)),f.push(o)}let T=new Map;for(let[o,h]of m){if(!p[o]){n.push(`referenced component "${o}" not found in components.schemas`);continue}let u=h[0];T.set(o,h.length>=2||!u?{shared:!0}:{shared:!1,owner:u})}let N=[],H=ge(e,a,n);N.push(ue(y,H));let C=o=>{let h=T.get(o),u=I(o);if(h?.shared)return{import:`_shared/${u}`,path:`_shared/${u}.ts`};let f=h?.owner;return f?c==="flat"?{import:`_OWN_${f.name}`,path:""}:{import:`${x(f)}/${u}`,path:`${x(f)}/${u}.ts`}:{import:`_shared/${u}`,path:`_shared/${u}.ts`}},_=[];for(let[o,h]of T){let u=p[o];if(!u)continue;let f={used:new Set,unresolved:new Set},O=S(u,f,0);f.used.delete(o);for(let F of f.unresolved)n.push(`unresolved $ref "${F}" in component ${o} \u2192 unknown`);let v=[...f.used],b=(m.get(o)??[]).map(F=>F.name),R=C(o),A=c==="flat"&&!h.shared&&!!h.owner;A||N.push({path:R.path,contents:le(o,O,v,C,R.path)}),_.push({name:o,file:A&&h.owner?`${x(h.owner)}.ts (inlined)`:R.path,shared:h.shared,importers:b,refs:v})}for(let o of l)N.push(fe(o,{layout:c,placement:T,components:p,fileOfComponent:C,warnings:n}));N.push(de(l,c));let D={generator:"stitch gen openapi",validator:s,layout:c,operations:l.map(o=>({name:o.name,method:o.method,path:o.path,...o.tag?{tag:o.tag}:{},file:c==="flat"?`${I(o.name)}.ts`:`${x(o)}/index.ts`,uses:[...g.get(o)??[]]})),schemas:_};return N.push({path:".stitch-gen.json",contents:`${JSON.stringify(D,null,2)}
2
+ `}),{files:N,manifest:D,selected:l.map(o=>({name:o.name,method:o.method,path:o.path,...o.tag?{tag:o.tag}:{}})),warnings:n,notices:r}}function ae(e,t){return t.all?!0:(t.tags?.length??0)>0||(t.only?.length??0)>0||(t.grep?.length??0)>0?!!(t.tags?.length&&e.tag&&t.tags.includes(e.tag)||t.only?.length&&(t.only.includes(e.name)||e.op.operationId&&t.only.includes(e.op.operationId))||t.grep&&e.path.includes(t.grep)):!1}function ce(e){let t=[];for(let s of e.parameters??[])s.schema&&t.push(s.schema);let n=e.requestBody?.content?.["application/json"]?.schema;n&&t.push(n);let r=Z(e);return r&&t.push(r),t}function Z(e){let t=e.responses??{},n=["200","201","202","2XX","default"].find(r=>t[r])??Object.keys(t)[0];if(n)return t[n]?.content?.["application/json"]?.schema}function x(e){return I(e.name)}function L(e,t){let n=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",r=pe(n,t);return r.startsWith(".")||(r=`./${r}`),r}function pe(e,t){let n=e?e.split("/"):[],r=t.split("/"),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let c=n.slice(s).map(()=>".."),p=r.slice(s);return[...c,...p].join("/")}function le(e,t,n,r,s){let c=n.filter(a=>a!==e).map(a=>{let y=r(a),$=L(s,y.import);return`import type { ${E(a)} } from '${$}';`});return`${c.length?`${c.join(`
3
+ `)}
4
+
5
+ `:""}export type ${E(e)} = ${t};
6
+ `}function ue(e,t){let n=["seam",...t.imports],r=[];return r.push(`import { ${n.join(", ")} } from 'stitchapi';`),r.push(""),r.push("// Generated by `stitch gen openapi`. This file is yours to edit (eject model)."),r.push("export const client = seam({"),e?r.push(` baseUrl: ${G(e)},`):r.push(" // TODO: set baseUrl (no `servers` in the spec)"),t.expr&&r.push(` auth: ${t.expr},`),r.push(" // TODO: tune shared resilience, e.g."),r.push(" // retry: { attempts: 3, on: [429, 502, 503] },"),r.push(" // throttle: { rate: '10/s', scope: 'host' },"),r.push("});"),{path:"client.ts",contents:`${r.join(`
7
+ `)}
8
+ `}}function fe(e,t){let n=t.layout==="flat"?`${I(e.name)}.ts`:`${x(e)}/index.ts`,r=Z(e.op),s={used:new Set,unresolved:new Set},c=r?S(r,s):"unknown";for(let i of s.unresolved)t.warnings.push(`unresolved $ref "${i}" in ${e.name} response \u2192 unknown`);let p=new Map,a=[],y=i=>{let g=t.placement.get(i);if(t.layout==="flat"&&g&&!g.shared){W(i,t,a,new Set);return}let m=t.fileOfComponent(i);p.set(E(i),L(n,m.import))};for(let i of s.used)y(i);let $=t.layout==="flat"?"./client":"../client",d=[];d.push(`import { client } from '${$}';`);for(let[i,g]of p)d.push(`import type { ${i} } from '${g}';`);d.push(""),a.length&&(d.push("// --- types private to this operation (delete this file, they go too) ---"),d.push(...a),d.push("")),e.op.summary&&d.push(`// ${e.op.summary}`),d.push(`// ${e.method} ${e.path}`);let l=[];l.push(` path: ${G(e.path)},`),e.method!=="GET"&&l.push(` method: ${G(e.method)},`);let w=(e.op.parameters??[]).filter(i=>i.in==="query").map(i=>i.name);return w.length&&l.push(` // query params: ${w.join(", ")} \u2014 pass them in the call's \`query\``),e.op.requestBody?.content?.["application/json"]&&l.push(" bodyType: 'json',"),d.push(`export const ${e.name} = client.stitch<${c}>({`),d.push(...l),d.push("});"),{path:n,contents:`${d.join(`
9
+ `)}
10
+ `}}function W(e,t,n,r){if(r.has(e))return;r.add(e);let s=t.components[e];if(!s)return;let c={used:new Set,unresolved:new Set},p=S(s,c);n.push(`type ${E(e)} = ${p};`);for(let a of c.used){let y=t.placement.get(a);a!==e&&y&&!y.shared&&W(a,t,n,r)}}function de(e,t){let n=["export { client } from './client';"];for(let r of e){let s=t==="flat"?`./${I(r.name)}`:`./${x(r)}`;n.push(`export { ${r.name} } from '${s}';`)}return{path:"index.ts",contents:`${n.join(`
11
+ `)}
12
+ `}}function ge(e,t,n){let r=e.security?.[0],s=r?Object.keys(r)[0]:Object.keys(t)[0];if(!s)return{imports:[]};let c=t[s];if(!c)return{imports:[]};if(c.type==="http"&&c.scheme==="bearer")return{expr:"bearer(env('API_TOKEN'))",imports:["bearer","env"]};if(c.type==="http"&&c.scheme==="basic")return{expr:"basic({ user: env('API_USER'), pass: env('API_PASSWORD') })",imports:["basic","env"]};if(c.type==="apiKey"){let p=c.in==="query"?"in: 'query', ":"",a=c.name?`name: ${JSON.stringify(c.name)}, `:"";return{expr:`apiKey({ ${p}${a}value: env('API_KEY') })`,imports:["apiKey","env"]}}return n.push(`security scheme "${s}" (type ${c.type??"?"}) not auto-mapped \u2014 set client.ts auth manually`),{imports:[]}}function he(e,t){return{generator:"stitch gen openapi",validator:e,layout:t,operations:[],schemas:[]}}var P=require("fs/promises"),k=require("path"),me=`stitch-openapi \u2014 eject selected operations from an OpenAPI document into stitch source
13
+
14
+ usage:
15
+ stitch-openapi <spec> --out <dir> [--all | --tag <t> | --only <id> | --grep <s>]
16
+ [--layout dir|flat] [--validator types-only] [--dry-run]
17
+
18
+ <spec> an OpenAPI 3.x document (JSON or YAML)
19
+ --out, -o <dir> output directory (required unless --dry-run)
20
+ --all generate every operation (otherwise pass a selector)
21
+ --tag <t> only operations with this tag (repeatable)
22
+ --only <id> only this operationId / export name (repeatable)
23
+ --grep <substr> only operations whose path contains this substring
24
+ --layout dir|flat dir = one folder per operation (default); flat = one file per operation
25
+ --validator <t> types-only (default; v1). valibot/zod tiers are not implemented yet
26
+ --dry-run print the files to stdout instead of writing them
27
+
28
+ Ejects ready-to-own source you edit afterward: a client.ts seam, one stitch per operation typed
29
+ via stitch<T>(), atomic component types placed by fan-in (used by >=2 ops -> _shared/, by one ->
30
+ private to it), an index.ts, and a .stitch-gen.json ownership manifest. types-only emits no runtime
31
+ validation (a notice says so). Auth maps securitySchemes -> bearer/apiKey/basic with env()
32
+ placeholders; the secret is never emitted.
33
+ `;function ye(){return{cwd:process.cwd(),write:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e),readFileText:e=>(0,P.readFile)(e,"utf8"),writeFile:async(e,t)=>{await(0,P.mkdir)((0,k.dirname)(e),{recursive:!0}),await(0,P.writeFile)(e,t,"utf8")}}}async function $e(e,t={}){let n={...ye(),...t};if(e.length===0||e[0]==="-h"||e[0]==="--help")return n.write(me),e.length===0?2:0;let r,s,c=!1,p={},a=[],y=[];for(let i=0;i<e.length;i++){let g=e[i];if(g!==void 0)if(g==="--out"||g==="-o")s=e[++i];else if(g==="--all")p.all=!0;else if(g==="--tag"){let m=e[++i];m&&a.push(m)}else if(g==="--only"){let m=e[++i];m&&y.push(m)}else if(g==="--grep"){let m=e[++i];m&&(p.grep=m)}else if(g==="--validator"){let m=e[++i];m&&(p.validator=m)}else if(g==="--layout"){let m=e[++i];m&&(p.layout=m)}else g==="--dry-run"?c=!0:!g.startsWith("-")&&r===void 0?r=g:n.writeErr(`warning: ignored unknown arg: ${g}
34
+ `)}if(a.length&&(p.tags=a),y.length&&(p.only=y),r===void 0)return n.writeErr(`missing <spec> file
35
+ `),2;if(s===void 0&&!c)return n.writeErr(`--out <dir> is required (or use --dry-run)
36
+ `),2;let $;try{$=await n.readFileText(r)}catch(i){return n.writeErr(`could not read ${r}: ${i.message}
37
+ `),1}let d;try{if(/\.ya?ml$/i.test(r)){let{parse:i}=await import("yaml");d=i($)}else d=JSON.parse($)}catch(i){return n.writeErr(`could not parse ${r}: ${i.message}
38
+ `),1}let l=B(d,p);for(let i of l.notices)n.writeErr(`note: ${i}
39
+ `);for(let i of l.warnings)n.writeErr(`warning: ${i}
40
+ `);if(l.selected.length===0)return 1;n.writeErr(`selected ${l.selected.length} operation(s):
41
+ `);for(let i of l.selected)n.writeErr(` ${i.method} ${i.path} -> ${i.name}
42
+ `);if(c){for(let i of l.files)n.write(`
43
+ // ===== ${i.path} =====
44
+ `),n.write(i.contents);return 0}let w=s;for(let i of l.files)await n.writeFile((0,k.resolve)(n.cwd,w,i.path),i.contents);return n.writeErr(`wrote ${l.files.length} file(s) to ${w}
45
+ `),0}0&&(module.exports={main});
package/lib/cli.mjs ADDED
@@ -0,0 +1,34 @@
1
+ import{a as h}from"./chunk-4RAYEZG5.mjs";import{mkdir as m,readFile as g,writeFile as E}from"fs/promises";import{dirname as $,resolve as b}from"path";var v=`stitch-openapi \u2014 eject selected operations from an OpenAPI document into stitch source
2
+
3
+ usage:
4
+ stitch-openapi <spec> --out <dir> [--all | --tag <t> | --only <id> | --grep <s>]
5
+ [--layout dir|flat] [--validator types-only] [--dry-run]
6
+
7
+ <spec> an OpenAPI 3.x document (JSON or YAML)
8
+ --out, -o <dir> output directory (required unless --dry-run)
9
+ --all generate every operation (otherwise pass a selector)
10
+ --tag <t> only operations with this tag (repeatable)
11
+ --only <id> only this operationId / export name (repeatable)
12
+ --grep <substr> only operations whose path contains this substring
13
+ --layout dir|flat dir = one folder per operation (default); flat = one file per operation
14
+ --validator <t> types-only (default; v1). valibot/zod tiers are not implemented yet
15
+ --dry-run print the files to stdout instead of writing them
16
+
17
+ Ejects ready-to-own source you edit afterward: a client.ts seam, one stitch per operation typed
18
+ via stitch<T>(), atomic component types placed by fan-in (used by >=2 ops -> _shared/, by one ->
19
+ private to it), an index.ts, and a .stitch-gen.json ownership manifest. types-only emits no runtime
20
+ validation (a notice says so). Auth maps securitySchemes -> bearer/apiKey/basic with env()
21
+ placeholders; the secret is never emitted.
22
+ `;function O(){return{cwd:process.cwd(),write:t=>process.stdout.write(t),writeErr:t=>process.stderr.write(t),readFileText:t=>g(t,"utf8"),writeFile:async(t,l)=>{await m($(t),{recursive:!0}),await E(t,l,"utf8")}}}async function x(t,l={}){let r={...O(),...l};if(t.length===0||t[0]==="-h"||t[0]==="--help")return r.write(v),t.length===0?2:0;let s,d,c=!1,a={},p=[],u=[];for(let e=0;e<t.length;e++){let n=t[e];if(n!==void 0)if(n==="--out"||n==="-o")d=t[++e];else if(n==="--all")a.all=!0;else if(n==="--tag"){let i=t[++e];i&&p.push(i)}else if(n==="--only"){let i=t[++e];i&&u.push(i)}else if(n==="--grep"){let i=t[++e];i&&(a.grep=i)}else if(n==="--validator"){let i=t[++e];i&&(a.validator=i)}else if(n==="--layout"){let i=t[++e];i&&(a.layout=i)}else n==="--dry-run"?c=!0:!n.startsWith("-")&&s===void 0?s=n:r.writeErr(`warning: ignored unknown arg: ${n}
23
+ `)}if(p.length&&(a.tags=p),u.length&&(a.only=u),s===void 0)return r.writeErr(`missing <spec> file
24
+ `),2;if(d===void 0&&!c)return r.writeErr(`--out <dir> is required (or use --dry-run)
25
+ `),2;let f;try{f=await r.readFileText(s)}catch(e){return r.writeErr(`could not read ${s}: ${e.message}
26
+ `),1}let w;try{if(/\.ya?ml$/i.test(s)){let{parse:e}=await import("yaml");w=e(f)}else w=JSON.parse(f)}catch(e){return r.writeErr(`could not parse ${s}: ${e.message}
27
+ `),1}let o=h(w,a);for(let e of o.notices)r.writeErr(`note: ${e}
28
+ `);for(let e of o.warnings)r.writeErr(`warning: ${e}
29
+ `);if(o.selected.length===0)return 1;r.writeErr(`selected ${o.selected.length} operation(s):
30
+ `);for(let e of o.selected)r.writeErr(` ${e.method} ${e.path} -> ${e.name}
31
+ `);if(c){for(let e of o.files)r.write(`
32
+ // ===== ${e.path} =====
33
+ `),r.write(e.contents);return 0}let y=d;for(let e of o.files)await r.writeFile(b(r.cwd,y,e.path),e.contents);return r.writeErr(`wrote ${o.files.length} file(s) to ${y}
34
+ `),0}export{x as main};
@@ -0,0 +1,71 @@
1
+ /** A JSON-Schema-ish node as it appears in an OpenAPI document. Intentionally loose. */
2
+ interface SchemaNode {
3
+ $ref?: string;
4
+ type?: string | string[];
5
+ format?: string;
6
+ enum?: unknown[];
7
+ const?: unknown;
8
+ items?: SchemaNode;
9
+ properties?: Record<string, SchemaNode>;
10
+ required?: string[];
11
+ additionalProperties?: boolean | SchemaNode;
12
+ allOf?: SchemaNode[];
13
+ oneOf?: SchemaNode[];
14
+ anyOf?: SchemaNode[];
15
+ nullable?: boolean;
16
+ description?: string;
17
+ }
18
+ interface SecuritySchemeObject {
19
+ type?: string;
20
+ scheme?: string;
21
+ in?: string;
22
+ name?: string;
23
+ }
24
+ interface OpenApiDoc {
25
+ openapi?: string;
26
+ info?: {
27
+ title?: string;
28
+ version?: string;
29
+ };
30
+ servers?: {
31
+ url?: string;
32
+ }[];
33
+ paths?: Record<string, unknown>;
34
+ components?: {
35
+ schemas?: Record<string, SchemaNode>;
36
+ securitySchemes?: Record<string, SecuritySchemeObject>;
37
+ };
38
+ security?: Record<string, unknown>[];
39
+ }
40
+ interface GenOptions {
41
+ /** ADR 0013 Q2: default `types-only` (no runtime validation; loud notice). */
42
+ validator?: 'types-only' | 'valibot' | 'zod';
43
+ /** ADR 0013 Q3: default `dir`. `single` is not implemented in v1. */
44
+ layout?: 'dir' | 'flat';
45
+ /** Filters (ADR 0013 Decision 2). `all` overrides the others. */
46
+ only?: string[];
47
+ tags?: string[];
48
+ grep?: string;
49
+ all?: boolean;
50
+ }
51
+ interface GenFile {
52
+ /** Path relative to the output directory. */
53
+ path: string;
54
+ contents: string;
55
+ }
56
+ interface GenResult {
57
+ files: GenFile[];
58
+ /** `.stitch-gen.json` payload (ADR 0013 Decision 9). */
59
+ manifest: unknown;
60
+ selected: {
61
+ name: string;
62
+ method: string;
63
+ path: string;
64
+ tag?: string;
65
+ }[];
66
+ warnings: string[];
67
+ notices: string[];
68
+ }
69
+ declare function planGen(doc: OpenApiDoc, opts?: GenOptions): GenResult;
70
+
71
+ export { type GenFile, type GenOptions, type GenResult, type OpenApiDoc, type SchemaNode, planGen };
package/lib/index.d.ts ADDED
@@ -0,0 +1,71 @@
1
+ /** A JSON-Schema-ish node as it appears in an OpenAPI document. Intentionally loose. */
2
+ interface SchemaNode {
3
+ $ref?: string;
4
+ type?: string | string[];
5
+ format?: string;
6
+ enum?: unknown[];
7
+ const?: unknown;
8
+ items?: SchemaNode;
9
+ properties?: Record<string, SchemaNode>;
10
+ required?: string[];
11
+ additionalProperties?: boolean | SchemaNode;
12
+ allOf?: SchemaNode[];
13
+ oneOf?: SchemaNode[];
14
+ anyOf?: SchemaNode[];
15
+ nullable?: boolean;
16
+ description?: string;
17
+ }
18
+ interface SecuritySchemeObject {
19
+ type?: string;
20
+ scheme?: string;
21
+ in?: string;
22
+ name?: string;
23
+ }
24
+ interface OpenApiDoc {
25
+ openapi?: string;
26
+ info?: {
27
+ title?: string;
28
+ version?: string;
29
+ };
30
+ servers?: {
31
+ url?: string;
32
+ }[];
33
+ paths?: Record<string, unknown>;
34
+ components?: {
35
+ schemas?: Record<string, SchemaNode>;
36
+ securitySchemes?: Record<string, SecuritySchemeObject>;
37
+ };
38
+ security?: Record<string, unknown>[];
39
+ }
40
+ interface GenOptions {
41
+ /** ADR 0013 Q2: default `types-only` (no runtime validation; loud notice). */
42
+ validator?: 'types-only' | 'valibot' | 'zod';
43
+ /** ADR 0013 Q3: default `dir`. `single` is not implemented in v1. */
44
+ layout?: 'dir' | 'flat';
45
+ /** Filters (ADR 0013 Decision 2). `all` overrides the others. */
46
+ only?: string[];
47
+ tags?: string[];
48
+ grep?: string;
49
+ all?: boolean;
50
+ }
51
+ interface GenFile {
52
+ /** Path relative to the output directory. */
53
+ path: string;
54
+ contents: string;
55
+ }
56
+ interface GenResult {
57
+ files: GenFile[];
58
+ /** `.stitch-gen.json` payload (ADR 0013 Decision 9). */
59
+ manifest: unknown;
60
+ selected: {
61
+ name: string;
62
+ method: string;
63
+ path: string;
64
+ tag?: string;
65
+ }[];
66
+ warnings: string[];
67
+ notices: string[];
68
+ }
69
+ declare function planGen(doc: OpenApiDoc, opts?: GenOptions): GenResult;
70
+
71
+ export { type GenFile, type GenOptions, type GenResult, type OpenApiDoc, type SchemaNode, planGen };
package/lib/index.js ADDED
@@ -0,0 +1,12 @@
1
+ "use strict";var G=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var X=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})},Y=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of W(t))!H.call(e,s)&&s!==n&&G(e,s,{get:()=>t[s],enumerable:!(r=L(t,s))||r.enumerable});return e};var Q=e=>Y(G({},"__esModule",{value:!0}),e);var le={};X(le,{planGen:()=>z});module.exports=Q(le);var V=["get","put","post","delete","patch","options","head","trace"];function D(e){return e.replace(/[{}]/g," ").replace(/[^A-Za-z0-9]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").trim().split(/\s+/).filter(Boolean)}function E(e){let t=D(e);return t.length===0?"op":t.map((n,r)=>r===0?n.toLowerCase():n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join("")}function C(e){let t=E(e);return t.charAt(0).toUpperCase()+t.slice(1)}function q(e){let t=D(e);return t.length?t.map(n=>n.toLowerCase()).join("-"):"item"}function M(e){let t=E(e);return/^[A-Za-z_$]/.test(t)?t:`op${C(t)}`}function ee(e,t,n){return n.operationId?.trim()?M(n.operationId):M(`${e} ${t}`)}function U(e){let t=/^#\/components\/schemas\/([^/]+)$/.exec(e);return t?t[1]:null}function S(e,t,n=0){if(!e||n>30)return"unknown";if(e.$ref){let o=U(e.$ref);return o===null?(t.unresolved.add(e.$ref),"unknown"):(t.used.add(o),C(o))}let r=e.nullable===!0,s=o=>r?`${o} | null`:o;if(Array.isArray(e.enum)&&e.enum.length>0)return s(e.enum.map(o=>JSON.stringify(o)).join(" | "));if(e.const!==void 0)return s(JSON.stringify(e.const));if(Array.isArray(e.allOf)&&e.allOf.length)return s(e.allOf.map(o=>`(${S(o,t,n+1)})`).join(" & "));let a=e.oneOf??e.anyOf;if(Array.isArray(a)&&a.length)return s(a.map(o=>`(${S(o,t,n+1)})`).join(" | "));let g=Array.isArray(e.type)?e.type[0]:e.type;switch(g){case"string":return s("string");case"integer":case"number":return s("number");case"boolean":return s("boolean");case"null":return"null";case"array":return s(`Array<${S(e.items,t,n+1)}>`);default:{if(e.properties){let h=new Set(e.required??[]),O=Object.entries(e.properties).map(([b,f])=>{let m=h.has(b)?"":"?";return`${te(b)}${m}: ${S(f,t,n+1)}`}),l=`{ ${O.join("; ")} }`,d=e.additionalProperties;return d&&typeof d=="object"&&(l=`${l} & Record<string, ${S(d,t,n+1)}>`),s(O.length?l:"Record<string, unknown>")}let o=e.additionalProperties;return o&&typeof o=="object"?s(`Record<string, ${S(o,t,n+1)}>`):g==="object"?s("Record<string, unknown>"):"unknown"}}}function te(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function _(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}function j(e,t){if(e){if(e.$ref){let n=U(e.$ref);n&&t.add(n);return}j(e.items,t);for(let n of Object.values(e.properties??{}))j(n,t);e.additionalProperties&&typeof e.additionalProperties=="object"&&j(e.additionalProperties,t);for(let n of e.allOf??[])j(n,t);for(let n of e.oneOf??[])j(n,t);for(let n of e.anyOf??[])j(n,t)}}function z(e,t={}){let n=[],r=[],s=t.validator??"types-only",a=t.layout??"dir";s!=="types-only"&&n.push(`validator "${s}" is not implemented in v1; emitting types-only`),r.push("validator: types-only \u2014 runtime validation + drift are OFF. Re-run with --validator valibot|zod once those tiers ship.");let g=e.components?.schemas??{},o=e.components?.securitySchemes??{},h=e.servers?.[0]?.url;(e.servers?.length??0)>1&&n.push(`spec has ${e.servers?.length} servers; used the first (${h}). Edit client.ts to switch.`);let O=[],l=new Set;for(let[i,u]of Object.entries(e.paths??{})){if(typeof u!="object"||u===null)continue;let p=u;for(let c of V){let y=p[c];if(typeof y!="object"||y===null)continue;let w=y,$=ee(c.toUpperCase(),i,w);if(l.has($)){let v=2;for(;l.has(`${$}_${v}`);)v++;n.push(`name collision: "${$}" \u2192 "${$}_${v}" (rename it)`),$=`${$}_${v}`}l.add($);let R=w.tags?.[0];O.push({name:$,method:c.toUpperCase(),path:i,...R?{tag:R}:{},op:w})}}let d=O.filter(i=>ne(i,t));if(d.length===0)return n.push("no operations selected \u2014 pass --all, --tag <t>, --only <id>, or --grep <substr>"),{files:[],manifest:ue(s,a),selected:[],warnings:n,notices:r};let b=new Map,f=i=>{let u=b.get(i);if(u)return u;let p=new Set;b.set(i,p);let c=new Set;j(g[i],c);for(let y of c){p.add(y);for(let w of f(y))p.add(w)}return p},m=new Map;for(let i of d){let u=new Set;for(let c of re(i.op))j(c,u);let p=new Set(u);for(let c of u)for(let y of f(c))p.add(y);m.set(i,p)}let A=new Map;for(let[i,u]of m)for(let p of u){let c=A.get(p);c||(c=[],A.set(p,c)),c.push(i)}let P=new Map;for(let[i,u]of A){if(!g[i]){n.push(`referenced component "${i}" not found in components.schemas`);continue}let p=u[0];P.set(i,u.length>=2||!p?{shared:!0}:{shared:!1,owner:p})}let N=[],Z=ce(e,o,n);N.push(oe(h,Z));let T=i=>{let u=P.get(i),p=q(i);if(u?.shared)return{import:`_shared/${p}`,path:`_shared/${p}.ts`};let c=u?.owner;return c?a==="flat"?{import:`_OWN_${c.name}`,path:""}:{import:`${x(c)}/${p}`,path:`${x(c)}/${p}.ts`}:{import:`_shared/${p}`,path:`_shared/${p}.ts`}},I=[];for(let[i,u]of P){let p=g[i];if(!p)continue;let c={used:new Set,unresolved:new Set},y=S(p,c,0);c.used.delete(i);for(let k of c.unresolved)n.push(`unresolved $ref "${k}" in component ${i} \u2192 unknown`);let w=[...c.used],$=(A.get(i)??[]).map(k=>k.name),R=T(i),v=a==="flat"&&!u.shared&&!!u.owner;v||N.push({path:R.path,contents:ie(i,y,w,T,R.path)}),I.push({name:i,file:v&&u.owner?`${x(u.owner)}.ts (inlined)`:R.path,shared:u.shared,importers:$,refs:w})}for(let i of d)N.push(ae(i,{layout:a,placement:P,components:g,fileOfComponent:T,warnings:n}));N.push(pe(d,a));let F={generator:"stitch gen openapi",validator:s,layout:a,operations:d.map(i=>({name:i.name,method:i.method,path:i.path,...i.tag?{tag:i.tag}:{},file:a==="flat"?`${q(i.name)}.ts`:`${x(i)}/index.ts`,uses:[...m.get(i)??[]]})),schemas:I};return N.push({path:".stitch-gen.json",contents:`${JSON.stringify(F,null,2)}
2
+ `}),{files:N,manifest:F,selected:d.map(i=>({name:i.name,method:i.method,path:i.path,...i.tag?{tag:i.tag}:{}})),warnings:n,notices:r}}function ne(e,t){return t.all?!0:(t.tags?.length??0)>0||(t.only?.length??0)>0||(t.grep?.length??0)>0?!!(t.tags?.length&&e.tag&&t.tags.includes(e.tag)||t.only?.length&&(t.only.includes(e.name)||e.op.operationId&&t.only.includes(e.op.operationId))||t.grep&&e.path.includes(t.grep)):!1}function re(e){let t=[];for(let s of e.parameters??[])s.schema&&t.push(s.schema);let n=e.requestBody?.content?.["application/json"]?.schema;n&&t.push(n);let r=K(e);return r&&t.push(r),t}function K(e){let t=e.responses??{},n=["200","201","202","2XX","default"].find(r=>t[r])??Object.keys(t)[0];if(n)return t[n]?.content?.["application/json"]?.schema}function x(e){return q(e.name)}function B(e,t){let n=e.includes("/")?e.slice(0,e.lastIndexOf("/")):"",r=se(n,t);return r.startsWith(".")||(r=`./${r}`),r}function se(e,t){let n=e?e.split("/"):[],r=t.split("/"),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let a=n.slice(s).map(()=>".."),g=r.slice(s);return[...a,...g].join("/")}function ie(e,t,n,r,s){let a=n.filter(o=>o!==e).map(o=>{let h=r(o),O=B(s,h.import);return`import type { ${C(o)} } from '${O}';`});return`${a.length?`${a.join(`
3
+ `)}
4
+
5
+ `:""}export type ${C(e)} = ${t};
6
+ `}function oe(e,t){let n=["seam",...t.imports],r=[];return r.push(`import { ${n.join(", ")} } from 'stitchapi';`),r.push(""),r.push("// Generated by `stitch gen openapi`. This file is yours to edit (eject model)."),r.push("export const client = seam({"),e?r.push(` baseUrl: ${_(e)},`):r.push(" // TODO: set baseUrl (no `servers` in the spec)"),t.expr&&r.push(` auth: ${t.expr},`),r.push(" // TODO: tune shared resilience, e.g."),r.push(" // retry: { attempts: 3, on: [429, 502, 503] },"),r.push(" // throttle: { rate: '10/s', scope: 'host' },"),r.push("});"),{path:"client.ts",contents:`${r.join(`
7
+ `)}
8
+ `}}function ae(e,t){let n=t.layout==="flat"?`${q(e.name)}.ts`:`${x(e)}/index.ts`,r=K(e.op),s={used:new Set,unresolved:new Set},a=r?S(r,s):"unknown";for(let f of s.unresolved)t.warnings.push(`unresolved $ref "${f}" in ${e.name} response \u2192 unknown`);let g=new Map,o=[],h=f=>{let m=t.placement.get(f);if(t.layout==="flat"&&m&&!m.shared){J(f,t,o,new Set);return}let A=t.fileOfComponent(f);g.set(C(f),B(n,A.import))};for(let f of s.used)h(f);let O=t.layout==="flat"?"./client":"../client",l=[];l.push(`import { client } from '${O}';`);for(let[f,m]of g)l.push(`import type { ${f} } from '${m}';`);l.push(""),o.length&&(l.push("// --- types private to this operation (delete this file, they go too) ---"),l.push(...o),l.push("")),e.op.summary&&l.push(`// ${e.op.summary}`),l.push(`// ${e.method} ${e.path}`);let d=[];d.push(` path: ${_(e.path)},`),e.method!=="GET"&&d.push(` method: ${_(e.method)},`);let b=(e.op.parameters??[]).filter(f=>f.in==="query").map(f=>f.name);return b.length&&d.push(` // query params: ${b.join(", ")} \u2014 pass them in the call's \`query\``),e.op.requestBody?.content?.["application/json"]&&d.push(" bodyType: 'json',"),l.push(`export const ${e.name} = client.stitch<${a}>({`),l.push(...d),l.push("});"),{path:n,contents:`${l.join(`
9
+ `)}
10
+ `}}function J(e,t,n,r){if(r.has(e))return;r.add(e);let s=t.components[e];if(!s)return;let a={used:new Set,unresolved:new Set},g=S(s,a);n.push(`type ${C(e)} = ${g};`);for(let o of a.used){let h=t.placement.get(o);o!==e&&h&&!h.shared&&J(o,t,n,r)}}function pe(e,t){let n=["export { client } from './client';"];for(let r of e){let s=t==="flat"?`./${q(r.name)}`:`./${x(r)}`;n.push(`export { ${r.name} } from '${s}';`)}return{path:"index.ts",contents:`${n.join(`
11
+ `)}
12
+ `}}function ce(e,t,n){let r=e.security?.[0],s=r?Object.keys(r)[0]:Object.keys(t)[0];if(!s)return{imports:[]};let a=t[s];if(!a)return{imports:[]};if(a.type==="http"&&a.scheme==="bearer")return{expr:"bearer(env('API_TOKEN'))",imports:["bearer","env"]};if(a.type==="http"&&a.scheme==="basic")return{expr:"basic({ user: env('API_USER'), pass: env('API_PASSWORD') })",imports:["basic","env"]};if(a.type==="apiKey"){let g=a.in==="query"?"in: 'query', ":"",o=a.name?`name: ${JSON.stringify(a.name)}, `:"";return{expr:`apiKey({ ${g}${o}value: env('API_KEY') })`,imports:["apiKey","env"]}}return n.push(`security scheme "${s}" (type ${a.type??"?"}) not auto-mapped \u2014 set client.ts auth manually`),{imports:[]}}function ue(e,t){return{generator:"stitch gen openapi",validator:e,layout:t,operations:[],schemas:[]}}0&&(module.exports={planGen});
package/lib/index.mjs ADDED
@@ -0,0 +1 @@
1
+ import{a as e}from"./chunk-4RAYEZG5.mjs";export{e as planGen};
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@stitchapi/openapi",
3
+ "version": "1.0.0-rc.4",
4
+ "type": "commonjs",
5
+ "description": "Eject selected operations from an OpenAPI document into ready-to-own StitchAPI source — a build-time code generator, separate from the zero-dep runtime.",
6
+ "main": "lib/index.js",
7
+ "module": "lib/index.mjs",
8
+ "types": "lib/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./lib/index.d.mts",
13
+ "default": "./lib/index.mjs"
14
+ },
15
+ "require": {
16
+ "types": "./lib/index.d.ts",
17
+ "default": "./lib/index.js"
18
+ }
19
+ }
20
+ },
21
+ "bin": {
22
+ "stitch-openapi": "bin/stitch-openapi"
23
+ },
24
+ "sideEffects": false,
25
+ "files": [
26
+ "lib",
27
+ "bin"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/rejifald/StitchAPI.git",
35
+ "directory": "packages/openapi"
36
+ },
37
+ "keywords": [
38
+ "stitchapi",
39
+ "openapi",
40
+ "swagger",
41
+ "codegen",
42
+ "code-generation",
43
+ "client-generator",
44
+ "scaffold",
45
+ "typescript"
46
+ ],
47
+ "author": "Oleksandr Zhuravlov (rejifald@gmail.com)",
48
+ "license": "Apache-2.0",
49
+ "homepage": "https://stitchapi.dev",
50
+ "engines": {
51
+ "node": ">=18.18.0"
52
+ },
53
+ "dependencies": {
54
+ "yaml": "^2.4.2"
55
+ },
56
+ "devDependencies": {
57
+ "@types/node": "^22.10.0",
58
+ "tsup": "^8.3.0",
59
+ "typescript": "^5.9.3",
60
+ "vitest": "^4.1.8"
61
+ },
62
+ "scripts": {
63
+ "build": "tsup",
64
+ "test": "vitest run",
65
+ "check:types": "tsc --noEmit"
66
+ }
67
+ }