@nifrajs/cli 2.9.1 → 2.11.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 (55) hide show
  1. package/README.md +2 -1
  2. package/dist/check.d.ts +9 -1
  3. package/dist/check.d.ts.map +1 -1
  4. package/dist/check.js +38 -6
  5. package/dist/check.js.map +1 -1
  6. package/dist/cli.d.ts +2 -18
  7. package/dist/cli.d.ts.map +1 -1
  8. package/dist/cli.js +129 -66
  9. package/dist/cli.js.map +1 -1
  10. package/dist/dev-bun-config.d.ts +17 -6
  11. package/dist/dev-bun-config.d.ts.map +1 -1
  12. package/dist/dev-bun-config.js +51 -14
  13. package/dist/dev-bun-config.js.map +1 -1
  14. package/dist/doctor.d.ts +10 -0
  15. package/dist/doctor.d.ts.map +1 -1
  16. package/dist/doctor.js +17 -1
  17. package/dist/doctor.js.map +1 -1
  18. package/dist/introspect.d.ts +26 -6
  19. package/dist/introspect.d.ts.map +1 -1
  20. package/dist/introspect.js +92 -2
  21. package/dist/introspect.js.map +1 -1
  22. package/dist/load.d.ts +4 -0
  23. package/dist/load.d.ts.map +1 -1
  24. package/dist/load.js +1 -0
  25. package/dist/load.js.map +1 -1
  26. package/dist/mcp-http.js +1 -1
  27. package/dist/mcp-http.js.map +1 -1
  28. package/dist/mcp.js +2 -2
  29. package/dist/mcp.js.map +1 -1
  30. package/dist/pipeline-guard.d.ts +25 -10
  31. package/dist/pipeline-guard.d.ts.map +1 -1
  32. package/dist/pipeline-guard.js +35 -15
  33. package/dist/pipeline-guard.js.map +1 -1
  34. package/dist/pipeline-report.d.ts +34 -0
  35. package/dist/pipeline-report.d.ts.map +1 -0
  36. package/dist/pipeline-report.js +282 -0
  37. package/dist/pipeline-report.js.map +1 -0
  38. package/dist/sdk.d.ts +10 -0
  39. package/dist/sdk.d.ts.map +1 -0
  40. package/dist/sdk.js +229 -0
  41. package/dist/sdk.js.map +1 -0
  42. package/docs/llms-full.txt +246 -17
  43. package/docs/types.json +725 -16
  44. package/package.json +9 -9
  45. package/src/check.ts +54 -5
  46. package/src/cli.ts +131 -67
  47. package/src/dev-bun-config.ts +57 -14
  48. package/src/doctor.ts +28 -1
  49. package/src/introspect.ts +124 -4
  50. package/src/load.ts +5 -0
  51. package/src/mcp-http.ts +1 -1
  52. package/src/mcp.ts +2 -2
  53. package/src/pipeline-guard.ts +44 -14
  54. package/src/pipeline-report.ts +341 -0
  55. package/src/sdk.ts +260 -0
@@ -0,0 +1,282 @@
1
+ /**
2
+ * The two-pipeline rule, reported STATICALLY - which bundler this app runs on, and the config hazards
3
+ * that only exist because nifra supports two.
4
+ *
5
+ * `loadApp` already refuses a plugin in the wrong slot ({@link ./load.ts}), and `nifra dev`/`nifra build`
6
+ * print the chosen bundler. Both of those need the app's config to be IMPORTED, which is code execution -
7
+ * something `nifra check` deliberately never does, and something an agent inspecting a repo it has not
8
+ * installed cannot do at all. So this reads the config as text instead.
9
+ *
10
+ * Text, not types, so the rules are chosen for the ones that survive being read rather than run:
11
+ *
12
+ * - Which pipeline the app is on. `chooseBuildPipeline` decides from whether the plugin slots are
13
+ * empty, and "does this file declare a non-empty `vitePlugins`" is a question the source answers.
14
+ * - The adapter-entry hazard. `nifra build` imports the adapter from `framework.ts`, or from
15
+ * `nifra.config.ts` when there is no `framework.ts`, and bundles everything that file imports into
16
+ * the production server. A Vite plugin or an SFC compiler reached that way builds cleanly and then
17
+ * dies at startup on a missing native binding. Nothing runtime-side catches it: by then the build
18
+ * has already succeeded.
19
+ * - A plugin in the wrong slot, for the subset whose import specifier names its pipeline. The load
20
+ * guard classifies by hook shape and is authoritative; this catches the same thing earlier, before
21
+ * anything is installed or started.
22
+ * - `conditions` on the Bun pipeline, which reach SSR and cannot reach the dev client bundle.
23
+ *
24
+ * Everything here degrades to silence rather than guessing. A config that computes its plugins, or
25
+ * re-exports them from elsewhere, yields `certain: false` and no findings - a static reader that
26
+ * invents a pipeline is worse than one that says it could not tell.
27
+ */
28
+ import { existsSync } from "node:fs";
29
+ import { join } from "node:path";
30
+ import { codePositionMask, stripComments } from "./check.js";
31
+ /** A plugin slot, and the pipeline it feeds. */
32
+ const SLOT_PIPELINE = {
33
+ vitePlugins: "vite",
34
+ clientPlugins: "bun",
35
+ serverPlugins: "bun",
36
+ };
37
+ const SLOTS = Object.keys(SLOT_PIPELINE);
38
+ /**
39
+ * Specifiers that carry a dev toolchain: Vite itself, a Vite/Rollup plugin, or a framework's SFC
40
+ * compiler plugin (`@nifrajs/web-vue/plugin` and friends, which import the compiler). A relative
41
+ * `./plugin` is NOT matched - a local file of that name is as likely to be the app's own tiny plugin as
42
+ * a compiler, and this rule fails a gate.
43
+ */
44
+ const DEV_TOOLCHAIN = /^vite$|^vite\/|^@vitejs\/|vite-plugin|^rollup$|^@rollup\/|^esbuild$|^(?:@[^/]+\/)?[^./][^/]*\/(?:.*\/)?plugin(?:\.ts)?$/;
45
+ /** Specifiers that name the Vite pipeline outright. */
46
+ const VITE_SPECIFIER = /^vite$|^vite\/|^@vitejs\/|vite-plugin/;
47
+ /** Specifiers whose package subpath is nifra's Bun-plugin convention (`@nifrajs/web-vue/plugin`). */
48
+ const BUN_SPECIFIER = /^(?:@[^/]+\/)?[^./][^/]*\/(?:.*\/)?plugin(?:\.ts)?$/;
49
+ const lineAt = (src, index) => {
50
+ let line = 1;
51
+ for (let i = 0; i < index && i < src.length; i++)
52
+ if (src[i] === "\n")
53
+ line++;
54
+ return line;
55
+ };
56
+ /** Local binding names introduced by one import clause (`a`, `{ b as c }`, `* as ns`). */
57
+ function localNames(clause) {
58
+ const names = [];
59
+ const braced = /\{([^}]*)\}/.exec(clause);
60
+ if (braced !== null) {
61
+ for (const part of (braced[1] ?? "").split(",")) {
62
+ const named = /([A-Za-z_$][\w$]*)\s*$/.exec(part.trim());
63
+ if (named?.[1] !== undefined)
64
+ names.push(named[1]);
65
+ }
66
+ }
67
+ const head = clause.replace(/\{[^}]*\}/, " ").replace(/,/g, " ");
68
+ const star = /\*\s*as\s+([A-Za-z_$][\w$]*)/.exec(head);
69
+ if (star?.[1] !== undefined)
70
+ names.push(star[1]);
71
+ else {
72
+ const def = /^\s*([A-Za-z_$][\w$]*)\s*$/.exec(head);
73
+ if (def?.[1] !== undefined)
74
+ names.push(def[1]);
75
+ }
76
+ return names;
77
+ }
78
+ /**
79
+ * Every value-importing binding in a module, mapped to the specifier it came from. `import type` is
80
+ * skipped: a type has no runtime cost, so it is neither a bundled toolchain nor a plugin in a slot.
81
+ */
82
+ function importedBindings(stripped) {
83
+ const out = new Map();
84
+ const re = /(?<![.\w$])import\s+(?!type[\s{])([^'";]+?)\s+from\s*['"]([^'"]+)['"]/g;
85
+ for (let m = re.exec(stripped); m !== null; m = re.exec(stripped)) {
86
+ const specifier = m[2];
87
+ if (specifier === undefined)
88
+ continue;
89
+ for (const name of localNames(m[1] ?? ""))
90
+ out.set(name, { specifier, index: m.index });
91
+ }
92
+ return out;
93
+ }
94
+ /** Every specifier a module imports for its side effects or bindings, with the position to report. */
95
+ function importedSpecifiers(stripped) {
96
+ const out = [];
97
+ const re = /(?<![.\w$])import\s+(?:(?!type[\s{])[^'";]*?\s+from\s*)?['"]([^'"]+)['"]/g;
98
+ for (let m = re.exec(stripped); m !== null; m = re.exec(stripped)) {
99
+ if (m[1] !== undefined)
100
+ out.push({ specifier: m[1], index: m.index });
101
+ }
102
+ return out;
103
+ }
104
+ /** Index just past the `]` matching the `[` at `open`, or `undefined` when it never closes. */
105
+ function closeBracket(masked, open) {
106
+ let depth = 0;
107
+ for (let i = open; i < masked.length; i++) {
108
+ const c = masked[i];
109
+ if (c === "[")
110
+ depth++;
111
+ else if (c === "]") {
112
+ depth--;
113
+ if (depth === 0)
114
+ return i;
115
+ }
116
+ }
117
+ return undefined;
118
+ }
119
+ const ABSENT = { present: false, certain: true };
120
+ /**
121
+ * Read one exported binding as a plugin slot.
122
+ *
123
+ * Only an array LITERAL is read precisely; a thunk (`() => import(…)`), a bare identifier or a
124
+ * re-export is recorded as present-but-uncertain. That asymmetry is deliberate: `[]` and `[vue()]`
125
+ * decide the pipeline, and anything else is a promise the source cannot keep.
126
+ */
127
+ function readSlot(masked, stripped, name) {
128
+ const declaration = new RegExp(`(?<![.\\w$])export\\s+(?:const|let|var)\\s+${name}\\b[^=\\n]*=\\s*`);
129
+ const m = declaration.exec(masked);
130
+ if (m !== null) {
131
+ const start = m.index + m[0].length;
132
+ if (masked[start] === "[") {
133
+ const end = closeBracket(masked, start);
134
+ if (end !== undefined) {
135
+ // Both views are offset-preserving, and each answers a different question: the mask has string
136
+ // CONTENTS blanked, so identifiers found in it are real code; the stripped source keeps them, so
137
+ // it is the one that can tell `["solid"]` from `[]`.
138
+ const code = masked.slice(start + 1, end);
139
+ const text = stripped.slice(start + 1, end);
140
+ const items = [...code.matchAll(/(?<![.\w$])([A-Za-z_$][\w$]*)/g)].map((i) => i[1] ?? "");
141
+ return { present: text.trim() !== "", certain: true, index: m.index, items };
142
+ }
143
+ }
144
+ return { present: true, certain: false, index: m.index };
145
+ }
146
+ // `export { vitePlugins } from "./plugins.ts"` - present, but its contents live in another file.
147
+ const reexport = new RegExp(`(?<![.\\w$])export\\s*\\{[^}]*\\b${name}\\b[^}]*\\}`);
148
+ const r = reexport.exec(stripped);
149
+ if (r !== null)
150
+ return { present: true, certain: false, index: r.index };
151
+ // `export * from …` could carry the slot; say so rather than reporting an absence that isn't one.
152
+ if (/(?<![.\w$])export\s*\*\s*from/.test(stripped))
153
+ return { present: false, certain: false };
154
+ return ABSENT;
155
+ }
156
+ /** Which pipeline a plugin reference belongs to, or `undefined` when its name and origin say nothing. */
157
+ function classifyRef(name, specifier) {
158
+ // nifra's own Bun plugins are named for what they are, and the name survives an alias-free import.
159
+ if (/BunPlugin$/.test(name))
160
+ return "bun";
161
+ if (specifier === undefined)
162
+ return undefined;
163
+ if (VITE_SPECIFIER.test(specifier))
164
+ return "vite";
165
+ if (BUN_SPECIFIER.test(specifier))
166
+ return "bun";
167
+ return undefined;
168
+ }
169
+ /** Read one file as text, or `undefined` when it is missing or unreadable. */
170
+ async function readSource(path) {
171
+ try {
172
+ return await Bun.file(path).text();
173
+ }
174
+ catch {
175
+ return undefined;
176
+ }
177
+ }
178
+ /**
179
+ * Report the pipeline and its config hazards for the app at `cwd`, without executing anything.
180
+ * Total: a missing or unreadable config yields `ran: false`, never a throw.
181
+ */
182
+ export async function collectPipelineReport(cwd) {
183
+ const configFile = existsSync(join(cwd, "nifra.config.ts")) ? "nifra.config.ts" : "framework.ts";
184
+ const source = await readSource(join(cwd, configFile));
185
+ if (source === undefined) {
186
+ return {
187
+ ran: false,
188
+ pipeline: "unknown",
189
+ reason: "no nifra.config.ts or framework.ts here",
190
+ certain: false,
191
+ findings: [],
192
+ };
193
+ }
194
+ const masked = codePositionMask(source);
195
+ const stripped = stripComments(source);
196
+ const bindings = importedBindings(stripped);
197
+ const slots = Object.fromEntries(SLOTS.map((slot) => [slot, readSlot(masked, stripped, slot)]));
198
+ const findings = [];
199
+ // A plugin whose specifier names the other pipeline. The load-time guard classifies by hook shape and
200
+ // remains the authority; this is the half of it that can run on a repo nobody has installed yet.
201
+ for (const slot of SLOTS) {
202
+ const state = slots[slot];
203
+ const expected = SLOT_PIPELINE[slot];
204
+ for (const item of state.items ?? []) {
205
+ const binding = bindings.get(item);
206
+ const actual = classifyRef(item, binding?.specifier);
207
+ if (actual === undefined || actual === expected)
208
+ continue;
209
+ const from = binding !== undefined ? ` (imported from "${binding.specifier}")` : "";
210
+ findings.push({
211
+ rule: "plugin-slot",
212
+ severity: "error",
213
+ file: configFile,
214
+ line: lineAt(source, state.index ?? 0),
215
+ message: `\`${item}\`${from} is a ${actual === "vite" ? "Vite" : "Bun"} plugin but sits in \`${slot}\`, which feeds ` +
216
+ `${expected === "vite" ? "Vite" : "Bun.build"}. The wrong bundler never calls its hooks, so the transform silently does not run and the build still succeeds.`,
217
+ fix: actual === "vite"
218
+ ? `move \`${item}\` to \`vitePlugins\``
219
+ : `move \`${item}\` to \`clientPlugins\` (client bundle) or \`serverPlugins\` (SSR)`,
220
+ });
221
+ }
222
+ }
223
+ // Which bundler this app gets, by the same rule `chooseBuildPipeline` applies to the loaded config.
224
+ const viteOnly = slots.vitePlugins.present && !slots.clientPlugins.present && !slots.serverPlugins.present;
225
+ const certain = SLOTS.every((slot) => slots[slot].certain);
226
+ const pipeline = viteOnly ? "vite" : "bun";
227
+ const reason = viteOnly
228
+ ? "auto: this app's only transforms are `vitePlugins`, which the Bun build cannot run"
229
+ : slots.clientPlugins.present || slots.serverPlugins.present
230
+ ? "default: this app declares Bun plugins, so both phases stay on Bun"
231
+ : "default: no transforms to place, so both phases stay on Bun";
232
+ // The adapter entry is bundled into every `nifra build` server entry. Whatever it imports goes with it.
233
+ const adapterEntry = existsSync(join(cwd, "framework.ts")) ? "framework.ts" : configFile;
234
+ const entrySource = adapterEntry === configFile ? source : await readSource(join(cwd, adapterEntry));
235
+ if (entrySource !== undefined) {
236
+ const seen = new Set();
237
+ for (const { specifier, index } of importedSpecifiers(stripComments(entrySource))) {
238
+ if (!DEV_TOOLCHAIN.test(specifier) || seen.has(specifier))
239
+ continue;
240
+ seen.add(specifier);
241
+ findings.push({
242
+ rule: "adapter-entry",
243
+ severity: "error",
244
+ file: adapterEntry,
245
+ line: lineAt(entrySource, index),
246
+ message: `${adapterEntry} imports "${specifier}", and \`nifra build\` imports the adapter from ${adapterEntry} - ` +
247
+ "so the dev toolchain is bundled into the production server entry. The build succeeds and the server then fails at startup on a dependency of the bundler (a missing native binding, typically), which reads like a broken install rather than a config split.",
248
+ fix: adapterEntry === "framework.ts"
249
+ ? 'move "' +
250
+ specifier +
251
+ '" to `nifra.config.ts`, which only the CLI imports, and keep `framework.ts` to the adapter'
252
+ : 'add a `framework.ts` exporting just the adapter, re-export it from `nifra.config.ts` (`export { adapter } from "./framework"`), and leave the toolchain imports in the config',
253
+ });
254
+ }
255
+ }
256
+ // `conditions` reach SSR on the Bun pipeline and cannot reach the client bundle Bun's dev server
257
+ // serves - it takes no resolve conditions from bunfig or anywhere else. `nifra dev` says so at
258
+ // startup; a project whose CI only runs `nifra check` would otherwise never hear it.
259
+ const conditions = readSlot(masked, stripped, "conditions");
260
+ if (conditions.present && pipeline === "bun") {
261
+ findings.push({
262
+ rule: "bun-client-conditions",
263
+ severity: "warning",
264
+ file: configFile,
265
+ line: lineAt(source, conditions.index ?? 0),
266
+ message: "`conditions` are honoured by SSR and by `nifra build`, but Bun's dev-server bundler accepts no resolve conditions - so under `nifra dev` a package with an `exports` map can resolve to one file in the browser and another everywhere else.",
267
+ fix: "run `nifra dev --vite` when the client bundle must resolve exactly as production does",
268
+ });
269
+ }
270
+ return {
271
+ ran: true,
272
+ pipeline: certain ? pipeline : "unknown",
273
+ reason: certain
274
+ ? reason
275
+ : "the config states its plugins indirectly (a thunk, an identifier or a re-export), so the bundler can only be read by loading it - `nifra dev` and `nifra build` print the real one",
276
+ certain,
277
+ configFile,
278
+ adapterEntry,
279
+ findings,
280
+ };
281
+ }
282
+ //# sourceMappingURL=pipeline-report.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pipeline-report.js","sourceRoot":"","sources":["../src/pipeline-report.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAG5D,gDAAgD;AAChD,MAAM,aAAa,GAAG;IACpB,WAAW,EAAE,MAAM;IACnB,aAAa,EAAE,KAAK;IACpB,aAAa,EAAE,KAAK;CACsC,CAAA;AAI5D,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,aAAa,CAAoB,CAAA;AA+B3D;;;;;GAKG;AACH,MAAM,aAAa,GACjB,yHAAyH,CAAA;AAE3H,uDAAuD;AACvD,MAAM,cAAc,GAAG,uCAAuC,CAAA;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YAAY;QACZ,QAAQ;KACT,CAAA;AACH,CAAC"}
package/dist/sdk.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { type OpenAPIDocument } from "@nifrajs/schema/openapi";
2
+ export type SdkLanguage = "python" | "go";
3
+ /** Render a generated SDK. Python uses the standard library; Go uses net/http. */
4
+ export declare function renderSdk(document: OpenAPIDocument, language: SdkLanguage): string;
5
+ /** Load `backend.ts`, generate an SDK, and write it to the project. */
6
+ export declare function runSdk(cwd: string, options: {
7
+ readonly language: SdkLanguage;
8
+ readonly out?: string;
9
+ }): Promise<void>;
10
+ //# sourceMappingURL=sdk.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../src/sdk.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,eAAe,EAAa,MAAM,yBAAyB,CAAA;AAEzE,MAAM,MAAM,WAAW,GAAG,QAAQ,GAAG,IAAI,CAAA;AAoOzC,kFAAkF;AAClF,wBAAgB,SAAS,CAAC,QAAQ,EAAE,eAAe,EAAE,QAAQ,EAAE,WAAW,GAAG,MAAM,CAElF;AAED,uEAAuE;AACvE,wBAAsB,MAAM,CAC1B,GAAG,EAAE,MAAM,EACX,OAAO,EAAE;IAAE,QAAQ,CAAC,QAAQ,EAAE,WAAW,CAAC;IAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,GACjE,OAAO,CAAC,IAAI,CAAC,CAiBf"}
package/dist/sdk.js ADDED
@@ -0,0 +1,229 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ /** Deterministic, dependency-free SDK generation from the backend's OpenAPI contract. */
10
+ import { existsSync } from "node:fs";
11
+ import { basename, resolve } from "node:path";
12
+ import { toOpenAPI } from "@nifrajs/schema/openapi";
13
+ const HTTP_METHODS = ["get", "post", "put", "patch", "delete", "head", "options"];
14
+ function operations(document) {
15
+ const result = [];
16
+ for (const [path, item] of Object.entries(document.paths).sort(([a], [b]) => a.localeCompare(b))) {
17
+ for (const method of HTTP_METHODS) {
18
+ const operation = item[method];
19
+ if (operation !== null && typeof operation === "object") {
20
+ result.push({ method, path, operation: operation });
21
+ }
22
+ }
23
+ }
24
+ return result;
25
+ }
26
+ function identifier(value, fallback) {
27
+ const startsWithDigit = /^\d/.test(value);
28
+ const normalized = value
29
+ .replace(/[^A-Za-z0-9_]+/g, "_")
30
+ .replace(/_+/g, "_")
31
+ .replace(/^_+|_+$/g, "");
32
+ const safe = startsWithDigit ? `_${normalized}` : normalized;
33
+ return safe === "" || safe === "_" ? fallback : safe;
34
+ }
35
+ function operationName(operation, method, path) {
36
+ return identifier(operation.operationId ?? `${method}_${path}`, `${method}_request`);
37
+ }
38
+ function uniqueNames(items) {
39
+ const counts = new Map();
40
+ return items.map((item) => {
41
+ const count = (counts.get(item) ?? 0) + 1;
42
+ counts.set(item, count);
43
+ return count === 1 ? item : `${item}_${count}`;
44
+ });
45
+ }
46
+ function pathParameters(path) {
47
+ return [...path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]).filter(Boolean);
48
+ }
49
+ function pythonSdk(document) {
50
+ const entries = operations(document);
51
+ const names = uniqueNames(entries.map(({ method, path, operation }) => operationName(operation, method, path)));
52
+ const methods = [];
53
+ entries.forEach(({ method, path, operation }, index) => {
54
+ const name = names[index];
55
+ const pathParams = pathParameters(path);
56
+ const queryParams = (operation.parameters ?? []).filter((parameter) => parameter.in === "query");
57
+ const used = new Set(["self", "body", ...pathParams]);
58
+ const queryNames = queryParams.map((parameter) => {
59
+ let value = identifier(parameter.name, "query");
60
+ while (used.has(value))
61
+ value += "_";
62
+ used.add(value);
63
+ return value;
64
+ });
65
+ const args = pathParams.map((parameter) => `${identifier(parameter, "param")}: Any`);
66
+ const keywordArgs = queryParams.map((parameter, queryIndex) => {
67
+ const required = parameter.required ? "" : " = None";
68
+ return `${queryNames[queryIndex]}: Any${required}`;
69
+ });
70
+ if (operation.requestBody !== undefined)
71
+ keywordArgs.push("body: Any = None");
72
+ const signature = [...args, ...(keywordArgs.length > 0 ? ["*", ...keywordArgs] : [])].join(", ");
73
+ const query = queryNames.length === 0
74
+ ? "None"
75
+ : `{${queryNames.map((value) => `${JSON.stringify(value)}: ${value}`).join(", ")}}`;
76
+ const paths = pathParams.length === 0
77
+ ? "None"
78
+ : `{${pathParams.map((value) => `${JSON.stringify(value)}: ${identifier(value, "param")}`).join(", ")}}`;
79
+ const body = operation.requestBody === undefined ? "None" : "body";
80
+ methods.push(` def ${name}(self${signature ? `, ${signature}` : ""}) -> Any:\n` +
81
+ ` return self._request(${JSON.stringify(method.toUpperCase())}, ${JSON.stringify(path)}, path_params=${paths}, query=${query}, body=${body})`);
82
+ });
83
+ return `# Generated by nifra. Regenerate with: nifra sdk --lang python
84
+ from __future__ import annotations
85
+
86
+ import json
87
+ import urllib.error
88
+ import urllib.parse
89
+ import urllib.request
90
+ from typing import Any, Mapping
91
+
92
+
93
+ class NifraApiError(RuntimeError):
94
+ def __init__(self, status: int, body: Any):
95
+ super().__init__(f"Nifra API request failed with HTTP {status}")
96
+ self.status = status
97
+ self.body = body
98
+
99
+
100
+ class Client:
101
+ def __init__(self, base_url: str, headers: Mapping[str, str] | None = None, timeout: float = 30.0):
102
+ self.base_url = base_url.rstrip("/")
103
+ self.headers = dict(headers or {})
104
+ self.timeout = timeout
105
+
106
+ def _request(self, method: str, path: str, *, path_params: Mapping[str, Any] | None, query: Mapping[str, Any] | None, body: Any) -> Any:
107
+ route = path
108
+ for key, value in (path_params or {}).items():
109
+ route = route.replace("{" + key + "}", urllib.parse.quote(str(value), safe=""))
110
+ params = [(key, value) for key, value in (query or {}).items() if value is not None]
111
+ url = self.base_url + route
112
+ if params:
113
+ url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params, doseq=True)
114
+ payload = None if body is None else json.dumps(body).encode("utf-8")
115
+ request = urllib.request.Request(url, data=payload, method=method, headers=self.headers)
116
+ if payload is not None:
117
+ request.add_header("Content-Type", "application/json")
118
+ try:
119
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
120
+ raw = response.read()
121
+ return json.loads(raw) if raw else None
122
+ except urllib.error.HTTPError as error:
123
+ raw = error.read()
124
+ try:
125
+ value = json.loads(raw) if raw else None
126
+ except json.JSONDecodeError:
127
+ value = raw.decode("utf-8", errors="replace")
128
+ raise NifraApiError(error.code, value) from error
129
+
130
+ ${methods.length === 0 ? " pass" : methods.join("\n\n")}
131
+ `;
132
+ }
133
+ function goExportName(value) {
134
+ const name = identifier(value, "Request");
135
+ return name[0].toUpperCase() + name.slice(1);
136
+ }
137
+ function goSdk(document) {
138
+ const entries = operations(document);
139
+ const names = uniqueNames(entries.map(({ method, path, operation }) => operationName(operation, method, path)));
140
+ const methods = [];
141
+ entries.forEach(({ method, path }, index) => {
142
+ const pathParams = pathParameters(path);
143
+ const args = pathParams.map((parameter) => `${identifier(parameter, "param")} string`);
144
+ args.push("query url.Values", "body any");
145
+ const pathMap = pathParams.length === 0
146
+ ? "nil"
147
+ : `map[string]string{${pathParams.map((value) => `${JSON.stringify(value)}: ${identifier(value, "param")}`).join(", ")}}`;
148
+ methods.push(`func (c *Client) ${goExportName(names[index])}(${args.join(", ")}) (any, error) {\n` +
149
+ ` return c.request(http.Method${method[0].toUpperCase()}${method.slice(1)}, ${JSON.stringify(path)}, ${pathMap}, query, body)\n` +
150
+ `}`);
151
+ });
152
+ return `// Code generated by nifra. Regenerate with: nifra sdk --lang go
153
+ package nifrasdk
154
+
155
+ import (
156
+ "bytes"
157
+ "encoding/json"
158
+ "fmt"
159
+ "io"
160
+ "net/http"
161
+ "net/url"
162
+ "strings"
163
+ )
164
+
165
+ type Client struct {
166
+ BaseURL string
167
+ HTTP *http.Client
168
+ Headers http.Header
169
+ }
170
+
171
+ func NewClient(baseURL string) *Client {
172
+ return &Client{BaseURL: strings.TrimRight(baseURL, "/"), HTTP: http.DefaultClient, Headers: make(http.Header)}
173
+ }
174
+
175
+ func (c *Client) request(method, path string, pathParams map[string]string, query url.Values, body any) (any, error) {
176
+ route := path
177
+ for key, value := range pathParams {
178
+ route = strings.ReplaceAll(route, "{"+key+"}", url.PathEscape(value))
179
+ }
180
+ target := c.BaseURL + route
181
+ parsed, err := url.Parse(target)
182
+ if err != nil { return nil, err }
183
+ parsed.RawQuery = query.Encode()
184
+ var reader io.Reader
185
+ if body != nil {
186
+ payload, err := json.Marshal(body)
187
+ if err != nil { return nil, err }
188
+ reader = bytes.NewReader(payload)
189
+ }
190
+ request, err := http.NewRequest(method, parsed.String(), reader)
191
+ if err != nil { return nil, err }
192
+ for key, values := range c.Headers { for _, value := range values { request.Header.Add(key, value) } }
193
+ if body != nil { request.Header.Set("Content-Type", "application/json") }
194
+ response, err := c.HTTP.Do(request)
195
+ if err != nil { return nil, err }
196
+ defer response.Body.Close()
197
+ raw, err := io.ReadAll(response.Body)
198
+ if err != nil { return nil, err }
199
+ var value any
200
+ if len(raw) > 0 { if err := json.Unmarshal(raw, &value); err != nil { value = string(raw) } }
201
+ if response.StatusCode < 200 || response.StatusCode >= 300 { return nil, fmt.Errorf("nifra API request failed with HTTP %d: %v", response.StatusCode, value) }
202
+ return value, nil
203
+ }
204
+
205
+ ${methods.length === 0 ? "// No operations were found.\n" : `${methods.join("\n\n")}\n`}`;
206
+ }
207
+ /** Render a generated SDK. Python uses the standard library; Go uses net/http. */
208
+ export function renderSdk(document, language) {
209
+ return language === "python" ? pythonSdk(document) : goSdk(document);
210
+ }
211
+ /** Load `backend.ts`, generate an SDK, and write it to the project. */
212
+ export async function runSdk(cwd, options) {
213
+ const backendPath = resolve(cwd, "backend.ts");
214
+ if (!existsSync(backendPath)) {
215
+ throw new Error(`[nifra] no backend.ts in ${cwd} - SDK generation needs the API contract.`);
216
+ }
217
+ const backend = (await import(__rewriteRelativeImportExtension(backendPath))).backend;
218
+ if (backend === undefined)
219
+ throw new Error(`[nifra] ${backendPath} does not export \`backend\`.`);
220
+ const document = toOpenAPI(backend, {
221
+ title: `${basename(cwd)} API`,
222
+ version: "1.0.0",
223
+ });
224
+ const extension = options.language === "python" ? "py" : "go";
225
+ const out = resolve(cwd, options.out ?? `nifra_sdk.${extension}`);
226
+ await Bun.write(out, renderSdk(document, options.language));
227
+ console.log(`[nifra] wrote ${options.language} SDK with ${Object.keys(document.paths).length} path${Object.keys(document.paths).length === 1 ? "" : "s"} to ${out}`);
228
+ }
229
+ //# sourceMappingURL=sdk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../src/sdk.ts"],"names":[],"mappings":";;;;;;;;AAAA,yFAAyF;AACzF,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAC7C,OAAO,EAAwB,SAAS,EAAE,MAAM,yBAAyB,CAAA;AAczE,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,CAAU,CAAA;AAE1F,SAAS,UAAU,CACjB,QAAyB;IAEzB,MAAM,MAAM,GAAiE,EAAE,CAAA;IAC/E,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAC1E,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,CACnB,EAAE,CAAC;QACF,KAAK,MA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