@jutsustack/api-codegen 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/README.md +574 -141
  2. package/dist/cache/manifest.d.ts +0 -1
  3. package/dist/cache/manifest.d.ts.map +1 -1
  4. package/dist/cache/manifest.js +1 -1
  5. package/dist/cache/manifest.js.map +1 -1
  6. package/dist/cjs/cache/manifest.d.ts +34 -0
  7. package/dist/cjs/cache/manifest.js +45 -0
  8. package/dist/cjs/cli.d.ts +8 -0
  9. package/dist/cjs/cli.js +245 -0
  10. package/dist/cjs/codegen/emit-api.d.ts +6 -0
  11. package/dist/cjs/codegen/emit-api.js +108 -0
  12. package/dist/cjs/codegen/emit-bindings.d.ts +8 -0
  13. package/dist/cjs/codegen/emit-bindings.js +115 -0
  14. package/dist/cjs/codegen/emit-types.d.ts +10 -0
  15. package/dist/cjs/codegen/emit-types.js +232 -0
  16. package/dist/cjs/codegen/emit.d.ts +28 -0
  17. package/dist/cjs/codegen/emit.js +180 -0
  18. package/dist/cjs/codegen/files.d.ts +14 -0
  19. package/dist/cjs/codegen/files.js +66 -0
  20. package/dist/cjs/codegen/plan.d.ts +32 -0
  21. package/dist/cjs/codegen/plan.js +84 -0
  22. package/dist/cjs/codegen/print.d.ts +10 -0
  23. package/dist/cjs/codegen/print.js +65 -0
  24. package/dist/cjs/codegen/templates/bindings.d.ts +13 -0
  25. package/dist/cjs/codegen/templates/bindings.js +707 -0
  26. package/dist/cjs/codegen/templates/runtime.d.ts +2 -0
  27. package/dist/cjs/codegen/templates/runtime.js +1401 -0
  28. package/dist/cjs/codegen/templates/transports.d.ts +1 -0
  29. package/dist/cjs/codegen/templates/transports.js +272 -0
  30. package/dist/cjs/codegen/tsType.d.ts +15 -0
  31. package/dist/cjs/codegen/tsType.js +114 -0
  32. package/dist/cjs/collect/collect.d.ts +16 -0
  33. package/dist/cjs/collect/collect.js +472 -0
  34. package/dist/cjs/collect/naming.d.ts +25 -0
  35. package/dist/cjs/collect/naming.js +149 -0
  36. package/dist/cjs/collect/path.d.ts +10 -0
  37. package/dist/cjs/collect/path.js +67 -0
  38. package/dist/cjs/config/init.d.ts +37 -0
  39. package/dist/cjs/config/init.js +143 -0
  40. package/dist/cjs/config/load.d.ts +11 -0
  41. package/dist/cjs/config/load.js +121 -0
  42. package/dist/cjs/config/types.d.ts +88 -0
  43. package/dist/cjs/config/types.js +2 -0
  44. package/dist/cjs/config/validate.d.ts +8 -0
  45. package/dist/cjs/config/validate.js +200 -0
  46. package/dist/cjs/generate.d.ts +55 -0
  47. package/dist/cjs/generate.js +263 -0
  48. package/dist/cjs/index.d.ts +23 -0
  49. package/dist/cjs/index.js +48 -0
  50. package/dist/cjs/model/collection.d.ts +83 -0
  51. package/dist/cjs/model/collection.js +16 -0
  52. package/dist/cjs/model/infer.d.ts +7 -0
  53. package/dist/cjs/model/infer.js +95 -0
  54. package/dist/cjs/model/merge.d.ts +3 -0
  55. package/dist/cjs/model/merge.js +131 -0
  56. package/dist/cjs/model/reserved.d.ts +2 -0
  57. package/dist/cjs/model/reserved.js +128 -0
  58. package/dist/cjs/model/schema.d.ts +54 -0
  59. package/dist/cjs/model/schema.js +2 -0
  60. package/dist/cjs/package.json +1 -0
  61. package/dist/cjs/parsers/openapi-schema.d.ts +30 -0
  62. package/dist/cjs/parsers/openapi-schema.js +241 -0
  63. package/dist/cjs/parsers/openapi.d.ts +8 -0
  64. package/dist/cjs/parsers/openapi.js +435 -0
  65. package/dist/cjs/parsers/postman.d.ts +20 -0
  66. package/dist/cjs/parsers/postman.js +493 -0
  67. package/dist/cjs/parsers/types.d.ts +52 -0
  68. package/dist/cjs/parsers/types.js +2 -0
  69. package/dist/cjs/sources/load.d.ts +25 -0
  70. package/dist/cjs/sources/load.js +296 -0
  71. package/dist/cjs/sources/parse.d.ts +4 -0
  72. package/dist/cjs/sources/parse.js +50 -0
  73. package/dist/cjs/util/errors.d.ts +9 -0
  74. package/dist/cjs/util/errors.js +23 -0
  75. package/dist/cjs/util/fs.d.ts +7 -0
  76. package/dist/cjs/util/fs.js +44 -0
  77. package/dist/cjs/util/hash.d.ts +3 -0
  78. package/dist/cjs/util/hash.js +26 -0
  79. package/dist/cjs/util/json.d.ts +10 -0
  80. package/dist/cjs/util/json.js +31 -0
  81. package/dist/cjs/util/log.d.ts +22 -0
  82. package/dist/cjs/util/log.js +45 -0
  83. package/dist/cjs/version.d.ts +2 -0
  84. package/dist/cjs/version.js +6 -0
  85. package/dist/cli.d.ts +3 -1
  86. package/dist/cli.d.ts.map +1 -1
  87. package/dist/cli.js +42 -12
  88. package/dist/cli.js.map +1 -1
  89. package/dist/codegen/emit-api.d.ts +3 -1
  90. package/dist/codegen/emit-api.d.ts.map +1 -1
  91. package/dist/codegen/emit-api.js +32 -7
  92. package/dist/codegen/emit-api.js.map +1 -1
  93. package/dist/codegen/emit-bindings.d.ts +9 -0
  94. package/dist/codegen/emit-bindings.d.ts.map +1 -0
  95. package/dist/codegen/emit-bindings.js +112 -0
  96. package/dist/codegen/emit-bindings.js.map +1 -0
  97. package/dist/codegen/emit-types.d.ts +8 -1
  98. package/dist/codegen/emit-types.d.ts.map +1 -1
  99. package/dist/codegen/emit-types.js +10 -8
  100. package/dist/codegen/emit-types.js.map +1 -1
  101. package/dist/codegen/emit.d.ts +10 -1
  102. package/dist/codegen/emit.d.ts.map +1 -1
  103. package/dist/codegen/emit.js +142 -37
  104. package/dist/codegen/emit.js.map +1 -1
  105. package/dist/codegen/files.d.ts +3 -12
  106. package/dist/codegen/files.d.ts.map +1 -1
  107. package/dist/codegen/files.js +3 -12
  108. package/dist/codegen/files.js.map +1 -1
  109. package/dist/codegen/print.d.ts +1 -4
  110. package/dist/codegen/print.d.ts.map +1 -1
  111. package/dist/codegen/print.js +1 -4
  112. package/dist/codegen/print.js.map +1 -1
  113. package/dist/codegen/templates/bindings.d.ts +14 -0
  114. package/dist/codegen/templates/bindings.d.ts.map +1 -0
  115. package/dist/codegen/templates/bindings.js +705 -0
  116. package/dist/codegen/templates/bindings.js.map +1 -0
  117. package/dist/codegen/templates/runtime.d.ts +2 -1
  118. package/dist/codegen/templates/runtime.d.ts.map +1 -1
  119. package/dist/codegen/templates/runtime.js +1192 -279
  120. package/dist/codegen/templates/runtime.js.map +1 -1
  121. package/dist/codegen/templates/transports.d.ts +2 -0
  122. package/dist/codegen/templates/transports.d.ts.map +1 -0
  123. package/dist/codegen/templates/transports.js +270 -0
  124. package/dist/codegen/templates/transports.js.map +1 -0
  125. package/dist/collect/collect.d.ts +1 -11
  126. package/dist/collect/collect.d.ts.map +1 -1
  127. package/dist/collect/collect.js +21 -28
  128. package/dist/collect/collect.js.map +1 -1
  129. package/dist/collect/naming.d.ts +1 -4
  130. package/dist/collect/naming.d.ts.map +1 -1
  131. package/dist/collect/naming.js +1 -4
  132. package/dist/collect/naming.js.map +1 -1
  133. package/dist/collect/path.d.ts +2 -9
  134. package/dist/collect/path.d.ts.map +1 -1
  135. package/dist/collect/path.js +2 -9
  136. package/dist/collect/path.js.map +1 -1
  137. package/dist/config/init.d.ts +11 -2
  138. package/dist/config/init.d.ts.map +1 -1
  139. package/dist/config/init.js +55 -7
  140. package/dist/config/init.js.map +1 -1
  141. package/dist/config/load.d.ts.map +1 -1
  142. package/dist/config/load.js +26 -1
  143. package/dist/config/load.js.map +1 -1
  144. package/dist/config/types.d.ts +13 -5
  145. package/dist/config/types.d.ts.map +1 -1
  146. package/dist/config/validate.d.ts +2 -6
  147. package/dist/config/validate.d.ts.map +1 -1
  148. package/dist/config/validate.js +18 -7
  149. package/dist/config/validate.js.map +1 -1
  150. package/dist/generate.d.ts +2 -8
  151. package/dist/generate.d.ts.map +1 -1
  152. package/dist/generate.js +13 -12
  153. package/dist/generate.js.map +1 -1
  154. package/dist/index.d.ts +4 -4
  155. package/dist/index.d.ts.map +1 -1
  156. package/dist/index.js +4 -4
  157. package/dist/index.js.map +1 -1
  158. package/dist/model/infer.d.ts +2 -9
  159. package/dist/model/infer.d.ts.map +1 -1
  160. package/dist/model/infer.js +2 -9
  161. package/dist/model/infer.js.map +1 -1
  162. package/dist/model/merge.d.ts +1 -5
  163. package/dist/model/merge.d.ts.map +1 -1
  164. package/dist/model/merge.js +1 -5
  165. package/dist/model/merge.js.map +1 -1
  166. package/dist/model/reserved.d.ts +1 -4
  167. package/dist/model/reserved.d.ts.map +1 -1
  168. package/dist/model/reserved.js +63 -4
  169. package/dist/model/reserved.js.map +1 -1
  170. package/dist/model/schema.d.ts +1 -4
  171. package/dist/model/schema.d.ts.map +1 -1
  172. package/dist/parsers/openapi-schema.d.ts +1 -5
  173. package/dist/parsers/openapi-schema.d.ts.map +1 -1
  174. package/dist/parsers/openapi-schema.js +2 -5
  175. package/dist/parsers/openapi-schema.js.map +1 -1
  176. package/dist/parsers/postman.d.ts +0 -3
  177. package/dist/parsers/postman.d.ts.map +1 -1
  178. package/dist/parsers/postman.js +2 -5
  179. package/dist/parsers/postman.js.map +1 -1
  180. package/dist/sources/load.d.ts +0 -6
  181. package/dist/sources/load.d.ts.map +1 -1
  182. package/dist/sources/load.js +4 -7
  183. package/dist/sources/load.js.map +1 -1
  184. package/dist/sources/parse.d.ts +0 -2
  185. package/dist/sources/parse.d.ts.map +1 -1
  186. package/dist/sources/parse.js +1 -1
  187. package/dist/sources/parse.js.map +1 -1
  188. package/dist/version.d.ts +1 -1
  189. package/dist/version.js +1 -1
  190. package/package.json +40 -12
  191. package/schema/config.schema.json +58 -12
  192. package/dist/codegen/emit-hooks.d.ts +0 -5
  193. package/dist/codegen/emit-hooks.d.ts.map +0 -1
  194. package/dist/codegen/emit-hooks.js +0 -67
  195. package/dist/codegen/emit-hooks.js.map +0 -1
  196. package/dist/codegen/templates/hooks.d.ts +0 -11
  197. package/dist/codegen/templates/hooks.d.ts.map +0 -1
  198. package/dist/codegen/templates/hooks.js +0 -272
  199. package/dist/codegen/templates/hooks.js.map +0 -1
@@ -0,0 +1,296 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.loadSource = loadSource;
7
+ const promises_1 = require("node:fs/promises");
8
+ const node_path_1 = __importDefault(require("node:path"));
9
+ const manifest_js_1 = require("../cache/manifest.js");
10
+ const validate_js_1 = require("../config/validate.js");
11
+ const errors_js_1 = require("../util/errors.js");
12
+ const fs_js_1 = require("../util/fs.js");
13
+ const hash_js_1 = require("../util/hash.js");
14
+ /** Hard cap on a downloaded document. */
15
+ const MAX_SOURCE_BYTES = 50 * 1024 * 1024;
16
+ const TIMEOUT_MS = 30_000;
17
+ const POSTMAN_API = 'https://api.getpostman.com';
18
+ async function loadSource(source, ctx) {
19
+ const loaded = source.path !== undefined
20
+ ? await loadFile(source, source.path, ctx)
21
+ : await loadRemote(source, ctx);
22
+ if (source.environment !== undefined) {
23
+ const envPath = node_path_1.default.resolve(ctx.configDir, source.environment);
24
+ const envText = await (0, promises_1.readFile)(envPath, 'utf8').catch((error) => {
25
+ throw new errors_js_1.CodegenError('SOURCE_READ', `Source "${source.id}": cannot read environment ${source.environment}: ${(0, errors_js_1.errorMessage)(error)}`);
26
+ });
27
+ loaded.environment = parseEnvironment(envText, source.id);
28
+ loaded.meta.hash = (0, hash_js_1.sha256)(`${loaded.meta.hash}\0${(0, hash_js_1.sha256)(envText)}`);
29
+ }
30
+ return loaded;
31
+ }
32
+ async function loadFile(source, rel, ctx) {
33
+ const file = node_path_1.default.resolve(ctx.configDir, rel);
34
+ let text;
35
+ let mtime;
36
+ try {
37
+ [text, mtime] = await Promise.all([
38
+ (0, promises_1.readFile)(file, 'utf8'),
39
+ (0, promises_1.stat)(file).then((s) => s.mtime),
40
+ ]);
41
+ }
42
+ catch (error) {
43
+ throw new errors_js_1.CodegenError('SOURCE_READ', `Source "${source.id}": cannot read ${rel}: ${(0, errors_js_1.errorMessage)(error)}`);
44
+ }
45
+ return {
46
+ config: source,
47
+ text,
48
+ from: 'file',
49
+ meta: {
50
+ id: source.id,
51
+ origin: (0, fs_js_1.toPosixRelative)(ctx.configDir, file),
52
+ hash: (0, hash_js_1.sha256)(text),
53
+ mtime: mtime.toISOString(),
54
+ fetchedAt: ctx.now().toISOString(),
55
+ },
56
+ };
57
+ }
58
+ function remoteRequest(source, env) {
59
+ if (source.postman) {
60
+ const keyEnv = source.postman.apiKeyEnv ?? 'POSTMAN_API_KEY';
61
+ if (!(0, validate_js_1.isEnvName)(keyEnv))
62
+ throw new errors_js_1.CodegenError('CONFIG_INVALID', `Source "${source.id}": invalid apiKeyEnv`);
63
+ const key = env[keyEnv];
64
+ if (!key) {
65
+ throw new errors_js_1.CodegenError('ENV_MISSING', `Source "${source.id}": set ${keyEnv} to your Postman API key (Postman → Settings → API keys)`);
66
+ }
67
+ const url = `${POSTMAN_API}/collections/${encodeURIComponent(source.postman.collectionId)}`;
68
+ return {
69
+ url,
70
+ origin: url,
71
+ headers: { 'x-api-key': key, 'accept': 'application/json' },
72
+ };
73
+ }
74
+ const url = source.url;
75
+ const headers = {
76
+ accept: 'application/json, application/yaml, text/yaml, */*;q=0.5',
77
+ };
78
+ for (const [name, value] of Object.entries(source.headers ?? {})) {
79
+ headers[name.toLowerCase()] = interpolateEnv(value, env, source.id);
80
+ }
81
+ return { url, origin: stripCredentials(url), headers };
82
+ }
83
+ /** `Bearer ${API_TOKEN}` → value from the environment; a missing variable is an error. */
84
+ function interpolateEnv(value, env, sourceId) {
85
+ return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_m, name) => {
86
+ const v = env[name];
87
+ if (v === undefined)
88
+ throw new errors_js_1.CodegenError('ENV_MISSING', `Source "${sourceId}": environment variable ${name} is not set`);
89
+ return v;
90
+ });
91
+ }
92
+ function stripCredentials(url) {
93
+ try {
94
+ const u = new URL(url);
95
+ u.username = '';
96
+ u.password = '';
97
+ return u.toString();
98
+ }
99
+ catch {
100
+ return url;
101
+ }
102
+ }
103
+ async function loadRemote(source, ctx) {
104
+ const request = remoteRequest(source, ctx.env);
105
+ const snapshotFile = (0, manifest_js_1.snapshotPath)(ctx.cacheDir, source.id);
106
+ const snapshot = await (0, fs_js_1.readTextIfExists)(snapshotFile);
107
+ const previous = ctx.previous && ctx.previous.origin === request.origin
108
+ ? ctx.previous
109
+ : undefined;
110
+ const fromSnapshot = (reason) => {
111
+ if (snapshot === undefined) {
112
+ throw new errors_js_1.CodegenError('SOURCE_OFFLINE', `Source "${source.id}": ${reason} and there is no cached copy yet`);
113
+ }
114
+ const meta = {
115
+ id: source.id,
116
+ origin: request.origin,
117
+ hash: (0, hash_js_1.sha256)(snapshot),
118
+ fetchedAt: previous?.fetchedAt ?? ctx.now().toISOString(),
119
+ };
120
+ if (previous?.etag)
121
+ meta.etag = previous.etag;
122
+ if (previous?.lastModified)
123
+ meta.lastModified = previous.lastModified;
124
+ if (previous?.updatedAt)
125
+ meta.updatedAt = previous.updatedAt;
126
+ return {
127
+ config: source,
128
+ text: snapshot,
129
+ url: request.origin,
130
+ from: 'cache',
131
+ meta,
132
+ };
133
+ };
134
+ if (ctx.offline)
135
+ return fromSnapshot('--offline is set');
136
+ let response;
137
+ let finalUrl = request.url;
138
+ try {
139
+ ({ response, url: finalUrl } = await fetchFollowingRedirects(ctx.fetch, request.url, conditionalHeaders(request.headers, snapshot, previous)));
140
+ }
141
+ catch (error) {
142
+ if (snapshot !== undefined) {
143
+ ctx.logger.warn(`Source "${source.id}": ${request.origin} unreachable (${(0, errors_js_1.errorMessage)(error)}); using the cached copy`);
144
+ return fromSnapshot('unreachable');
145
+ }
146
+ throw new errors_js_1.CodegenError('SOURCE_FETCH', `Source "${source.id}": cannot reach ${request.origin}: ${(0, errors_js_1.errorMessage)(error)}`);
147
+ }
148
+ if (response.status === 304) {
149
+ ctx.logger.debug(`Source "${source.id}": not modified (304)`);
150
+ return fromSnapshot('not modified');
151
+ }
152
+ if (!response.ok) {
153
+ if (response.status >= 500 && snapshot !== undefined) {
154
+ ctx.logger.warn(`Source "${source.id}": ${request.origin} answered ${response.status}; using the cached copy`);
155
+ return fromSnapshot(`server error ${response.status}`);
156
+ }
157
+ const hint = response.status === 401 || response.status === 403
158
+ ? ' (check credentials / API key)'
159
+ : '';
160
+ throw new errors_js_1.CodegenError('SOURCE_FETCH', `Source "${source.id}": ${request.origin} answered ${response.status}${hint}`);
161
+ }
162
+ const text = await readLimited(response, source.id);
163
+ await (0, fs_js_1.writeFileAtomic)(snapshotFile, text);
164
+ return {
165
+ config: source,
166
+ text,
167
+ url: stripCredentials(finalUrl),
168
+ from: 'network',
169
+ meta: downloadedMeta(source, request.origin, text, response.headers, ctx.now()),
170
+ };
171
+ }
172
+ /** Ask the server to answer 304 when the cached copy is still current. */
173
+ function conditionalHeaders(headers, snapshot, previous) {
174
+ const out = { ...headers };
175
+ if (snapshot === undefined || previous?.hash !== (0, hash_js_1.sha256)(snapshot))
176
+ return out;
177
+ if (previous.etag)
178
+ out['if-none-match'] = previous.etag;
179
+ if (previous.lastModified)
180
+ out['if-modified-since'] = previous.lastModified;
181
+ return out;
182
+ }
183
+ function downloadedMeta(source, origin, text, headers, now) {
184
+ const meta = {
185
+ id: source.id,
186
+ origin,
187
+ hash: (0, hash_js_1.sha256)(text),
188
+ fetchedAt: now.toISOString(),
189
+ };
190
+ const etag = headers.get('etag');
191
+ if (etag)
192
+ meta.etag = etag;
193
+ const lastModified = headers.get('last-modified');
194
+ if (lastModified)
195
+ meta.lastModified = lastModified;
196
+ const updatedAt = source.postman ? postmanUpdatedAt(text) : undefined;
197
+ if (updatedAt)
198
+ meta.updatedAt = updatedAt;
199
+ return meta;
200
+ }
201
+ /** Headers that may follow a redirect to another origin; everything else may be a secret. */
202
+ const PORTABLE_HEADERS = new Set([
203
+ 'accept',
204
+ 'if-none-match',
205
+ 'if-modified-since',
206
+ ]);
207
+ const MAX_REDIRECTS = 5;
208
+ /** fetch() following redirects by hand, so credentials never reach another origin. */
209
+ async function fetchFollowingRedirects(doFetch, url, headers) {
210
+ const origin = new URL(url).origin;
211
+ const signal = AbortSignal.timeout(TIMEOUT_MS);
212
+ let current = url;
213
+ for (let hop = 0;; hop++) {
214
+ const sameOrigin = new URL(current).origin === origin;
215
+ const sent = sameOrigin
216
+ ? headers
217
+ : Object.fromEntries(Object.entries(headers).filter(([k]) => PORTABLE_HEADERS.has(k)));
218
+ const response = await doFetch(current, {
219
+ headers: sent,
220
+ signal,
221
+ redirect: 'manual',
222
+ });
223
+ const location = response.headers.get('location');
224
+ if (response.status < 300 ||
225
+ response.status > 399 ||
226
+ response.status === 304 ||
227
+ !location) {
228
+ return { response, url: current };
229
+ }
230
+ if (hop >= MAX_REDIRECTS)
231
+ throw new Error(`more than ${MAX_REDIRECTS} redirects`);
232
+ const next = new URL(location, current);
233
+ if (next.protocol !== 'https:' && next.protocol !== 'http:') {
234
+ throw new Error(`redirect to unsupported URL ${next.protocol}`);
235
+ }
236
+ await response.body?.cancel();
237
+ current = next.toString();
238
+ }
239
+ }
240
+ async function readLimited(response, sourceId) {
241
+ const declared = Number(response.headers.get('content-length') ?? '0');
242
+ const tooBig = () => new errors_js_1.CodegenError('SOURCE_FETCH', `Source "${sourceId}": document is larger than ${MAX_SOURCE_BYTES / 1024 / 1024} MB`);
243
+ if (declared > MAX_SOURCE_BYTES)
244
+ throw tooBig();
245
+ if (!response.body)
246
+ return response.text();
247
+ const reader = response.body.getReader();
248
+ const chunks = [];
249
+ let size = 0;
250
+ for (;;) {
251
+ const { done, value } = await reader.read();
252
+ if (done)
253
+ break;
254
+ size += value.byteLength;
255
+ if (size > MAX_SOURCE_BYTES) {
256
+ await reader.cancel();
257
+ throw tooBig();
258
+ }
259
+ chunks.push(value);
260
+ }
261
+ return Buffer.concat(chunks).toString('utf8');
262
+ }
263
+ function postmanUpdatedAt(text) {
264
+ try {
265
+ const doc = JSON.parse(text);
266
+ const value = doc.collection?.info?.updatedAt;
267
+ return typeof value === 'string' ? value : undefined;
268
+ }
269
+ catch {
270
+ return undefined;
271
+ }
272
+ }
273
+ /** Enabled `values` of a Postman environment export. */
274
+ function parseEnvironment(text, sourceId) {
275
+ let doc;
276
+ try {
277
+ doc = JSON.parse(text);
278
+ }
279
+ catch {
280
+ throw new errors_js_1.CodegenError('SOURCE_FORMAT', `Source "${sourceId}": environment file is not JSON`);
281
+ }
282
+ const values = doc.values;
283
+ const out = {};
284
+ if (!Array.isArray(values))
285
+ return out;
286
+ for (const v of values) {
287
+ if (v &&
288
+ typeof v === 'object' &&
289
+ typeof v.key === 'string' &&
290
+ v.enabled !== false &&
291
+ v.value !== undefined) {
292
+ out[v.key] = String(v.value);
293
+ }
294
+ }
295
+ return out;
296
+ }
@@ -0,0 +1,4 @@
1
+ import type { ParsedSource } from '../parsers/types.js';
2
+ import type { LoadedSource } from './load.js';
3
+ /** Parse a loaded source with the parser its content (or its declared `type`) calls for. */
4
+ export declare function parseSource(loaded: LoadedSource): ParsedSource;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseSource = parseSource;
4
+ const yaml_1 = require("yaml");
5
+ const openapi_js_1 = require("../parsers/openapi.js");
6
+ const postman_js_1 = require("../parsers/postman.js");
7
+ const errors_js_1 = require("../util/errors.js");
8
+ /** JSON first; YAML for Swagger / OpenAPI documents written in YAML. */
9
+ function parseDocument(text, sourceId) {
10
+ const trimmed = text.replace(/^\uFEFF/, '').trim();
11
+ if (!trimmed)
12
+ throw new errors_js_1.CodegenError('SOURCE_FORMAT', `Source "${sourceId}" is empty`);
13
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
14
+ try {
15
+ return JSON.parse(trimmed);
16
+ }
17
+ catch (error) {
18
+ throw new errors_js_1.CodegenError('SOURCE_FORMAT', `Source "${sourceId}" is not valid JSON: ${(0, errors_js_1.errorMessage)(error)}`);
19
+ }
20
+ }
21
+ try {
22
+ // yaml's default alias limit guards against "billion laughs" documents
23
+ return (0, yaml_1.parse)(trimmed, { maxAliasCount: 100 });
24
+ }
25
+ catch (error) {
26
+ throw new errors_js_1.CodegenError('SOURCE_FORMAT', `Source "${sourceId}" is neither JSON nor YAML: ${(0, errors_js_1.errorMessage)(error)}`);
27
+ }
28
+ }
29
+ /** Parse a loaded source with the parser its content (or its declared `type`) calls for. */
30
+ function parseSource(loaded) {
31
+ const { id } = loaded.config;
32
+ const doc = parseDocument(loaded.text, id);
33
+ const declared = loaded.config.type ?? 'auto';
34
+ const openApiKind = (0, openapi_js_1.detectOpenApiKind)(doc);
35
+ const isPostman = !openApiKind && (0, postman_js_1.unwrapPostman)(doc) !== undefined;
36
+ if (declared === 'postman' || (declared === 'auto' && isPostman)) {
37
+ if (!isPostman)
38
+ throw new errors_js_1.CodegenError('SOURCE_FORMAT', `Source "${id}" is declared as postman but is not a Postman collection`);
39
+ return (0, postman_js_1.parsePostman)(doc, id, loaded.environment ? { environment: loaded.environment } : {});
40
+ }
41
+ if (declared === 'openapi' ||
42
+ declared === 'swagger' ||
43
+ (declared === 'auto' && openApiKind)) {
44
+ if (!openApiKind) {
45
+ throw new errors_js_1.CodegenError('SOURCE_FORMAT', `Source "${id}" is declared as ${declared} but has no "openapi: 3.x" / "swagger: 2.0" field`);
46
+ }
47
+ return (0, openapi_js_1.parseOpenApi)(doc, id, loaded.url ? { sourceUrl: loaded.url } : {});
48
+ }
49
+ throw new errors_js_1.CodegenError('SOURCE_FORMAT', `Source "${id}": unrecognised format (expected a Postman v2 collection, Swagger 2.0 or OpenAPI 3.x)`);
50
+ }
@@ -0,0 +1,9 @@
1
+ export type CodegenErrorCode = 'CONFIG_NOT_FOUND' | 'CONFIG_AMBIGUOUS' | 'CONFIG_INVALID' | 'CONFIG_EXISTS' | 'SOURCE_READ' | 'SOURCE_FETCH' | 'SOURCE_FORMAT' | 'SOURCE_OFFLINE' | 'ENV_MISSING' | 'OUTPUT_UNSAFE' | 'OUTPUT_MODIFIED' | 'USAGE';
2
+ /** Expected, user-facing failure. The CLI prints `message` without a stack trace. */
3
+ export declare class CodegenError extends Error {
4
+ readonly code: CodegenErrorCode;
5
+ readonly details: readonly string[];
6
+ constructor(code: CodegenErrorCode, message: string, details?: readonly string[]);
7
+ }
8
+ export declare function isCodegenError(error: unknown): error is CodegenError;
9
+ export declare function errorMessage(error: unknown): string;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CodegenError = void 0;
4
+ exports.isCodegenError = isCodegenError;
5
+ exports.errorMessage = errorMessage;
6
+ /** Expected, user-facing failure. The CLI prints `message` without a stack trace. */
7
+ class CodegenError extends Error {
8
+ code;
9
+ details;
10
+ constructor(code, message, details = []) {
11
+ super(message);
12
+ this.name = 'CodegenError';
13
+ this.code = code;
14
+ this.details = details;
15
+ }
16
+ }
17
+ exports.CodegenError = CodegenError;
18
+ function isCodegenError(error) {
19
+ return error instanceof CodegenError;
20
+ }
21
+ function errorMessage(error) {
22
+ return error instanceof Error ? error.message : String(error);
23
+ }
@@ -0,0 +1,7 @@
1
+ export declare function readTextIfExists(file: string): Promise<string | undefined>;
2
+ /** Write via a temp file + rename so readers never see a half-written file. */
3
+ export declare function writeFileAtomic(file: string, content: string): Promise<void>;
4
+ /** True when `child` is `parent` or inside it (after resolving `..`). */
5
+ export declare function isInside(parent: string, child: string): boolean;
6
+ /** Forward-slash relative path, for output that must be identical on every OS. */
7
+ export declare function toPosixRelative(from: string, to: string): string;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.readTextIfExists = readTextIfExists;
7
+ exports.writeFileAtomic = writeFileAtomic;
8
+ exports.isInside = isInside;
9
+ exports.toPosixRelative = toPosixRelative;
10
+ const node_crypto_1 = require("node:crypto");
11
+ const promises_1 = require("node:fs/promises");
12
+ const node_path_1 = __importDefault(require("node:path"));
13
+ async function readTextIfExists(file) {
14
+ try {
15
+ return await (0, promises_1.readFile)(file, 'utf8');
16
+ }
17
+ catch (error) {
18
+ if (error.code === 'ENOENT')
19
+ return undefined;
20
+ throw error;
21
+ }
22
+ }
23
+ /** Write via a temp file + rename so readers never see a half-written file. */
24
+ async function writeFileAtomic(file, content) {
25
+ await (0, promises_1.mkdir)(node_path_1.default.dirname(file), { recursive: true });
26
+ const tmp = `${file}.${process.pid}.${(0, node_crypto_1.randomBytes)(4).toString('hex')}.tmp`;
27
+ try {
28
+ await (0, promises_1.writeFile)(tmp, content, 'utf8');
29
+ await (0, promises_1.rename)(tmp, file);
30
+ }
31
+ catch (error) {
32
+ await (0, promises_1.rm)(tmp, { force: true });
33
+ throw error;
34
+ }
35
+ }
36
+ /** True when `child` is `parent` or inside it (after resolving `..`). */
37
+ function isInside(parent, child) {
38
+ const rel = node_path_1.default.relative(node_path_1.default.resolve(parent), node_path_1.default.resolve(child));
39
+ return rel === '' || (!rel.startsWith('..') && !node_path_1.default.isAbsolute(rel));
40
+ }
41
+ /** Forward-slash relative path, for output that must be identical on every OS. */
42
+ function toPosixRelative(from, to) {
43
+ return node_path_1.default.relative(from, to).split(node_path_1.default.sep).join('/');
44
+ }
@@ -0,0 +1,3 @@
1
+ export declare function sha256(input: string | Uint8Array): string;
2
+ /** JSON with object keys sorted, so equal values always hash the same. */
3
+ export declare function stableStringify(value: unknown): string;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sha256 = sha256;
4
+ exports.stableStringify = stableStringify;
5
+ const node_crypto_1 = require("node:crypto");
6
+ function sha256(input) {
7
+ return (0, node_crypto_1.createHash)('sha256').update(input).digest('hex');
8
+ }
9
+ /** JSON with object keys sorted, so equal values always hash the same. */
10
+ function stableStringify(value) {
11
+ return JSON.stringify(sortKeys(value));
12
+ }
13
+ function sortKeys(value) {
14
+ if (Array.isArray(value))
15
+ return value.map(sortKeys);
16
+ if (value && typeof value === 'object') {
17
+ const out = {};
18
+ for (const key of Object.keys(value).sort()) {
19
+ const v = value[key];
20
+ if (v !== undefined)
21
+ out[key] = sortKeys(v);
22
+ }
23
+ return out;
24
+ }
25
+ return value;
26
+ }
@@ -0,0 +1,10 @@
1
+ export type Json = Record<string, unknown>;
2
+ export declare function isObject(value: unknown): value is Json;
3
+ export declare function asArray(value: unknown): unknown[];
4
+ export declare function asString(value: unknown): string | undefined;
5
+ /** The string items of an array (anything else is dropped). */
6
+ export declare function asStrings(value: unknown): string[];
7
+ /** A trimmed, non-empty string, or undefined. */
8
+ export declare function text(value: unknown): string | undefined;
9
+ /** The value when it is an object, an empty object otherwise. */
10
+ export declare function objectAt(value: unknown): Json;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ // Narrowing helpers for untrusted JSON / YAML documents.
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.isObject = isObject;
5
+ exports.asArray = asArray;
6
+ exports.asString = asString;
7
+ exports.asStrings = asStrings;
8
+ exports.text = text;
9
+ exports.objectAt = objectAt;
10
+ function isObject(value) {
11
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
12
+ }
13
+ function asArray(value) {
14
+ return Array.isArray(value) ? value : [];
15
+ }
16
+ function asString(value) {
17
+ return typeof value === 'string' ? value : undefined;
18
+ }
19
+ /** The string items of an array (anything else is dropped). */
20
+ function asStrings(value) {
21
+ return asArray(value).filter((v) => typeof v === 'string');
22
+ }
23
+ /** A trimmed, non-empty string, or undefined. */
24
+ function text(value) {
25
+ const trimmed = asString(value)?.trim();
26
+ return trimmed ? trimmed : undefined;
27
+ }
28
+ /** The value when it is an object, an empty object otherwise. */
29
+ function objectAt(value) {
30
+ return isObject(value) ? value : {};
31
+ }
@@ -0,0 +1,22 @@
1
+ export interface Logger {
2
+ info(message: string): void;
3
+ success(message: string): void;
4
+ warn(message: string): void;
5
+ error(message: string): void;
6
+ debug(message: string): void;
7
+ }
8
+ export interface LoggerOptions {
9
+ quiet?: boolean;
10
+ verbose?: boolean;
11
+ color?: boolean;
12
+ out?: (line: string) => void;
13
+ err?: (line: string) => void;
14
+ }
15
+ export declare function createLogger(options?: LoggerOptions): Logger;
16
+ /** Collects messages instead of printing them (tests, programmatic use). */
17
+ export declare function createMemoryLogger(): Logger & {
18
+ readonly lines: {
19
+ level: string;
20
+ message: string;
21
+ }[];
22
+ };
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createLogger = createLogger;
4
+ exports.createMemoryLogger = createMemoryLogger;
5
+ const paint = (on, code) => (s) => on ? `\u001b[${code}m${s}\u001b[39m` : s;
6
+ function createLogger(options = {}) {
7
+ const out = options.out ?? ((line) => process.stdout.write(line + '\n'));
8
+ const err = options.err ?? ((line) => process.stderr.write(line + '\n'));
9
+ const color = options.color ?? false;
10
+ const green = paint(color, 32);
11
+ const yellow = paint(color, 33);
12
+ const red = paint(color, 31);
13
+ const gray = paint(color, 90);
14
+ return {
15
+ info: (m) => {
16
+ if (!options.quiet)
17
+ out(m);
18
+ },
19
+ success: (m) => {
20
+ if (!options.quiet)
21
+ out(`${green('✔')} ${m}`);
22
+ },
23
+ warn: (m) => err(`${yellow('⚠')} ${m}`),
24
+ error: (m) => err(`${red('✖')} ${m}`),
25
+ debug: (m) => {
26
+ if (options.verbose)
27
+ out(gray(m));
28
+ },
29
+ };
30
+ }
31
+ /** Collects messages instead of printing them (tests, programmatic use). */
32
+ function createMemoryLogger() {
33
+ const lines = [];
34
+ const push = (level) => (message) => {
35
+ lines.push({ level, message });
36
+ };
37
+ return {
38
+ lines,
39
+ info: push('info'),
40
+ success: push('success'),
41
+ warn: push('warn'),
42
+ error: push('error'),
43
+ debug: push('debug'),
44
+ };
45
+ }
@@ -0,0 +1,2 @@
1
+ export declare const PACKAGE_NAME = "@jutsustack/api-codegen";
2
+ export declare const VERSION = "0.2.0";
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VERSION = exports.PACKAGE_NAME = void 0;
4
+ // Kept in sync with package.json by test/version.test.ts.
5
+ exports.PACKAGE_NAME = '@jutsustack/api-codegen';
6
+ exports.VERSION = '0.2.0';
package/dist/cli.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import type { Logger } from './util/log.js';
2
- export declare const HELP = "@jutsustack/api-codegen 0.1.0\nGenerate a typed API layer for React Native, React and Next.js from Postman,\nSwagger and OpenAPI collections.\n\nUsage\n jutsu-api [command] [options]\n\nCommands\n generate Build api-collection.json and the typed client (default)\n check Exit 1 when generated files are out of date (CI)\n collect Only build api-collection.json\n init Create <project>-api.config.json\n\nOptions\n -c, --config <file> Config file (default: the *-api.config.json in the cwd)\n --cwd <dir> Run as if started in <dir>\n -f, --force Regenerate even if nothing changed; overwrite edited files\n --offline Use cached copies of remote sources, never the network\n --dry-run Show what would change without writing\n -q, --quiet Only print warnings and errors\n -v, --verbose Print debug details\n -h, --help Show this help\n -V, --version Show the version\n\ninit options\n --name <project> Project name (default: package.json name)\n --target <t> react-native | react | next (default: detected)\n --source <s> Path or URL of the first collection / spec\n --output <dir> Output folder (default: src/api, lib/api for Next.js)\n\nExit codes\n 0 success / up to date 1 failure or stale (check) 2 usage or config error\n\nEnvironment\n POSTMAN_API_KEY Key for \"postman\": { \"collectionId\" } sources\n NO_COLOR Disable colours\n";
2
+ export declare const HELP: string;
3
3
  /** Run the CLI; resolves the process exit code. */
4
4
  export declare function main(argv: string[], io?: {
5
5
  logger?: Logger;
6
6
  }): Promise<number>;
7
+ /** How to run the CLI with the package manager that started it (npm, pnpm, yarn or bun). */
8
+ export declare function runner(env?: NodeJS.ProcessEnv): string;
7
9
  //# sourceMappingURL=cli.d.ts.map
package/dist/cli.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAG5C,eAAO,MAAM,IAAI,w+CAoChB,CAAC;AAwCF,mDAAmD;AACnD,wBAAsB,IAAI,CACxB,IAAI,EAAE,MAAM,EAAE,EACd,EAAE,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAO,GAC3B,OAAO,CAAC,MAAM,CAAC,CA0DjB"}
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAG5C,eAAO,MAAM,IAAI,QAyChB,CAAC;AA0CF,mDAAmD;AACnD,wBAAsB,IAAI,CACxB,IAAI,EAAE,MAAM,EAAE,EACd,EAAE,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAO,GAC3B,OAAO,CAAC,MAAM,CAAC,CA0DjB;AAwGD,4FAA4F;AAC5F,wBAAgB,MAAM,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,MAAM,CAMnE"}