@shdwsdk/cli 1.2.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/wizard.ts CHANGED
@@ -1,267 +1,266 @@
1
- // ============================================================================
2
- // @shdwsdk/cli — Interactive Setup Wizard (npx @shdwsdk/sdk init / npx shdw-init)
3
- // ============================================================================
4
-
5
- import { stdin as defaultInput, stdout as defaultOutput } from "node:process";
6
- import { createInterface } from "node:readline/promises";
7
- import {
8
- GRID_REGION_FACTORS,
9
- MODEL_ENERGY_COEFFICIENTS,
10
- resolveGridRegionFactor,
11
- resolveModelCoefficient,
12
- } from "@shdwsdk/sdk";
13
- import { generateShdwBoilerplateFile } from "./codegen.js";
14
- import {
15
- DEFAULT_SHDW_INGEST_ENDPOINT,
16
- testShdwConnectivity,
17
- type ConnectivityTestResult,
18
- } from "./connectivity.js";
19
- import { injectShdwEnvVariables } from "./env.js";
20
-
21
- export interface CliWizardOptions {
22
- cwd?: string;
23
- apiKey?: string;
24
- region?: string;
25
- model?: string;
26
- outputPath?: string;
27
- endpoint?: string;
28
- skipPing?: boolean;
29
- customFetch?: typeof fetch;
30
- }
31
-
32
- export interface CliWizardResult {
33
- apiKeyPrefix: string;
34
- gridRegion: string;
35
- modelPattern: string;
36
- envFilePath: string;
37
- boilerplateFilePath: string;
38
- connectivity: ConnectivityTestResult | null;
39
- }
40
-
41
- export function parseCliArgs(argv: readonly string[]): CliWizardOptions & {
42
- help?: boolean;
43
- } {
44
- const opts: CliWizardOptions & { help?: boolean } = {};
45
- for (let i = 0; i < argv.length; i++) {
46
- const arg = argv[i];
47
- if (arg === "--help" || arg === "-h") {
48
- opts.help = true;
49
- } else if (arg === "--skip-ping") {
50
- opts.skipPing = true;
51
- } else if (arg === "--api-key" && argv[i + 1]) {
52
- opts.apiKey = argv[++i];
53
- } else if (arg === "--region" && argv[i + 1]) {
54
- opts.region = argv[++i];
55
- } else if (arg === "--model" && argv[i + 1]) {
56
- opts.model = argv[++i];
57
- } else if ((arg === "--out" || arg === "--output") && argv[i + 1]) {
58
- opts.outputPath = argv[++i];
59
- } else if (arg === "--endpoint" && argv[i + 1]) {
60
- opts.endpoint = argv[++i];
61
- }
62
- }
63
- return opts;
64
- }
65
-
66
- function printHelp(): void {
67
- defaultOutput.write(`
68
- SHDWsdk (@shdwsdk/sdk) Interactive Setup Wizard
69
-
70
- Usage:
71
- npx @shdwsdk/sdk init
72
- npx shdw-init
73
-
74
- Options:
75
- --api-key <key> SHDW API key (shdw_live_*)
76
- --region <region> Primary cloud datacenter region (e.g., us-west-2, eu-north-1)
77
- --model <pattern> Primary AI model pattern (e.g., claude-3-7-sonnet, gpt-4o, gemini-2.5-pro)
78
- --out <path> Boilerplate output path (default: src/lib/shdw.ts)
79
- --endpoint <url> Custom telemetry ingest URL (default: ${DEFAULT_SHDW_INGEST_ENDPOINT})
80
- --skip-ping Skip the live connectivity validation ping
81
- -h, --help Show this help message
82
- `);
83
- }
84
-
85
- export async function runInitWizard(
86
- options: CliWizardOptions = {}
87
- ): Promise<CliWizardResult> {
88
- const cwd = options.cwd ?? process.cwd();
89
- const regions = Object.values(GRID_REGION_FACTORS);
90
- const models = [...MODEL_ENERGY_COEFFICIENTS];
91
-
92
- const needsInteractive =
93
- !options.apiKey || !options.region || !options.model || !options.outputPath;
94
-
95
- const rl = needsInteractive
96
- ? createInterface({ input: defaultInput, output: defaultOutput })
97
- : null;
98
-
99
- try {
100
- if (needsInteractive) {
101
- defaultOutput.write(
102
- "\n=== SHDWsdk (@shdwsdk/sdk) Setup Wizard — Scope 3 Carbon & AI-BOM ===\n\n"
103
- );
104
- }
105
-
106
- // 1. Prompt for SHDW API Key (shdw_live_*)
107
- let apiKey = options.apiKey?.trim() ?? "";
108
- while (!apiKey && rl) {
109
- const answer = await rl.question(
110
- "1. Enter your SHDW API key (shdw_live_*): "
111
- );
112
- const trimmed = answer.trim();
113
- if (trimmed.length < 12) {
114
- defaultOutput.write(
115
- " Invalid API key. Please enter a valid key (at least 12 characters, e.g., shdw_live_...).\n"
116
- );
117
- continue;
118
- }
119
- if (!trimmed.startsWith("shdw_live_") && !trimmed.startsWith("shdw_test_")) {
120
- defaultOutput.write(
121
- " Note: Production keys typically start with 'shdw_live_'. Proceeding with provided key.\n"
122
- );
123
- }
124
- apiKey = trimmed;
125
- }
126
-
127
- // 2. Select Primary Cloud Data Center Region
128
- let selectedRegion = options.region?.trim() ?? "";
129
- if (!selectedRegion && rl) {
130
- defaultOutput.write(
131
- "\n2. Select your primary cloud data center region:\n"
132
- );
133
- regions.forEach((r, idx) => {
134
- defaultOutput.write(
135
- ` [${idx + 1}] ${r.region.padEnd(16)} — ${r.displayName} (${r.intensityGco2PerKwh} gCO2e/kWh)\n`
136
- );
137
- });
138
- const defaultIdx = regions.findIndex((r) => r.region === "us-west-2") + 1;
139
- const answer = await rl.question(
140
- ` Choose region number or code [default: ${defaultIdx} (us-west-2)]: `
141
- );
142
- const trimmed = answer.trim();
143
- if (!trimmed) {
144
- selectedRegion = "us-west-2";
145
- } else {
146
- const num = Number(trimmed);
147
- if (Number.isInteger(num) && num >= 1 && num <= regions.length) {
148
- selectedRegion = regions[num - 1]?.region ?? "us-west-2";
149
- } else {
150
- selectedRegion = resolveGridRegionFactor(trimmed).region;
151
- }
152
- }
153
- }
154
- const resolvedRegion = resolveGridRegionFactor(
155
- selectedRegion || "us-west-2"
156
- );
157
-
158
- // 3. Select Primary AI Model Pattern
159
- let selectedModel = options.model?.trim() ?? "";
160
- if (!selectedModel && rl) {
161
- defaultOutput.write("\n3. Select your primary AI model in production:\n");
162
- models.forEach((m, idx) => {
163
- defaultOutput.write(
164
- ` [${idx + 1}] ${m.modelPattern.padEnd(22)} — ${m.displayName}\n`
165
- );
166
- });
167
- const answer = await rl.question(
168
- " Choose model number or pattern [default: 1 (claude-3-7-sonnet)]: "
169
- );
170
- const trimmed = answer.trim();
171
- if (!trimmed) {
172
- selectedModel = "claude-3-7-sonnet";
173
- } else {
174
- const num = Number(trimmed);
175
- if (Number.isInteger(num) && num >= 1 && num <= models.length) {
176
- selectedModel = models[num - 1]?.modelPattern ?? "claude-3-7-sonnet";
177
- } else {
178
- selectedModel = trimmed;
179
- }
180
- }
181
- }
182
- const resolvedModel = resolveModelCoefficient(
183
- selectedModel || "claude-3-7-sonnet"
184
- );
185
- const effectiveModelPattern =
186
- resolvedModel.modelPattern === "default-frontier" && selectedModel
187
- ? selectedModel
188
- : resolvedModel.modelPattern;
189
-
190
- // 4. Output Path for Boilerplate File
191
- let outputPath = options.outputPath?.trim() ?? "";
192
- if (!outputPath && rl) {
193
- const answer = await rl.question(
194
- "\n4. Boilerplate integration file path [default: src/lib/shdw.ts]: "
195
- );
196
- outputPath = answer.trim() || "src/lib/shdw.ts";
197
- }
198
- if (!outputPath) {
199
- outputPath = "src/lib/shdw.ts";
200
- }
201
-
202
- // 5. Environment File Injection (.env / .env.local)
203
- const envResult = injectShdwEnvVariables({
204
- cwd,
205
- apiKey,
206
- gridRegion: resolvedRegion.region,
207
- });
208
- defaultOutput.write(
209
- `\n[1/3] ${envResult.createdNew ? "Created" : "Updated"} ${envResult.fileName} (${envResult.filePath})\n`
210
- );
211
-
212
- // 6. Boilerplate Code Generation
213
- const codeResult = generateShdwBoilerplateFile({
214
- cwd,
215
- outputPath,
216
- modelPattern: effectiveModelPattern,
217
- gridRegion: resolvedRegion.region,
218
- });
219
- defaultOutput.write(
220
- `[2/3] Generated ${codeResult.providerLabel} integration at ${codeResult.relativePath}\n`
221
- );
222
-
223
- // 7. Live Connectivity Test (<= 1500ms AbortController timeout)
224
- let connectivity: ConnectivityTestResult | null = null;
225
- if (!options.skipPing) {
226
- defaultOutput.write(
227
- "[3/3] Testing live connectivity (1500ms timeout guard)...\n"
228
- );
229
- connectivity = await testShdwConnectivity({
230
- apiKey,
231
- modelPattern: effectiveModelPattern,
232
- gridRegion: resolvedRegion.region,
233
- endpoint: options.endpoint,
234
- timeoutMs: 1500,
235
- customFetch: options.customFetch,
236
- });
237
- defaultOutput.write(
238
- ` ${connectivity.ok ? "OK:" : "WARN:"} ${connectivity.message}\n`
239
- );
240
- }
241
-
242
- defaultOutput.write(
243
- `\nSetup complete. Import your wrapped AI client from "./${codeResult.relativePath.replace(/\.ts$/, "")}" to begin tracking Scope 3 carbon & AI-BOM lineage.\n\n`
244
- );
245
-
246
- return {
247
- apiKeyPrefix: apiKey.slice(0, 14),
248
- gridRegion: resolvedRegion.region,
249
- modelPattern: effectiveModelPattern,
250
- envFilePath: envResult.filePath,
251
- boilerplateFilePath: codeResult.filePath,
252
- connectivity,
253
- };
254
- } finally {
255
- rl?.close();
256
- }
257
- }
258
-
259
- export async function runCliFromArgv(argv: readonly string[]): Promise<void> {
260
- const cleaned = argv[0] === "init" ? argv.slice(1) : argv;
261
- const parsed = parseCliArgs(cleaned);
262
- if (parsed.help) {
263
- printHelp();
264
- return;
265
- }
266
- await runInitWizard(parsed);
267
- }
1
+ // ============================================================================
2
+ // @shdwsdk/cli — Interactive Setup Wizard (npx @shdwsdk/sdk init / npx shdw-init)
3
+ // ============================================================================
4
+
5
+ import { stdin as defaultInput, stdout as defaultOutput } from "node:process";
6
+ import { createInterface } from "node:readline/promises";
7
+ import {
8
+ GRID_REGION_FACTORS,
9
+ MODEL_ENERGY_COEFFICIENTS,
10
+ resolveGridRegionFactor,
11
+ resolveModelCoefficient,
12
+ } from "@shdwsdk/sdk";
13
+ import { generateShdwBoilerplateFile } from "./codegen.js";
14
+ import {
15
+ DEFAULT_SHDW_INGEST_ENDPOINT,
16
+ testShdwConnectivity,
17
+ type ConnectivityTestResult,
18
+ } from "./connectivity.js";
19
+ import { injectShdwEnvVariables } from "./env.js";
20
+
21
+ export interface CliWizardOptions {
22
+ cwd?: string;
23
+ apiKey?: string;
24
+ region?: string;
25
+ model?: string;
26
+ outputPath?: string;
27
+ endpoint?: string;
28
+ skipPing?: boolean;
29
+ customFetch?: typeof fetch;
30
+ }
31
+
32
+ export interface CliWizardResult {
33
+ apiKeyPrefix: string;
34
+ gridRegion: string;
35
+ modelPattern: string;
36
+ envFilePath: string;
37
+ boilerplateFilePath: string;
38
+ connectivity: ConnectivityTestResult | null;
39
+ }
40
+
41
+ export function parseCliArgs(argv: readonly string[]): CliWizardOptions & {
42
+ help?: boolean;
43
+ } {
44
+ const opts: CliWizardOptions & { help?: boolean } = {};
45
+ for (let i = 0; i < argv.length; i++) {
46
+ const arg = argv[i];
47
+ if (arg === "--help" || arg === "-h") {
48
+ opts.help = true;
49
+ } else if (arg === "--skip-ping") {
50
+ opts.skipPing = true;
51
+ } else if (arg === "--api-key" && argv[i + 1]) {
52
+ opts.apiKey = argv[++i];
53
+ } else if (arg === "--region" && argv[i + 1]) {
54
+ opts.region = argv[++i];
55
+ } else if (arg === "--model" && argv[i + 1]) {
56
+ opts.model = argv[++i];
57
+ } else if ((arg === "--out" || arg === "--output") && argv[i + 1]) {
58
+ opts.outputPath = argv[++i];
59
+ } else if (arg === "--endpoint" && argv[i + 1]) {
60
+ opts.endpoint = argv[++i];
61
+ }
62
+ }
63
+ return opts;
64
+ }
65
+
66
+ function printHelp(): void {
67
+ defaultOutput.write(`
68
+ SHDWsdk (@shdwsdk/sdk) Interactive Setup Wizard
69
+
70
+ Usage:
71
+ npx @shdwsdk/sdk init
72
+ npx shdw-init
73
+
74
+ Options:
75
+ --api-key <key> SHDW API key (shdw_live_*)
76
+ --region <region> Primary cloud datacenter region (e.g., us-west-2, eu-north-1)
77
+ --model <pattern> Primary AI model id (e.g., claude-sonnet-5-5, gpt-6.1-sol, gemini-3.8-flash)
78
+ --out <path> Boilerplate output path (default: src/lib/shdw.ts)
79
+ --endpoint <url> Custom telemetry ingest URL (default: ${DEFAULT_SHDW_INGEST_ENDPOINT})
80
+ --skip-ping Skip the live connectivity validation ping
81
+ -h, --help Show this help message
82
+ `);
83
+ }
84
+
85
+ export async function runInitWizard(
86
+ options: CliWizardOptions = {}
87
+ ): Promise<CliWizardResult> {
88
+ const cwd = options.cwd ?? process.cwd();
89
+ const regions = Object.values(GRID_REGION_FACTORS);
90
+ const models = [...MODEL_ENERGY_COEFFICIENTS];
91
+
92
+ const needsInteractive =
93
+ !options.apiKey || !options.region || !options.model || !options.outputPath;
94
+
95
+ const rl = needsInteractive
96
+ ? createInterface({ input: defaultInput, output: defaultOutput })
97
+ : null;
98
+
99
+ try {
100
+ if (needsInteractive) {
101
+ defaultOutput.write(
102
+ "\n=== SHDWsdk (@shdwsdk/sdk) Setup Wizard — Scope 3 Carbon & AI-BOM ===\n\n"
103
+ );
104
+ }
105
+
106
+ // 1. Prompt for SHDW API Key (shdw_live_*)
107
+ let apiKey = options.apiKey?.trim() ?? "";
108
+ while (!apiKey && rl) {
109
+ const answer = await rl.question(
110
+ "1. Enter your SHDW API key (shdw_live_*): "
111
+ );
112
+ const trimmed = answer.trim();
113
+ if (trimmed.length < 12) {
114
+ defaultOutput.write(
115
+ " Invalid API key. Please enter a valid key (at least 12 characters, e.g., shdw_live_...).\n"
116
+ );
117
+ continue;
118
+ }
119
+ if (!trimmed.startsWith("shdw_live_") && !trimmed.startsWith("shdw_test_")) {
120
+ defaultOutput.write(
121
+ " Note: Production keys typically start with 'shdw_live_'. Proceeding with provided key.\n"
122
+ );
123
+ }
124
+ apiKey = trimmed;
125
+ }
126
+
127
+ // 2. Select Primary Cloud Data Center Region
128
+ let selectedRegion = options.region?.trim() ?? "";
129
+ if (!selectedRegion && rl) {
130
+ defaultOutput.write(
131
+ "\n2. Select your primary cloud data center region:\n"
132
+ );
133
+ regions.forEach((r, idx) => {
134
+ defaultOutput.write(
135
+ ` [${idx + 1}] ${r.region.padEnd(16)} — ${r.displayName} (${r.intensityGco2PerKwh} gCO2e/kWh)\n`
136
+ );
137
+ });
138
+ const defaultIdx = regions.findIndex((r) => r.region === "us-west-2") + 1;
139
+ const answer = await rl.question(
140
+ ` Choose region number or code [default: ${defaultIdx} (us-west-2)]: `
141
+ );
142
+ const trimmed = answer.trim();
143
+ if (!trimmed) {
144
+ selectedRegion = "us-west-2";
145
+ } else {
146
+ const num = Number(trimmed);
147
+ if (Number.isInteger(num) && num >= 1 && num <= regions.length) {
148
+ selectedRegion = regions[num - 1]?.region ?? "us-west-2";
149
+ } else {
150
+ selectedRegion = resolveGridRegionFactor(trimmed).region;
151
+ }
152
+ }
153
+ }
154
+ const resolvedRegion = resolveGridRegionFactor(
155
+ selectedRegion || "us-west-2"
156
+ );
157
+
158
+ // 3. Select Primary AI Model Pattern
159
+ let selectedModel = options.model?.trim() ?? "";
160
+ if (!selectedModel && rl) {
161
+ defaultOutput.write("\n3. Select your primary AI model in production:\n");
162
+ models.forEach((m, idx) => {
163
+ defaultOutput.write(
164
+ ` [${idx + 1}] ${m.modelPattern.padEnd(22)} — ${m.displayName}\n`
165
+ );
166
+ });
167
+ const answer = await rl.question(
168
+ ` Choose model number or id [default: 1 (${models[0]?.modelPattern ?? "claude-sonnet-5-5"})]: `
169
+ );
170
+ const trimmed = answer.trim();
171
+ if (!trimmed) {
172
+ selectedModel = models[0]?.modelPattern ?? "claude-sonnet-5-5";
173
+ } else {
174
+ const num = Number(trimmed);
175
+ if (Number.isInteger(num) && num >= 1 && num <= models.length) {
176
+ selectedModel = models[num - 1]?.modelPattern ?? "claude-sonnet-5-5";
177
+ } else {
178
+ selectedModel = trimmed;
179
+ }
180
+ }
181
+ }
182
+ const resolvedModel = resolveModelCoefficient(
183
+ selectedModel || models[0]?.modelPattern || "claude-sonnet-5-5"
184
+ );
185
+ // Keep the id the user will actually send to their provider; the catalog
186
+ // match is only used to pick provider-specific boilerplate.
187
+ const effectiveModelPattern = selectedModel || resolvedModel.modelPattern;
188
+
189
+ // 4. Output Path for Boilerplate File
190
+ let outputPath = options.outputPath?.trim() ?? "";
191
+ if (!outputPath && rl) {
192
+ const answer = await rl.question(
193
+ "\n4. Boilerplate integration file path [default: src/lib/shdw.ts]: "
194
+ );
195
+ outputPath = answer.trim() || "src/lib/shdw.ts";
196
+ }
197
+ if (!outputPath) {
198
+ outputPath = "src/lib/shdw.ts";
199
+ }
200
+
201
+ // 5. Environment File Injection (.env / .env.local)
202
+ const envResult = injectShdwEnvVariables({
203
+ cwd,
204
+ apiKey,
205
+ gridRegion: resolvedRegion.region,
206
+ });
207
+ defaultOutput.write(
208
+ `\n[1/3] ${envResult.createdNew ? "Created" : "Updated"} ${envResult.fileName} (${envResult.filePath})\n`
209
+ );
210
+
211
+ // 6. Boilerplate Code Generation
212
+ const codeResult = generateShdwBoilerplateFile({
213
+ cwd,
214
+ outputPath,
215
+ modelPattern: effectiveModelPattern,
216
+ gridRegion: resolvedRegion.region,
217
+ });
218
+ defaultOutput.write(
219
+ `[2/3] Generated ${codeResult.providerLabel} integration at ${codeResult.relativePath}\n`
220
+ );
221
+
222
+ // 7. Live Connectivity Test (<= 1500ms AbortController timeout)
223
+ let connectivity: ConnectivityTestResult | null = null;
224
+ if (!options.skipPing) {
225
+ defaultOutput.write(
226
+ "[3/3] Testing live connectivity (1500ms timeout guard)...\n"
227
+ );
228
+ connectivity = await testShdwConnectivity({
229
+ apiKey,
230
+ modelPattern: effectiveModelPattern,
231
+ gridRegion: resolvedRegion.region,
232
+ endpoint: options.endpoint,
233
+ timeoutMs: 1500,
234
+ customFetch: options.customFetch,
235
+ });
236
+ defaultOutput.write(
237
+ ` ${connectivity.ok ? "OK:" : "WARN:"} ${connectivity.message}\n`
238
+ );
239
+ }
240
+
241
+ defaultOutput.write(
242
+ `\nSetup complete. Import your wrapped AI client from "./${codeResult.relativePath.replace(/\.ts$/, "")}" to begin tracking Scope 3 carbon & AI-BOM lineage.\n\n`
243
+ );
244
+
245
+ return {
246
+ apiKeyPrefix: apiKey.slice(0, 14),
247
+ gridRegion: resolvedRegion.region,
248
+ modelPattern: effectiveModelPattern,
249
+ envFilePath: envResult.filePath,
250
+ boilerplateFilePath: codeResult.filePath,
251
+ connectivity,
252
+ };
253
+ } finally {
254
+ rl?.close();
255
+ }
256
+ }
257
+
258
+ export async function runCliFromArgv(argv: readonly string[]): Promise<void> {
259
+ const cleaned = argv[0] === "init" ? argv.slice(1) : argv;
260
+ const parsed = parseCliArgs(cleaned);
261
+ if (parsed.help) {
262
+ printHelp();
263
+ return;
264
+ }
265
+ await runInitWizard(parsed);
266
+ }