Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ jobs:
persist-credentials: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: '24.22.0'
node-version: '24.22.2'
cache: npm
- run: npm install --global npm@11.19.1 --ignore-scripts --no-audit --no-fund
- run: npm ci --ignore-scripts --no-audit --no-fund
Expand Down Expand Up @@ -79,7 +79,7 @@ jobs:
persist-credentials: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7
with:
node-version: '24.22.0'
node-version: '24.22.2'
- run: npm install --global npm@11.19.1 --ignore-scripts --no-audit --no-fund
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## 1.1.1

- Preserve HTTP and application error codes in CLI failures, with actionable hints for common account and service errors.

## 1.1.0

- Add account balance, product catalog and supported-country queries.
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Build the archive after checks pass, then install it from a separate application

```sh
npm pack
npm install /path/to/nstdata-proxy-sdk-node/nstdata-ai-proxy-1.1.0.tgz
npm install /path/to/nstdata-proxy-sdk-node/nstdata-ai-proxy-1.1.1.tgz
```

Package checks use empty npm caches to verify the exact tarball and default npm installation through a loopback registry. They verify the standalone npx/global CLI and run installed-client/CLI regressions, compile TypeScript declarations, and execute the documented Node.js command and guide operations against loopback API fixtures. Markdown checks cover all public documents; package checks execute the quick start and guide operations. Pass a previously built tarball path after `npm run check:package --` to validate that exact archive. Checks verify bilingual programs, documentation links and package bytes; they do not prove public npm availability or deployed API compatibility.
Expand Down
6 changes: 5 additions & 1 deletion docs/guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@ File mode `0600` restricts access on POSIX systems; on Windows, use a directory

Set `NSTDATA_API_TOKEN` in the environment or an explicit env file; interactive mode can prompt for it without echoing or storing it. `NSTDATA_TEAM_ID` is optional team context. `NSTDATA_API_BASE_URL` is an advanced API origin override, not a normal setup requirement or a proxy URL. Defaults use the official API.

Default stdout contains selection metadata and `count`; `saved: true` confirms file export. Exported JSON adds a `proxies` array. Errors go to stderr as `{ error: { code, message } }`. Exit codes: 0 success, 1 API/setup failure, 2 input/configuration assistance, 130 interruption. API configuration errors returned as `ProxyAPIError` use exit 1.
Default stdout contains selection metadata and `count`; `saved: true` confirms file export. Exported JSON adds a `proxies` array.

Errors go to stderr as `{ error: { code, message } }`, with `statusCode` and integer `applicationCode` when available. Common authentication, permission, rate-limit and service errors also include a short `hint`.

Exit codes: 0 success, 1 API/setup failure, 2 input/configuration assistance, 130 interruption. API configuration errors returned as `ProxyAPIError` use exit 1.

## Convenient proxy setup

Expand Down
6 changes: 5 additions & 1 deletion docs/guide_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@

`NSTDATA_API_TOKEN` 来自环境变量或显式指定的环境文件;交互模式可隐藏输入,不回显、不保存。`NSTDATA_TEAM_ID` 是可选团队上下文。`NSTDATA_API_BASE_URL` 仅用于高级 API 服务地址覆盖,不是常规必填参数,也不是代理 URL;默认使用官方 API。

默认 stdout 包含选择元数据和 `count`;`saved: true` 表示文件已保存。导出的 JSON 另含 `proxies` 数组。错误以 `{ error: { code, message } }` 写入 stderr。退出码:0 成功,1 API/准备失败,2 命令行输入需修正,130 中断;以 `ProxyAPIError` 返回的 API 配置错误使用退出码 1。
默认 stdout 包含选择元数据和 `count`;`saved: true` 表示文件已保存。导出的 JSON 另含 `proxies` 数组。

错误以 `{ error: { code, message } }` 写入 stderr,已知时附带 `statusCode` 和整数 `applicationCode`;常见认证、权限、限流和服务错误另有简短的 `hint`。

退出码:0 成功,1 API/准备失败,2 命令行输入需修正,130 中断;以 `ProxyAPIError` 返回的 API 配置错误使用退出码 1。

## 便捷出号

Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@nstdata-ai/proxy",
"version": "1.1.0",
"version": "1.1.1",
"description": "Node.js client for Nstdata proxy generation and customer channel APIs",
"type": "module",
"exports": {
Expand Down
17 changes: 16 additions & 1 deletion src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,20 @@ class InputError extends Error {
constructor(code, message) { super(message); this.code = code; }
}

function apiDiagnostics(error) {
const details = {};
if (Number.isInteger(error.statusCode) && error.statusCode >= 100 && error.statusCode <= 599)
details.statusCode = error.statusCode;
if (Number.isSafeInteger(error.applicationCode)) details.applicationCode = error.applicationCode;
if (error.code !== 'HTTP_ERROR' && error.code !== 'API_ERROR') return details;
const status = error.code === 'API_ERROR' ? details.applicationCode : details.statusCode;
if (status === 401) details.hint = 'Check NSTDATA_API_TOKEN and its account or team context.';
else if (status === 403) details.hint = 'Check the API key permissions and account or team access.';
else if (status === 429) details.hint = 'The API rate limit was reached. Wait before starting another command.';
else if (status >= 500 && status <= 599) details.hint = 'The API returned a service error. Check its status before another command.';
return details;
}

async function question(prompt, hidden = false) {
const output = hidden ? new Writable({ write(_chunk, _encoding, done) { done(); } }) : process.stderr;
const reader = createInterface({ input: process.stdin, output, terminal: true });
Expand Down Expand Up @@ -188,6 +202,7 @@ main().catch(error => {
if (controller.signal.aborted && !(error instanceof ProxyAPIError)) error = new ProxyAPIError('ABORTED');
const known = error instanceof InputError || error instanceof ProxyAPIError;
console.error(JSON.stringify({ error: { code: known ? error.code : 'INVALID_INPUT',
message: known ? error.message : 'Invalid command-line input. Run nstdata-proxy --help for usage.' } }));
message: known ? error.message : 'Invalid command-line input. Run nstdata-proxy --help for usage.',
...(error instanceof ProxyAPIError ? apiDiagnostics(error) : {}) } }));
process.exitCode = controller.signal.aborted || error.code === 'ABORTED' ? 130 : error instanceof ProxyAPIError ? 1 : 2;
});
49 changes: 49 additions & 0 deletions test/cli.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,55 @@ test('CLI previews are read-only and confirmed generation hides credentials by d
assert.equal(f.state.requests.filter(row => row.path.endsWith('/proxies')).length, 1);
});

test('CLI preserves safe API diagnostics and stops after a failed account check', async t => {
for (const scenario of [
{ status: 401, hint: /NSTDATA_API_TOKEN/ },
{ status: 403, hint: /permissions/ },
{ status: 429, hint: /rate limit/ },
{ status: 503, hint: /service/ },
{ status: 200, applicationCode: 403, expectedApplicationCode: 403, hint: /permissions/ },
{ status: 201, applicationCode: 403, expectedApplicationCode: 403, hint: /permissions/ },
{ status: 200, applicationCode: 10001, expectedApplicationCode: 10001 },
{ status: 200, applicationCode: 1.5 },
]) {
const f = await fixture(t, { handle(_req, res) {
res.writeHead(scenario.status, { 'content-type': 'application/json' });
res.end(JSON.stringify({ err: true, code: scenario.applicationCode ?? 403,
message: `${key} http://fixture:password@gateway.invalid/`, data: {} }));
return true;
} });
const result = await cli(['--yes', '--json'], { NSTDATA_API_TOKEN: key, NSTDATA_API_BASE_URL: f.baseUrl });
assert.equal(result.code, 1, result.stderr);
assert.equal(result.stdout, '');
const error = JSON.parse(result.stderr).error;
assert.equal(error.code, scenario.status < 300 ? 'API_ERROR' : 'HTTP_ERROR');
assert.equal(error.statusCode, scenario.status);
assert.equal(error.applicationCode, scenario.expectedApplicationCode);
if (scenario.hint) assert.match(error.hint, scenario.hint);
else assert.equal(error.hint, undefined);
assert.doesNotMatch(result.stderr, /quickstart-test-key|fixture:password|gateway\.invalid/);
assert.equal(f.state.requests.length, 1);
assert.ok(f.state.requests.every(row => row.method === 'GET' && row.path.endsWith('/user/info')));
}
});

test('CLI retains uncertain-creation diagnostics without suggesting or performing a retry', async t => {
const f = await fixture(t, { handle(req, res, url) {
if (req.method !== 'POST' || !url.pathname.endsWith('/channel')) return;
res.writeHead(503); res.end(key); return true;
} });
const result = await cli(['--yes', '--json'], { NSTDATA_API_TOKEN: key, NSTDATA_API_BASE_URL: f.baseUrl });
assert.equal(result.code, 1, result.stderr);
const error = JSON.parse(result.stderr).error;
assert.equal(error.code, 'CHANNEL_CREATION_UNCERTAIN');
assert.equal(error.statusCode, 503);
assert.equal(error.hint, undefined);
assert.match(error.message, /Check existing channels/);
assert.equal(f.state.requests.filter(row => row.method === 'POST').length, 1);
assert.equal(f.state.requests.filter(row => row.path.endsWith('/proxies')).length, 0);
assert.doesNotMatch(result.stdout + result.stderr, /quickstart-test-key/);
});

test('connection export is explicit, private, non-overwriting and separate from API-key storage', async t => {
const dir = await mkdtemp(join(tmpdir(), 'nstdata-proxy-cli-'));
t.after(() => rm(dir, { recursive: true, force: true }));
Expand Down
Loading