diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c82cb47..30dbbee 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -57,7 +57,6 @@ jobs: - name: Publish to npm env: NPM_DIST_TAG: ${{ needs.validate.outputs.dist_tag }} - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} run: npm publish --access public --provenance --tag "$NPM_DIST_TAG" github-release: diff --git a/README.md b/README.md index 6d48a92..734bb1d 100644 --- a/README.md +++ b/README.md @@ -43,5 +43,6 @@ npm run check local HTTP server. Their pinned source revision and checksums are recorded in `contracts/source.json`; no live API or Python installation is needed. -Releases run automatically on matching `v*` tags after all checks pass. See -[release setup](https://github.com/energy-tracker/api-client-typescript/blob/main/docs/releasing.md) for the one-time npm configuration and commands. +To release, update the version in `package.json` and `package-lock.json`, merge +into `main`, then push the matching `v*` tag on the merged commit. GitHub Actions +publishes to npm through OIDC after all checks pass. diff --git a/docs/api.md b/docs/api.md index b3734bc..bcc2255 100644 --- a/docs/api.md +++ b/docs/api.md @@ -136,3 +136,5 @@ for local or transport failures) and `apiMessage` (the server's message array). `TimeoutError` represents a client timeout, `NetworkError` a transport failure. Only each endpoint's exact success status is accepted. A caller-triggered abort rejects with the original abort reason rather than an SDK error. +An unreadable HTTP error body keeps its status-specific error class, with the +body failure in `cause`. Invalid entries in the server's message array are ignored. diff --git a/docs/releasing.md b/docs/releasing.md deleted file mode 100644 index e97862d..0000000 --- a/docs/releasing.md +++ /dev/null @@ -1,49 +0,0 @@ -# Releases - -Package: `@energy-tracker/api-client`. Repository: `energy-tracker/api-client-typescript`. - -## One-time setup - -1. Create the public GitHub repository and push this checkout's `main` branch. -2. Ensure the publishing npm account has access to the `energy-tracker` npm scope. - A GitHub organization does not automatically reserve the corresponding npm scope. -3. For the first tag release, add a temporary GitHub Actions secret `NPM_TOKEN` - containing a granular npm token allowed to create/publish the scoped package - without interactive 2FA. Push `v1.0.0` on the reviewed `main` commit using the - tag commands below. The workflow publishes the package and creates its GitHub release. -4. After that initial publication, in the npm package's settings add a GitHub Actions trusted publisher: - organization `energy-tracker`, repository `api-client-typescript`, workflow - `release.yml`, no environment name. Allow direct `npm publish`. -5. Remove the GitHub `NPM_TOKEN` secret and revoke that bootstrap token. Further - releases authenticate through OIDC. - -The [npm trusted publishing documentation](https://docs.npmjs.com/trusted-publishers/) -describes this configuration. Subsequent releases use OIDC with provenance and -need no long-lived npm token in GitHub secrets. The repository must be public for -public npm provenance. The workflow uses GitHub-hosted Ubuntu 24.04 and Node 24. - -## Version and tag - -```sh -npm version 1.1.0 --no-git-tag-version -npm run check -``` - -Commit both `package.json` and `package-lock.json`, review and merge to `main`. -Create the tag on the merged commit, including after a squash merge: - -```sh -git switch main -git pull --ff-only -git tag -a v1.1.0 -m 'Release 1.1.0' -git push origin v1.1.0 -``` - -The release workflow checks that the tag exactly matches the package and lockfile -versions, and that its commit belongs to `main`. It runs the complete CI matrix, -publishes to npm and then creates a GitHub release with generated notes. -Stable versions use npm's `latest` tag; prereleases such as `1.1.0-rc.1` use `next` -and are marked as GitHub prereleases. Versions are explicit; CI does not bump them. - -If npm publication succeeds but GitHub release creation fails, rerun only the -failed job. Published npm versions are immutable; do not move a released tag. diff --git a/package-lock.json b/package-lock.json index 96e07bb..8eca0d6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@energy-tracker/api-client", - "version": "1.0.0", + "version": "1.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@energy-tracker/api-client", - "version": "1.0.0", + "version": "1.0.1", "license": "MIT", "devDependencies": { "@types/node": "^20.0.0", diff --git a/package.json b/package.json index 1d6f4de..3a979c6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@energy-tracker/api-client", - "version": "1.0.0", + "version": "1.0.1", "description": "Typed async client for the Energy Tracker public API", "license": "MIT", "author": "Stefan Nebel", diff --git a/src/transport.ts b/src/transport.ts index 992cc57..f82e9f3 100644 --- a/src/transport.ts +++ b/src/transport.ts @@ -49,10 +49,17 @@ function messages(data: unknown): string[] { if (!data || typeof data !== 'object') return []; const value = (data as Record).message; if (typeof value === 'string') return [value]; - return Array.isArray(value) ? value.map(String) : []; + return Array.isArray(value) + ? value.filter((item): item is string => typeof item === 'string') + : []; } -function httpError(response: Response, data: unknown, expected: number): EnergyTrackerAPIError { - const options = { statusCode: response.status, apiMessage: messages(data) }; +function httpError( + response: Response, + data: unknown, + expected: number, + cause?: unknown, +): EnergyTrackerAPIError { + const options = { statusCode: response.status, apiMessage: messages(data), cause }; switch (response.status) { case 400: return new ValidationError('Bad Request', options); @@ -142,12 +149,12 @@ export class Transport { } const response = await this.#fetch(url, init); if (response.status !== request.status) { - const text = await response.text(); let data: unknown; try { - data = JSON.parse(text); - } catch { - /* HTTP status takes priority over an invalid error body. */ + data = JSON.parse(await response.text()); + } catch (cause) { + // Keep the known HTTP error when its body is invalid or interrupted. + throw httpError(response, undefined, request.status, cause); } throw httpError(response, data, request.status); } diff --git a/tests/client.test.mjs b/tests/client.test.mjs index caa4aea..a6d9bb9 100644 --- a/tests/client.test.mjs +++ b/tests/client.test.mjs @@ -103,23 +103,25 @@ test('network errors retain cause without HTTP status', async () => { }, ); }); -test('timeout covers streaming body after headers and does not retry', async (t) => { - let requests = 0; - const baseUrl = await serve(t, (req, res) => { - requests++; - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.write('['); +for (const status of [200, 429, 503]) { + test(`timeout covers streaming HTTP ${status} body and does not retry`, async (t) => { + let requests = 0; + const baseUrl = await serve(t, (req, res) => { + requests++; + res.writeHead(status, { 'Content-Type': 'application/json' }); + res.write('['); + }); + await assert.rejects( + () => client({ baseUrl, timeout: 0.2 }).devices.listStandard(), + (error) => { + assert.ok(error instanceof api.TimeoutError); + assert.equal(error.statusCode, null); + return true; + }, + ); + assert.equal(requests, 1); }); - await assert.rejects( - () => client({ baseUrl, timeout: 0.2 }).devices.listStandard(), - (error) => { - assert.ok(error instanceof api.TimeoutError); - assert.equal(error.statusCode, null); - return true; - }, - ); - assert.equal(requests, 1); -}); +} test('calculations use their own timeout', async (t) => { const baseUrl = await serve(t, async (req, res) => { await delay(100); @@ -133,29 +135,142 @@ test('calculations use their own timeout', async (t) => { [], ); }); -test('caller cancellation is preserved, including before starting a request', async (t) => { - const controller = new AbortController(); - const reason = new Error('Caller cancelled'); - const baseUrl = await serve(t, (req, res) => { - res.writeHead(200); - res.write('['); - controller.abort(reason); +for (const status of [200, 503]) { + test(`caller cancellation is preserved for HTTP ${status} and before requests`, async (t) => { + const controller = new AbortController(); + const reason = new Error('Caller cancelled'); + const baseUrl = await serve(t, (req, res) => { + res.writeHead(status); + res.write('['); + }); + const apiClient = client({ + baseUrl, + fetch: async (...args) => { + const response = await fetch(...args); + setImmediate(() => controller.abort(reason)); + return response; + }, + }); + await assert.rejects( + () => apiClient.devices.listStandard({ signal: controller.signal }), + (error) => error === reason, + ); + let calls = 0; + await assert.rejects( + () => + client({ + fetch: async () => { + calls++; + }, + }).devices.listVirtual({ signal: controller.signal }), + (error) => error === reason, + ); + assert.equal(calls, 0); + }); +} + +for (const [status, ErrorType] of [ + [400, api.ValidationError], + [401, api.AuthenticationError], + [403, api.ForbiddenError], + [404, api.ResourceNotFoundError], + [409, api.ConflictError], + [429, api.RateLimitError], + [503, api.ServiceUnavailableError], + [500, api.EnergyTrackerAPIError], + [201, api.EnergyTrackerAPIError], +]) { + test(`HTTP ${status} survives a failed response body`, async () => { + const cause = new Error('Response stream disconnected'); + const response = new Response( + new ReadableStream({ + start(stream) { + stream.error(cause); + }, + }), + { + status, + headers: { 'Retry-After': '20' }, + }, + ); + await assert.rejects( + () => client({ fetch: async () => response }).devices.listStandard(), + (error) => { + assert.equal(error.constructor, ErrorType); + assert.equal(error.statusCode, status); + assert.equal(error.cause, cause); + assert.deepEqual(error.apiMessage, []); + if (status === 429) assert.equal(error.retryAfter, 20); + return true; + }, + ); }); +} + +test('invalid message entries cannot mask HTTP status or retry-after', async (t) => { + const baseUrl = await serve(t, (req, res) => + res + .writeHead(429, { + 'Content-Type': 'application/json', + 'Retry-After': '20', + }) + .end( + JSON.stringify({ + message: ['Rate limited', { toString: null }, null, 42, false, ['nested']], + }), + ), + ); await assert.rejects( - () => client({ baseUrl }).devices.listStandard({ signal: controller.signal }), - (error) => error === reason, + () => client({ baseUrl }).devices.listStandard(), + (error) => { + assert.ok(error instanceof api.RateLimitError); + assert.equal(error.statusCode, 429); + assert.equal(error.retryAfter, 20); + assert.deepEqual(error.apiMessage, ['Rate limited']); + return true; + }, + ); +}); + +test('an interrupted success body remains a network error', async () => { + const cause = new Error('Response stream disconnected'); + const response = new Response( + new ReadableStream({ + start(stream) { + stream.error(cause); + }, + }), + { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }, ); - let calls = 0; await assert.rejects( - () => - client({ - fetch: async () => { - calls++; - }, - }).devices.listVirtual({ signal: controller.signal }), - (error) => error === reason, + () => client({ fetch: async () => response }).devices.listStandard(), + (error) => { + assert.ok(error instanceof api.NetworkError); + assert.equal(error.statusCode, null); + assert.equal(error.cause, cause); + return true; + }, + ); +}); + +test('a truncated HTTP error from the server keeps its status', async (t) => { + const baseUrl = await serve(t, (req, res) => { + res.writeHead(503, { 'Content-Type': 'application/json', 'Content-Length': '1000' }); + res.write('{"message":'); + setTimeout(() => res.destroy(), 20); + }); + await assert.rejects( + () => client({ baseUrl }).devices.listStandard(), + (error) => { + assert.ok(error instanceof api.ServiceUnavailableError); + assert.equal(error.statusCode, 503); + assert.ok(error.cause instanceof Error); + return true; + }, ); - assert.equal(calls, 0); }); const point = { date: '2026-09-01T00:00:00Z',