@nlxai/cli 1.2.2-alpha.6 → 1.2.2-alpha.8

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/README.md CHANGED
@@ -17,6 +17,8 @@ Intereact with NLX from the command line
17
17
 
18
18
  Options:
19
19
  -h, --help display help for command
20
+ -v, --verbose enable verbose logging
21
+ -V, --version show program version
20
22
 
21
23
  Commands:
22
24
  auth Authentication and user management
@@ -0,0 +1,59 @@
1
+ import { Command } from "commander";
2
+ import * as fs from "fs";
3
+ import { fetchManagementApi } from "../utils/index.js";
4
+ export const fetchCommand = new Command("fetch")
5
+ .description("Perform an authenticated request to the management API")
6
+ .argument("<method>", "HTTP method (GET, POST, PUT, DELETE, etc.)")
7
+ .argument("<path>", "API path (e.g. /models)")
8
+ .argument("[body]", "Request body as JSON string, name of a JSON file or -- for Standard Input")
9
+ .option("-p, --paginate", "Enable pagination", false)
10
+ .action(async (method, apiPath, body, opts) => {
11
+ if (body === "--") {
12
+ // Read from stdin
13
+ body = "";
14
+ process.stdin.setEncoding("utf8");
15
+ for await (const chunk of process.stdin)
16
+ body += chunk;
17
+ try {
18
+ body = JSON.parse(body);
19
+ }
20
+ catch (ed) {
21
+ console.error("Invalid JSON string from stdin: " + ed);
22
+ process.exit(1);
23
+ }
24
+ }
25
+ else if (body != null) {
26
+ // Try to parse as file path or JSON string
27
+ try {
28
+ if (fs.existsSync(body)) {
29
+ body = JSON.parse(fs.readFileSync(body, "utf8"));
30
+ }
31
+ else {
32
+ body = JSON.parse(body);
33
+ }
34
+ }
35
+ catch {
36
+ console.error("Invalid JSON string or file path: " + body);
37
+ process.exit(1);
38
+ }
39
+ }
40
+ let result = await fetchManagementApi(apiPath +
41
+ (opts.paginate
42
+ ? apiPath.includes("?")
43
+ ? "&size=1000"
44
+ : "?size=2&page=0"
45
+ : ""), method.toUpperCase(), body);
46
+ let agg;
47
+ if (opts.paginate) {
48
+ const key = Object.keys(result).filter((k) => k !== "nextPageId")[0];
49
+ agg = result[key];
50
+ while (result.nextPageId) {
51
+ result = await fetchManagementApi(apiPath + `?pageId=${result.nextPageId}`, method.toUpperCase(), body);
52
+ agg.push(...result[key]);
53
+ }
54
+ }
55
+ else {
56
+ agg = result;
57
+ }
58
+ console.log(JSON.stringify(agg, null, 2));
59
+ });
@@ -0,0 +1 @@
1
+ export declare const loginCommand: import("commander").Command;
@@ -0,0 +1,145 @@
1
+ import { Command } from "commander";
2
+ import * as fs from "fs";
3
+ import open from "open";
4
+ import * as os from "os";
5
+ import * as path from "path";
6
+ import { consola } from "consola";
7
+ import keytar from "keytar";
8
+ const ACCOUNTS_PATH = path.join(os.homedir(), ".nlx-cli-auth.json");
9
+ async function saveTokens(account, tokenData) {
10
+ await keytar.setPassword("nlx-cli", account, JSON.stringify(tokenData));
11
+ }
12
+ async function loadTokens() {
13
+ try {
14
+ const data = fs.readFileSync(ACCOUNTS_PATH, "utf8");
15
+ const accounts = JSON.parse(data);
16
+ if (accounts.currentAccount) {
17
+ const res = await keytar.getPassword("nlx-cli", accounts.currentAccount);
18
+ if (res)
19
+ return [accounts.currentAccount, JSON.parse(res)];
20
+ }
21
+ throw new Error("No tokens found for current account");
22
+ }
23
+ catch {
24
+ throw new Error("Failed to load tokens");
25
+ }
26
+ }
27
+ async function refreshTokenIfNeeded() {
28
+ let account, tokens;
29
+ try {
30
+ [account, tokens] = await loadTokens();
31
+ }
32
+ catch (error) {
33
+ consola.error("Error loading tokens");
34
+ return null;
35
+ }
36
+ if (!tokens || !tokens.refresh_token)
37
+ return null;
38
+ // Check expiry
39
+ const now = Math.floor(Date.now() / 1000);
40
+ if (tokens.expires_in &&
41
+ tokens.obtained_at &&
42
+ now < tokens.obtained_at + tokens.expires_in - 60) {
43
+ consola.debug("Access token is still valid.");
44
+ return tokens.access_token;
45
+ }
46
+ consola.debug("Access token is expired or invalid. Refreshing...");
47
+ // Refresh
48
+ const res = await fetch(`https://${AUTH0_DOMAIN}/oauth/token`, {
49
+ method: "POST",
50
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
51
+ body: new URLSearchParams({
52
+ grant_type: "refresh_token",
53
+ client_id: CLIENT_ID,
54
+ refresh_token: tokens.refresh_token,
55
+ }),
56
+ });
57
+ const newTokens = await res.json();
58
+ if (newTokens.access_token) {
59
+ newTokens.refresh_token = newTokens.refresh_token || tokens.refresh_token;
60
+ newTokens.obtained_at = now;
61
+ await saveTokens(account, newTokens);
62
+ return newTokens.access_token;
63
+ }
64
+ return null;
65
+ }
66
+ const AUTH0_DOMAIN = process.env.AUTH0_DOMAIN || "nlxdev.us.auth0.com"; // e.g. 'dev-xxxxxx.us.auth0.com'
67
+ const CLIENT_ID = process.env.AUTH0_CLIENT_ID || "A0qluq7wJQjFjMLle9pvrWWaVHM1QHE3";
68
+ const AUDIENCE = process.env.AUTH0_AUDIENCE || "https://nlxdev.us.auth0.com/api/v2/";
69
+ export const loginCommand = new Command("login")
70
+ .description("Authenticate with NLX")
71
+ .action(async () => {
72
+ // Step 1: Start device flow
73
+ const deviceCodeRes = await fetch(`https://${AUTH0_DOMAIN}/oauth/device/code`, {
74
+ method: "POST",
75
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
76
+ body: new URLSearchParams({
77
+ client_id: CLIENT_ID,
78
+ scope: "openid profile email offline_access",
79
+ audience: AUDIENCE,
80
+ }),
81
+ });
82
+ const deviceCodeData = await deviceCodeRes.json();
83
+ open(deviceCodeData.verification_uri_complete);
84
+ consola.box(`Please visit ${deviceCodeData.verification_uri_complete} and enter code: ${deviceCodeData.user_code}`);
85
+ // Step 2: Poll for token
86
+ let tokenData;
87
+ while (!tokenData) {
88
+ await new Promise((r) => setTimeout(r, deviceCodeData.interval * 1000));
89
+ const tokenRes = await fetch(`https://${AUTH0_DOMAIN}/oauth/token`, {
90
+ method: "POST",
91
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
92
+ body: new URLSearchParams({
93
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
94
+ device_code: deviceCodeData.device_code,
95
+ client_id: CLIENT_ID,
96
+ }),
97
+ });
98
+ const resData = await tokenRes.json();
99
+ if (resData.access_token) {
100
+ tokenData = resData;
101
+ }
102
+ else if (resData.error !== "authorization_pending") {
103
+ consola.error("Error:", resData.error_description || resData.error);
104
+ return;
105
+ }
106
+ }
107
+ // Step 3: Fetch user object
108
+ let accounts = { currentAccount: null, accounts: [] };
109
+ if (fs.existsSync(ACCOUNTS_PATH)) {
110
+ const data = fs.readFileSync(ACCOUNTS_PATH, "utf8");
111
+ accounts = JSON.parse(data);
112
+ }
113
+ const userRes = await fetch(`https://${AUTH0_DOMAIN}/userinfo`, {
114
+ headers: {
115
+ Authorization: `Bearer ${tokenData.access_token}`,
116
+ },
117
+ });
118
+ const userData = await userRes.json();
119
+ if (!accounts.currentAccount) {
120
+ await fs.promises.writeFile(ACCOUNTS_PATH, JSON.stringify({
121
+ currentAccount: userData.email,
122
+ accounts: [userData.email],
123
+ }));
124
+ }
125
+ else if (accounts.currentAccount !== userData.email) {
126
+ accounts.currentAccount = userData.email;
127
+ await fs.promises.writeFile(ACCOUNTS_PATH, JSON.stringify({
128
+ currentAccount: userData.email,
129
+ accounts: [userData.email, ...accounts.accounts],
130
+ }));
131
+ }
132
+ // Step 4: Store token securely
133
+ tokenData.obtained_at = Math.floor(Date.now() / 1000);
134
+ await saveTokens(userData.email, tokenData);
135
+ consola.success("Login successful! Access token stored securely.");
136
+ });
137
+ // Example usage: get a valid access token
138
+ export async function ensureToken() {
139
+ const accessToken = await refreshTokenIfNeeded();
140
+ if (!accessToken) {
141
+ consola.error("Not authenticated. Please run 'login' first.");
142
+ process.exit(1);
143
+ }
144
+ return accessToken;
145
+ }
@@ -0,0 +1,26 @@
1
+ import { Command } from "commander";
2
+ import { compile } from "json-schema-to-typescript";
3
+ import * as fs from "fs";
4
+ import * as path from "path";
5
+ import { fetchManagementApi } from "../utils/index.js";
6
+ export const modalitiesCommand = new Command("modalities")
7
+ .description("Fetch modalities and generate TypeScript interfaces")
8
+ .option("-o, --out <file>", "Output TypeScript file", "modalities-types.d.ts")
9
+ .action(async (opts) => {
10
+ const data = await fetchManagementApi(`models`);
11
+ // Generate TypeScript interfaces for each modelId
12
+ let output = "// Auto-generated from NLX\n// Please do not edit manually\n\n";
13
+ for (const item of data.items) {
14
+ const name = item.modelId.replace(/[^a-zA-Z0-9_]/g, "");
15
+ const schema = item.schema;
16
+ const ts = await compile(schema, name, {
17
+ bannerComment: "",
18
+ additionalProperties: false,
19
+ });
20
+ output += ts + "\n";
21
+ }
22
+ // Write to file specified by flag or default
23
+ const outPath = path.resolve(process.cwd(), opts.out);
24
+ fs.writeFileSync(outPath, output);
25
+ console.log(`TypeScript interfaces written to ${outPath}`);
26
+ });
@@ -0,0 +1,4 @@
1
+ const foot = (f) => {
2
+ return Math.ceil(f.gramsCO2 ?? 0);
3
+ };
4
+ export {};
package/lib/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/lib/index.js CHANGED
@@ -6,7 +6,8 @@ import { httpCommand } from "./commands/http.js";
6
6
  import { testCommand } from "./commands/test.js";
7
7
  import { consola } from "consola";
8
8
  import { readFileSync } from "fs";
9
- const packageJson = JSON.parse(readFileSync("../../package.json", "utf-8"));
9
+ import { resolve } from "path";
10
+ const packageJson = JSON.parse(readFileSync(resolve(import.meta.dirname, "../package.json"), "utf-8"));
10
11
  program.description("Intereact with NLX from the command line");
11
12
  program
12
13
  .option("-v, --verbose", "enable verbose logging")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nlxai/cli",
3
- "version": "1.2.2-alpha.6",
3
+ "version": "1.2.2-alpha.8",
4
4
  "description": "Tools for integrating with NLX apps",
5
5
  "keywords": [
6
6
  "NLX",
@@ -58,5 +58,5 @@
58
58
  "@vitest/ui": "^3.2.4",
59
59
  "vitest": "^3.2.4"
60
60
  },
61
- "gitHead": "b69e0d6fe441fe23b7193023f34e24d6c429590e"
61
+ "gitHead": "2829feb4c0a570906493c8f6d8671b14886d705c"
62
62
  }